[Tex/LaTex] Insert external PDF pages with adapted size, position and margins

pdfpages

I'm using the changepage package to adapt my pages as illustrated in this figure:

enter image description here

The paper size is A4 and the page size is B5 (first boarder). Within the B5 region, margins are set up as shown in the figure. Now I want to insert several pages from another pdf document with the pdfpages package:

enter image description here

The paper size is A4 and the margins are set up as shown in the figure. Now my question: is there a way to include these pages in my document and adapt the page size, position and margins to the ones shown in the first figure?

Best Answer

  • The included pages have a different aspect ratio (more width, less height). Therefore it is not possible to have the same margins unless the pages are distorted.

  • You can run the external PDF file through pdfcrop to get a PDF file without white margins. That makes the next steps/calculations easier.

  • Since the included page should fit into the text body and also the page layout has different margins for odd and even pages, \includegraphics might be easier to use, e.g.:

    \noindent
    \includegraphics[
        page=1,
        width=\textwidth,
        height=\textheight,
        keepaspectratio
    ]{external.pdf}
    \vfill
    \newpage
    

    Because of the larger width, the included page will be shorter in height than the normal text body.

  • The margin can be adjusted with option trim (can also be used with \includepdf). Positive values put the bounding box for TeX inside the image, negative values outside. If clipping (option clip) is not used, the cropped areas will show in the final output. That trick can be used for the top margin to get the header line of the included page above the text body, e.g.:

    \includegraphics[
      page=1,
      width=\textwidth,
      height=\textheight,
      keepaspectratio,
      trim=0 0 0 20pt,
    ]{external.pdf}
    

Automation

Both pdfTeX and LuaTeX knows \pdflastimagepages that contains the number of pages of the last included file. That can be used to automate the page inclusion via \includegraphics, e.g.:

\documentclass{article}
\usepackage{graphicx}

\makeatletter
\newcounter{imagepage}
\newcommand*{\foreachpage}[2]{%
  \begingroup
    \sbox0{\includegraphics{#1}}%
    \xdef\foreachpage@num{\the\pdflastximagepages}%
  \endgroup
  \setcounter{imagepage}{0}%
  \@whilenum\value{imagepage}<\foreachpage@num\do{%
    \stepcounter{imagepage}%
    #2\relax
  }%
}
\makeatother

\begin{document}
% image file is `example.pdf'
\foreachpage{example}{%
  \newpage   
  \begingroup 
    \centering
    \includegraphics[
      page=\value{imagepage},
      width=\textwidth,  
      height=\textheight,
      keepaspectratio,
    ]{example}%
    \newpage
  \endgroup
}
\end{document}