FlyingSaucer merge PDF doc after calling setDocumentFromString(html)

117 Views Asked by At

I'm using FlyingSaucer to create a PDF from HTML. It works well, but I'd like to append (merge) another PDF attachment to it as a separate page (or pages). The attachment will be a PDF.

My existing code:

org.xhtmlrenderer.pdf.ITextRenderer render = new org.xhtmlrenderer.pdf.ITextRenderer();
render.setDocumentFromString("<!--?xml version='1.0' encoding='utf-8'?--><html><body>Some text</body></html>");
render.layout();
ByteArrayOutputStream out = new ByteArrayOutputStream();
render.createPDF(out);

The attachments should be on a new PDF page.

Looking through the examples for Flying Saucer, it seems I should be able to do something like this:

final File outputFile = File.createTempFile("FlyingSaucer.PDFRenderToMultiplePages", ".pdf");
try (OutputStream os = newOutputStream(outputFile.toPath())) {

    ITextRenderer renderer = new ITextRenderer();

    // we need to create the target PDF
    // we'll create a page with HTML input string
    renderer.setDocumentFromString(htmlStr);
    renderer.layout();
    renderer.createPDF(os, false);

    // now append the existing PDF
    renderer.setDocument...? // how to read and add the PDF file here
    renderer.layout();
    renderer.writeNextDocument();
}

// complete the PDF
renderer.finishPDF();
0

There are 0 best solutions below