使用 java PDFBox 将一页源 pdf 复制(或重复)到另一个 pdf

Copy(or repeat) a page of source pdf into another pdf using java PDFBox

我有一个 template.pdf,它有页眉和页脚(有些 text/image)。我正在生成一个包含其他数据的新 pdf(比如 result.pdf)。我需要在 result.pdf 的每一页上 copy/repeat template.pdf。所以基本上 template.pdf 将在 result.pdf.

的每一页上充当页眉和页脚

问题是 template.pdf 只出现在 result.pdf 的第一页。我的 result.pdf 可以是任意 'n' 页数。

public class templateTest {

 public static void main(String[] args) throws IOException { 
   File file = new File("template.pdf");
   PDDocument mainDocument = PDDocument.load(file);     

    PDPage myPage = mainDocument.getPage(0);
    PDPageContentStream contentStream = new PDPageContentStream(mainDocument, myPage, AppendMode.APPEND, true);

    contentStream.beginText();
    // Some text
    // Table 1 (Depending on table 1 size, pdf pages will increase) 

    contentStream.endText();
    contentStream.close();

    mainDocument.save("result.pdf");
    mainDocument.close();
 }
}

我已经回答了我自己的问题。 Tilman Hausherr 为我指明了正确的方向。

public class templateTest {

 public static void main(String[] args) throws IOException { 

   File file = new File("template.pdf");
   PDDocument templatePdf = PDDocument.load(file);
   PDDocument mainDocument = new PDDocument();     

   PDPage myPage = new PDPage();
    mainDocument.addPage(myPage);
   PDPageContentStream contentStream = new PDPageContentStream(mainDocument, myPage, AppendMode.APPEND, true);

   contentStream.beginText();
   // Some text
  // Table 1 (Depending on table 1 size, pdf pages will increase) 

  contentStream.endText();
  contentStream.close();

  // Process of imposing a layer begins here
  PDPageTree destinationPages = mainDocument.getDocumentCatalog().getPages();

  LayerUtility layerUtility = new LayerUtility(mainDocument);

  PDFormXObject firstForm = layerUtility.importPageAsForm(templatePDF, 0);

  AffineTransform affineTransform = new AffineTransform();

  PDPage destPage = destinationPages.get(0);

  layerUtility.wrapInSaveRestore(destPage);
  layerUtility.appendFormAsLayer(destPage, firstForm, affineTransform, "external page");

  mainDocument.save("result.pdf");
  mainDocument.close();
 }
}