Extract pdf page and insert into existing pdf

2019-09-17 16:10发布

问题:

I have below iText code, I want to copy one page from src pdf file to other pdf file(I have existing PdfStamper, here it is mainPdfStamper).

PdfReader srcReader = new PdfReader(new FileInputStream("source.pdf"));

File file = File.createTempFile("temporary", ".pdf");

PdfStamper pdfStamper = new PdfStamper(srcReader, new FileOutputStream(file));
PdfImportedPage importedPage = pdfStamper.getImportedPage(srcReader, 1);

// copying extracted page from src pdf to existing pdf
mainPdfStamper.getOverContent(1).addTemplate(importedPage, 10,10);
pdfStamper.close();
srcReader.close();

This is not working and I am not aware of how to achieve this. In short, I want to copy one page from source pdf to existing pdf. Please help.

UPDATE

Below code worked as per the answer from Bruno.

    PdfReader reader2 = new PdfReader(srcPdf.getAbsolutePath());
    PdfImportedPage page = pdfStamper.getImportedPage(reader2, 1);
    stamper.insertPage(1, reader2.getPageSize(1));
    pdfStamper.getUnderContent(1).addTemplate(page, 100, 100);
    // Close the stamper and the readers
    pdfStamper.close();
    reader2.close();

回答1:

Please read the documentation, for instance chapter 6 of iText in Action. If you go to section 6.3.4 ("Inserting pages into an existing document"), you'll find the InsertPages example.

You only need this code if p is the page number indicating where you want to insert the page, main_file is the path to your main file and to_be_inserted the path to the file that needs to be inserted (dest is the path to the resulting file):

PdfReader reader = new PdfReader(main_file);
PdfReader reader2 = new PdfReader(to_be_inserted);
// Create a stamper
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
// Create an imported page to be inserted
PdfImportedPage page = stamper.getImportedPage(reader2, 1);
stamper.insertPage(p, reader2.getPageSize(1));
stamper.getUnderContent(i).addTemplate(page, 0, 0);
// Close the stamper and the readers
stamper.close();
reader.close();
reader2.close();

This is only one way to combine pages from two files. You can also use PdfCopy for this purpose. The advantage of using PdfCopy is the fact that you'll preserve the interactive features of the interactive page. When using PdfStamper, you'll lose any interactive feature (e.g. all links) that were present in the inserted page.



标签: java itext