Create PDF file with custom open actions

article will illustrate how to dynamically generate a PDF file, which will have
the print dialog box automatically popped up when the file is opened in your
web application.

public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    //if you have a password
    String pass = getPassword();
    byte[] password = pass.getBytes();
    Document document = new Document();

    String fileLocation = getPath();
    UrlResource pdf = new UrlResource(fileLocation);
    InputStream input = pdf.getInputStream();

    //if you get the file from local
    //InputStream input = new FileInputStream(getPath.());

    //Reads and parses a PDF document.
    PdfReader pdfReader = new PdfReader(input, password);    

    //if you want to generate the PDF file to the local rather than through the browser
    //OutputStream output = new FileOutputStream("c:\\merge.pdf");
    //PdfWriter writer = PdfWriter.getInstance(document, output);

    //using PdfCopy instead of PdfWriter as everything will be copied to an empty document and PdfCopy has addPage() method to copy each page into this new empty document.
    PdfCopy writer = new PdfCopy(document, response.getOutputStream());


    //set up the open actions you want to provide
    writer.setOpenAction(new PdfAction(PdfAction.PRINTDIALOG));;

    //Use this method to get the direct content for this document. It is an alternative comparing to use  writer.addPage(page).
    //PdfContentByte cb = writer.getDirectContent();

    PdfImportedPage page;

    for (int i = 1; i < pdfReader.getNumberOfPages() + 1; i++) {
        //Use this method to get a page from other PDF document.
        page = writer.getImportedPage(pdfReader, i);
        //cb.addTemplate(page, 0, 0);

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    return null;


The code also provides the
solution to generate the PDF file to the local rather via browser, which has
been commented.





This entry was posted in Dynamic File Generation. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s