This is a simple code copied from https://github.com/LibrePDF/OpenPDF/wiki/Hello-World. I am only adding a single paragrape, I expect page number to be 1 only, but it always adds a newPage (in listener i.e. PDFDocument)
Document document = new Document();
PdfWriter writer = null
try {
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
writer = PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld.pdf"));
// step 3: we open the document
document.open();
// step 4: we add a paragraph to the document
document.add(new Paragraph("Hello World"));
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
// step 5: we close the document
document.close();
assert writer.getCurrentPageNumber() == 1
How can I get the actual number of Pages in the documents?
It is part of the architecture of iText up to and including its 5.x versions and, therefore, also of OpenPDF to sometimes create pages and drop them again when it turns out they are not needed.
Furthermore, you test a value of the PdfWriter writer after it is closed (it implicitly is closed when closing the Document document), and one should never trust properties of a closed entity other than its closed state.
Most helpful comment
It is part of the architecture of iText up to and including its 5.x versions and, therefore, also of OpenPDF to sometimes create pages and drop them again when it turns out they are not needed.
Furthermore, you test a value of the
PdfWriter writerafter it is closed (it implicitly is closed when closing theDocument document), and one should never trust properties of a closed entity other than its closed state.