The last lines of the prerparePdfToAppend method look strange to me. But why make your life complicated? Return PDDocument:
public PDDocument prerparePdfToAppend() { final PDDocument document = new PDDocument(); final PDPage sourcePage = new PDPage(); document.addPage(sourcePage); PDPageContentStream contentStream = new PDPageContentStream(document, sourcePage); contentStream.beginText(); contentStream.setFont(PDType1Font.COURIER, 12); contentStream.showText("Name: " + firstName + " " + lastName); contentStream.newLine(); ... contentStream.endText(); contentStream.close(); return document; }
Then your merge code will look like this:
public void merge (String assetFileName) { PDFMergerUtility mergerUtility = new PDFMergerUtility(); PDDocument srcDoc = PDDocument.load(PDFBoxResourceLoader.getStream(assetFileName)); PDDocument dstDoc = prerparePdfToAppend(); mergerUtility.appendDocument(dstDoc, srcDoc); dstDoc.save(destStream); srcDoc.close(); dstDoc.close(); }
If this does not work, make sure that
PDFBoxResourceLoader.getStream(assetFileName)
- really a stream of real pdf. If it still does not work, indicate which line of this new code throws an exception. And of course, make sure you are using the latest version of PDFBox.
source share