5

I tried all the answers I could find about this topic, and can't get something to work.

This MWE works OK, but only in pdflatex, since \pdfximage do not work in lualatex.

\documentclass[12pt]{article}%
\usepackage{graphicx}
\begin{document}
\pdfximage{index.pdf}%
\the\pdflastximagepages
\end{document}

Answers in Get number of pages of external PDF

do not work, here is the code from the above link:

\documentclass{article}

\newcommand*{\pdfnumberofpages}[1]{%
  \directlua{%
    local doc = epdf.open("\luatexluaescapestring{#1}")
    local pages
    if (doc) then
      pages = doc:getCatalog():getNumPages()
    else
      pages = 0
    end
    tex.write(pages)
  }%
}

\begin{document}
Number of pages: \pdfnumberofpages{index.pdf}
\end{document}

Now, lulatex foo.tex gives

(/usr/local/texlive/2019/texmf-dist/tex/latex/base/size10.clo)) (./foo.aux)
! Undefined control sequence.
\pdfnumberofpages ...open("\luatexluaescapestring
                                                  {#1}") local pages if (doc...

l.17 Number of pages: \pdfnumberofpages{test.pdf}

What is the correct way to obtain the number of pdf pages of external PDF file using lualatex ?

Using TL 2019 on Linux.

1
  • The linked answer is from 2014 which was when LuaTeX was still in beta. Nov 29, 2019 at 0:20

2 Answers 2

7

The pdftex primitives are not gone, they have only been renamed: \pdfximage is \saveimageresource, and \pdflastximagepages is \lastsavedimageresourcepages. So:

\documentclass[12pt]{article}%
\usepackage{graphicx}
\begin{document}
\saveimageresource{index.pdf}%
\the\lastsavedimageresourcepages
\end{document}

Or you could load the luatex85 package, and then use the pdftex primitives, so that the document compiles with both pdflatex and lualatex.

2
  • What would be the the best way to extract this value into lua? token.get_macro('lastsavedimageresourcepages') returns nil Oct 10, 2023 at 17:37
  • @likethevegetable local p = "\the\lastsavedimageresourcepages" ? Or use the pdfe library as per Henri's alternative answer.
    – Robert
    Oct 11, 2023 at 0:58
6

The epdf library (based on poppler) has been replaced by the pdfe library (based on pplib). Further you did not define \luatexluaescapestring, you must have meant \luaescapestring.

\documentclass{article}

\newcommand*{\pdfnumberofpages}[1]{%
  \directlua{%
    local pages = 0
    local doc = pdfe.open("\luaescapestring{#1}")
    if doc then
      pages = pdfe.getnofpages(doc)
      pdfe.close(doc)
    end
    tex.write(pages)
  }%
}

\begin{document}
Number of pages: \pdfnumberofpages{index.pdf}
\end{document}
1
  • 1
    Oh, I thought this was about the Lua end. Nevermind, I'll leave it here for future readers. Nov 29, 2019 at 9:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .