How to add blank pages in exist PDF in java? [clos

2020-04-12 04:51发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 6 years ago.

I have normal PDF file, i want to insert blank pages at the end of PDF using itext LIBRARY, without disturbing the PDF contents.

回答1:

The answer by Dinup Kandel is wrong because it's about creating a document from scratch.

The answer by NK123 is very wrong because it uses PdfWriter/PdfImportedPage to concatenate documents. That example assumes that all pages in the original document have the size A4. This won't always be the case. As documented, this also throws away all interactivity.

The only good answer looks like this:

PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSizeWithRotation(1));
stamper.close();
reader.close();

If src refers to a document with 10 pages, the code above will add an extra blank 11th page, using the same page size as the first page.



回答2:

well i have searched the answer and found something like this but don't know if it will work or not

public static void main(String[] args) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer
            = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // step 3
        document.open();
        // step 4
        document.add(new Paragraph("This page will NOT be followed by a blank page!"));
        document.newPage();
        // we don't add anything to this page: newPage() will be ignored
        document.newPage();
        document.add(new Paragraph("This page will be followed by a blank page!"));
        document.newPage();
        writer.setPageEmpty(false);
        document.newPage();
        document.add(new Paragraph("The previous page was a blank page!"));
        // step 5
        document.close();

    }