# Include multiple PDF documents and create bookmark to first page

Suppose I have 4 PDFs: 1.pdf, 2.pdf, 3.pdf, 4.pdf

Now I want to combine them in the given order. I also want to create bookmarks to their first pages in the combined PDF.

The number of pages in any of the component PDFs is variable (They refer to different PDFs at different runtime created by a python program). The number of pages in any of them could become 1.

My search resulted in many posts but all of them assumes that the number of pages in the component PDF document is known beforehand (implicitly).

How that could be done? Any help will be highly appreciated.

Here are 4 sample files:

1. 1.pdf (1 page):

\documentclass{article}
\usepackage{lipsum}
\begin{document}
\section{First section}
\lipsum[1]
\end{document}

2. 2.pdf (3 pages):

\documentclass{article}
\usepackage{lipsum}
\begin{document}
\section{Second section}
\lipsum[2-15]
\end{document}

3. 3.pdf (5 pages):

\documentclass{article}
\usepackage{lipsum}
\begin{document}
\section{Third section}
\lipsum[16-40]
\end{document}

4. 4.pdf (10 pages):

\documentclass{article}
\usepackage{lipsum}
\begin{document}
\section{Fourth section}
\lipsum[1-50]
\end{document}


From this we can concatenate the four files using pdfpages and insert bookmarks to each files' first page using bookmark:

\documentclass{article}
\usepackage{lipsum,bookmark,pdfpages}
\begin{document}
\section{A section}
\lipsum[1-3]

\bookmark[dest={1.pdf.1}]{1.pdf}
\bookmark[dest={2.pdf.1}]{2.pdf}
\bookmark[dest={3.pdf.1}]{3.pdf}
\bookmark[dest={4.pdf.1}]{4.pdf}

\end{document}


Using \includepdf[link]{<file>} creates hyperlink destinations of the form <file>.<page number>, which is then used in the destination key for \bookmark to link to the first page.