IText: How to add blank page inside pdf?

19,729

Solution 1

First hit on google:

/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part1.chapter05;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class NewPage {

/** Path to the resulting PDF file. */
public static final String RESULT
    = "results/part1/chapter05/new_page.pdf";

/**
 * Main method creating the PDF.
 * @param    args    no arguments needed
 * @throws IOException 
 * @throws DocumentException 
 */
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();

    }
}

Solution 2

After you use, document.newPage();, it will be ignored if you don't add any content. So, if you need blank page, then add writer.setPageEmpty(false); right after calling newPage().

Solution 3

Just have a look at the following method of PdfWriter:

http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfWriter.html#setPageEmpty(boolean)

Should work like so:

Document doc = new Document();
PdfWriter pdfWriter
        = PdfWriter.getInstance(document, new FileOutputStream("file.pdf"));
pdfWriter.setPageEmpty(false);
doc.newPage();
doc.close();

You tell the writer that the page is not empty, even though it is, so a new page will be created.

Share:
19,729
marioosh
Author by

marioosh

mostly Java programmer, Linux, Node.js and JavaScript technologies enthusiast...

Updated on June 16, 2022

Comments

  • marioosh
    marioosh about 2 years

    I have pdf document, for example 25 pages. How to add one blank page beetwen page 10 and 11 ?

  • Michael Hogenson
    Michael Hogenson about 10 years
    I like this answer the best because it's short and too the point.