Reputation: 11
I'm now using Itext PdfSmartCopy. I'm adding some business contents to a document object with XMLworker. Then I declared a reader (for a pdf file to be concatenated to this document object). Then I'm calling PdfSmartCopy with the same document object and output file stream as arguments. Then I'm using conventional steps to copy the page to the document,
addHTML(document, htmlStringToBeAdded);
document.newPage();
com.itextpdf.text.pdf.PdfCopy copy = new com.itextpdf.text.pdf.PdfSmartCopy(document, new FileOutputStream("c:\\pdf_issue\\bad_itext3.pdf"));
com.itextpdf.text.pdf.PdfReader reader=new com.itextpdf.text.pdf.PdfReader("c:\\pdf_issue\\bad1.pdf");
// loop over the pages in that document
n = reader.getNumberOfPages();
for (int page = 0; page < n; ) {
copy.addPage(copy.getImportedPage(reader, ++page));
}
copy.freeReader(reader);
reader.close();
But I'm getting Null pointer exception at getPageReference? What's the issue?
Exception in thread "main" java.lang.NullPointerException
at com.itextpdf.text.pdf.PdfWriter.getPageReference(PdfWriter.java:1025)
at com.itextpdf.text.pdf.PdfWriter.getCurrentPage(PdfWriter.java:1043)
at com.itextpdf.text.pdf.PdfCopy.addPage(PdfCopy.java:356)
at com.jci.util.PdfTest.main(PdfTest.java:627)
But this piece works well if I use a new document object ie without adding business contents.
Upvotes: 0
Views: 5251
Reputation: 77528
We had a similar question in our closed issue tracker. In that ticket, it appeared that the Document
needed to be opened right after the PdfCopy
instance is created.
In your case, we see a similar problem: you use a Document
object to create a PDF from scratch, and you then use the same Document
to create a copy of an existing PDF. That can never work: you need to close the document you create from scratch first, and then create a new Document
for the copy process:
// first create the document
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.open();
addHTML(document, htmlStringToBeAdded);
document.close();
// Now you can use the document you've just created
PdfReader reader = new PdfReader(baos.toArray());
PdfReader existing = new PdfReader("c:\\pdf_issue\\bad1.pdf");
document = new Document();
PdfCopy copy = new PdfSmartCopy(document, new FileOutputStream("c:\\pdf_issue\\bad_itext3.pdf"));
document.open();
copy.addDocument(reader);
copy.addDocument(existing);
document.close();
reader.close();
existing.close();
Upvotes: 4