Search code examples
javaitextflying-saucer

How to open PDF created with flying-saucer/itext with a print dialog


Some background to this question can be found at Check printing with Java/JSP and Create a "print-only" PDF with itext

I have been able to successfully create and open a PDF with a print dialog using iText-2.0.8 and the following code:

String outputFile = "firstdoc.pdf";
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
writer.setOpenAction(new PdfAction(PdfAction.PRINTDIALOG)); 
document.open();
document.add(new Paragraph("TEST"));
document.close();

I have also been able to use flying-saucer to generate a PDF from XHTML using the following code:

String inputFile = "firstdoc.xhtml";
String url = new File(inputFile).toURI().toURL().toString();
String outputFile = "firstdoc.pdf";

OutputStream os = new FileOutputStream(outputFile);

ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);

os.close();

However, I can't seem to get the two to work together...

I would like to create the PDF using flying-saucer as in the 2nd code block and I would like to set the open action of that PDF to PdfAction.PRINTDIALOG.

How can I get these two sets of code to work together such that a flying-saucer created PDF opens with a print dialog initially?


Solution

  • Figured it out...

    In case someone else needs this in the future, you can just use PdfStamper to modify a PDF that has already been created.

    Here's the full code that worked for me:

    import java.io.*;
    
    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException;
    import com.lowagie.text.Paragraph;
    import com.lowagie.text.pdf.PdfWriter;
    import com.lowagie.text.pdf.PdfAction;
    import com.lowagie.text.pdf.PdfReader;
    import com.lowagie.text.pdf.PdfStamper;
    
    import org.xhtmlrenderer.pdf.ITextRenderer;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class FirstDoc {
    
        public static void main(String[] args) throws IOException, DocumentException {
    
            String inputFile = "firstdoc.xhtml";
            String url = new File(inputFile).toURI().toURL().toString();
            String outputFile = "firstdoc.pdf";
    
            OutputStream os = new FileOutputStream(outputFile);
    
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);
            renderer.layout();
            renderer.createPDF(os);
    
            os.close();
    
            PdfReader reader = new PdfReader(outputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("firstdocprint.pdf"));
            stamper.setPageAction(PdfWriter.PAGE_OPEN, new PdfAction(PdfAction.PRINTDIALOG), 1); 
            stamper.close();
        }
    }