Skip to content

Instantly share code, notes, and snippets.

@doraTeX
Last active April 22, 2023 06:05
Show Gist options
  • Save doraTeX/99366548d6bf8f683328caf09accc74c to your computer and use it in GitHub Desktop.
Save doraTeX/99366548d6bf8f683328caf09accc74c to your computer and use it in GitHub Desktop.
LaTeX package to get the number of pages in a given PDF file
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{countpdfpages}[2023/04/19 v0.1]
\RequirePackage{iftex}
\newcount\PDFPageCount
\newif\if@countpdfpages@pagenumread
\def\CountPDFPages#1{%
\IfFileExists{#1}{%
\ifluatex
\PDFPageCount=\directlua{tex.print(pdfe.getnofpages(pdfe.open('#1')))}\relax
\else\ifxetex
\PDFPageCount=\XeTeXpdfpagecount"#1"\relax
\else\ifpdftex
\pdfximage{#1}%
\PDFPageCount=\pdflastximagepages
\else
\immediate\openin\@inputcheck="|extractbb -O #1"\relax
\@countpdfpages@pagenumreadtrue
\loop
\catcode`\%=11\relax
\read\@inputcheck to\@tempa
\catcode`\%=14\relax
\ifeof\@inputcheck
\@pagenumreadfalse
\else
\expandafter\@CountPDFPages\expandafter{\@tempa}%
\fi
\if@countpdfpages@pagenumread\repeat
\immediate\closein\@inputcheck
\fi\fi\fi
}{%
\@latex@error{NOT FOUND: #1}%
}%
}
\catcode`\%=11
\def\@CountPDFPages#1{\@@CountPDFPages #1%%Pages:\relax}
\def\@@CountPDFPages #1%%Pages:#2\relax{\def\@tempb{#1}\relax
\ifx\@tempb\@empty
\@@@CountPDFPages#2\relax
\@countpdfpages@pagenumreadfalse
\fi
}
\def\@@@CountPDFPages#1 %%Pages:\relax{\PDFPageCount=#1\relax}
\catcode`\%=14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment