slamek10
slamek10

Reputation: 93

itext7 - adding content from existing PDF to a new one

I'm trying to add some content to my PDF document to the first page of the document. What would be appropriate way of doing this?

At the moment my code works, but it adds(inserts) a new page before the first page of my document. What could be used here insted of the

    PdfPage page = pdf.addNewPage(1, PageSize.A4);

so the content from the document I'm reading is added to the existing first page as content and not as a new page

  public static void addContentToFirstPage(String inputFilePath,String filePath) throws IOException, DocumentException {

      File inFile = new File(inputFilePath);
      File outFile = new File(inputFilePath + "_numbering.pdf");

      PdfDocument pdf = new PdfDocument(new PdfReader(inFile), new PdfWriter(outFile));
      PdfDocument origPdf = new PdfDocument(new PdfReader(filePath));

      PdfPage origPage = origPdf.getPage(1);
      Rectangle orig = origPage.getPageSize();

      PdfPage page = pdf.addNewPage(1, PageSize.A4);

      PdfCanvas canvas = new PdfCanvas(page);
      AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
                page.getPageSize().getWidth() / orig.getWidth(),
                page.getPageSize().getHeight() / orig.getHeight());

      canvas.concatMatrix(transformationMatrix);
      PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf); 

      canvas.addXObject(pageCopy, 0, 0);

      pdf.close();
      origPdf.close();

        // delete old file,rename new to old file
        inFile.delete();
        outFile.renameTo(new File(inputFilePath));

    }

Upvotes: 0

Views: 1428

Answers (1)

mkl
mkl

Reputation: 95898

To stamp your template page origPage onto the current first page of pdf instead of a new one, simply replace

PdfPage page = pdf.addNewPage(1, PageSize.A4);

by

PdfPage page = pdf.getPage(1);

Now page references the already existing first page instead of a new one, and your further manipulations add the template page thereupon.

Upvotes: 1

Related Questions