Wednesday, 1 September 2010

Joining and including PDFs in LaTeX

Have you ever wanted to join a set of separated PDFs together? Maybe a book broken into chapters or sections? There's a useful package that makes this easy with LaTeX: pdfpages. As far as I can tell, it's included in most LaTeX distributions. You can find the complete documentation at the CTAN entry but basic use is simple.

Basic Use

Include the package by placing the line

\usepackage{pdfpages}

in your document's preamble i.e. before \begin{document}. Then, where you want a PDF to appear, put the line

\includepdf{file.pdf}

where file.pdf is the relevant file. If you only want to include pages x through y, use

\includepdf[pages=x-y]{file.pdf}

instead. If you omit x and y completely it includes the entire document. Note that when you compile, you have to compile straight to PDF: as far as I can tell, this won't work if you compile to DVI or PS first.

The main use I have for this is to join files that represent parts of a single document back together. I come across such situations often in my searches for lecture notes and other free materials. I now just a have a single LaTeX file with a string of includepdf's that I adjust each time, compile and then rename the output.

Example

As a part-worked example, here's how I joined the obsolete Numerical Recipes in Fortran 77, Second Edition, into a single (monstrous) PDF. The second edition of NR is available free for C, Fortran 77 and Fortran 90. The PDFs are separated into sections: each file in the F77 version is labeled fc-s.pdf, where c is the chapter number and s is the section number. Beyond the introductory materials, many sections don't start on new pages so some pages are doubled up. I included each file with pdfpages and specified the page range to skip the first pages of sections that don't start on new pages. The result is a LaTeX file that looks like this:

\documentclass{article}
\usepackage{pdfpages}

\begin{document}

\includepdf[pages=-]{f0-0.pdf}
\includepdf[pages=-]{f0-1.pdf}
\includepdf[pages=-]{f0-2.pdf}
\includepdf[pages=-]{f1-0.pdf}
\includepdf[pages=2-]{f1-1.pdf}
\includepdf[pages=2-]{f1-2.pdf}
\includepdf[pages=-]{f2-0.pdf}
\includepdf[pages=2-]{f2-1.pdf}
...

\end{document}

I compile it with pdflatex and now have NR F77 in a single file for reference.

No comments:

Post a Comment