Example usage for com.lowagie.text.pdf PdfReader consolidateNamedDestinations

List of usage examples for com.lowagie.text.pdf PdfReader consolidateNamedDestinations

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfReader consolidateNamedDestinations.

Prototype

boolean consolidateNamedDestinations

To view the source code for com.lowagie.text.pdf PdfReader consolidateNamedDestinations.

Click Source Link

Usage

From source file:org.adempiere.webui.apps.ProcessDialog.java

License:Open Source License

public void onPrintShipments() {
    //   Loop through all items
    List<File> pdfList = new ArrayList<File>();
    for (int i = 0; i < m_ids.length; i++) {
        int M_InOut_ID = m_ids[i];
        ReportEngine re = ReportEngine.get(Env.getCtx(), ReportEngine.SHIPMENT, M_InOut_ID);
        pdfList.add(re.getPDF());/*from   w ww  .  j  a va 2s.c om*/
    }

    if (pdfList.size() > 1) {
        try {
            File outFile = File.createTempFile("PrintShipments", ".pdf");
            Document document = null;
            PdfWriter copy = null;
            for (File f : pdfList) {
                String fileName = f.getAbsolutePath();
                PdfReader reader = new PdfReader(fileName);
                reader.consolidateNamedDestinations();
                if (document == null) {
                    document = new Document(reader.getPageSizeWithRotation(1));
                    copy = PdfWriter.getInstance(document, new FileOutputStream(outFile));
                    document.open();
                }
                int pages = reader.getNumberOfPages();
                PdfContentByte cb = copy.getDirectContent();
                for (int i = 1; i <= pages; i++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    cb.addTemplate(page, 0, 0);
                }
            }
            document.close();

            hideBusyDialog();
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(outFile));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    } else if (pdfList.size() > 0) {
        hideBusyDialog();
        try {
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(pdfList.get(0)));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }
}

From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java

License:Open Source License

/**
 * construct a pdf document from pdf parts.
 * // w  w w  . j  a v  a2s  . c om
 * @param files
 *            list containing the pdf to assemble
 * @param properties
 *            converter properties
 * @param fout
 *            outputstream to write the new pdf
 * @param base_url
 *            base url of the document
 * @param producer
 *            producer of the pdf
 * 
 * @throws CConvertException
 *             if an error occured while reconstruct.
 */
public static void reconstruct(final List files, final Map properties, final OutputStream fout,
        final String base_url, final String producer, final PageSize[] size, final List hf)
        throws CConvertException {
    OutputStream out = fout;
    OutputStream out2 = fout;
    boolean signed = false;
    OutputStream oldOut = null;
    File tmp = null;
    File tmp2 = null;
    try {
        tmp = File.createTempFile("yahp", "pdf");
        tmp2 = File.createTempFile("yahp", "pdf");
        oldOut = out;
        if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) {
            signed = true;
            out2 = new FileOutputStream(tmp2);
        } // end if
        else {
            out2 = oldOut;
        }
        out = new FileOutputStream(tmp);
        com.lowagie.text.Document document = null;
        PdfCopy writer = null;
        boolean first = true;

        Map mapSizeDoc = new HashMap();

        int totalPage = 0;

        for (int i = 0; i < files.size(); i++) {
            final File fPDF = (File) files.get(i);
            final PdfReader reader = new PdfReader(fPDF.getAbsolutePath());
            reader.consolidateNamedDestinations();

            final int n = reader.getNumberOfPages();

            if (first) {
                first = false;
                // step 1: creation of a document-object
                // set title/creator/author
                document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, out);
                // use pdf version 1.5
                writer.setPdfVersion(PdfWriter.VERSION_1_3);
                // compress the pdf
                writer.setFullCompression();

                // check if encryption is needed
                if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                    final String password = (String) properties
                            .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
                    final int securityType = CDocumentReconstructor.getSecurityFlags(properties);
                    writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType);
                } // end if

                final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE);

                if (title != null) {
                    document.addTitle(title);
                } // end if
                else if (base_url != null) {
                    document.addTitle(base_url);
                } // end else if

                final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR);

                if (creator != null) {
                    document.addCreator(creator);
                } // end if
                else {
                    document.addCreator(IHtmlToPdfTransformer.VERSION);
                } // end else

                final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR);

                if (author != null) {
                    document.addAuthor(author);
                } // end if

                final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER);

                if (sproducer != null) {
                    document.add(new Meta("Producer", sproducer));
                } // end if
                else {
                    document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION
                            + " - http://www.allcolor.org/YaHPConverter/ - " + producer)));
                } // end else

                // step 3: we open the document
                document.open();
            } // end if

            PdfImportedPage page;

            for (int j = 0; j < n;) {
                ++j;
                totalPage++;
                mapSizeDoc.put("" + totalPage, "" + i);
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
            } // end for
        } // end for

        document.close();
        out.flush();
        out.close();
        {
            final PdfReader reader = new PdfReader(tmp.getAbsolutePath());
            ;
            final int n = reader.getNumberOfPages();
            final PdfStamper stp = new PdfStamper(reader, out2);
            int i = 0;
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer();
            while (i < n) {
                i++;
                int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i));
                final int[] dsize = size[indexSize].getSize();
                final int[] dmargin = size[indexSize].getMargin();
                for (final Iterator it = hf.iterator(); it.hasNext();) {
                    final CHeaderFooter chf = (CHeaderFooter) it.next();
                    if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) {
                        continue;
                    } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) {
                        continue;
                    }
                    final String text = chf.getContent().replaceAll("<pagenumber>", "" + i)
                            .replaceAll("<pagecount>", "" + n);
                    // text over the existing page
                    final PdfContentByte over = stp.getOverContent(i);
                    final ByteArrayOutputStream bbout = new ByteArrayOutputStream();
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(),
                                properties, bbout);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(),
                                properties, bbout);
                    }
                    final PdfReader readerHF = new PdfReader(bbout.toByteArray());
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0);
                    }
                    readerHF.close();
                }
            }
            stp.close();
        }
        try {
            out2.flush();
        } catch (Exception ignore) {
        } finally {
            try {
                out2.close();
            } catch (Exception ignore) {
            }
        }
        if (signed) {

            final String keypassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD);
            final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
            final String keyStorepassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD);
            final String privateKeyFile = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE);
            final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON);
            final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION);
            final boolean selfSigned = !"false"
                    .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING));
            PdfReader reader = null;

            if (password != null) {
                reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes());
            } // end if
            else {
                reader = new PdfReader(tmp2.getAbsolutePath());
            } // end else

            final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType())
                    : KeyStore.getInstance("pkcs12");
            ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray());

            final String alias = (String) ks.aliases().nextElement();
            final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray());
            final Certificate chain[] = ks.getCertificateChain(alias);
            final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0');

            if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null,
                        CDocumentReconstructor.getSecurityFlags(properties));
            } // end if

            final PdfSignatureAppearance sap = stp.getSignatureAppearance();

            if (selfSigned) {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            } // end if
            else {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            } // end else

            if (reason != null) {
                sap.setReason(reason);
            } // end if

            if (location != null) {
                sap.setLocation(location);
            } // end if

            stp.close();
            oldOut.flush();
        } // end if
    } // end try
    catch (final Exception e) {
        throw new CConvertException(
                "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e);
    } // end catch
    finally {
        try {
            tmp.delete();
        } // end try
        catch (final Exception ignore) {
        }
        try {
            tmp2.delete();
        } // end try
        catch (final Exception ignore) {
        }
    } // end finally
}

From source file:org.jaffa.modules.printing.services.MultiFormPrintEngine.java

License:Open Source License

/**
 * Merge a list of generated Pdf Documents together
 * @param documents /*from  w  w w  .j  a va2s .  co m*/
 * @throws java.io.IOException 
 * @throws com.lowagie.text.DocumentException 
 * @return byte[]
 */
public static byte[] mergePdf(List<byte[]> documents) throws IOException, DocumentException {
    int pageOffset = 0;
    ArrayList master = new ArrayList();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    Document document = null;
    PdfCopy writer = null;
    boolean first = true;
    for (Iterator<byte[]> it = documents.iterator(); it.hasNext();) {
        // we create a reader for a certain document
        PdfReader reader = new PdfReader(it.next());
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0)
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            master.addAll(bookmarks);
        }
        pageOffset += n;

        if (first) {
            first = false;

            // step 1: creation of a document-object
            document = new Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, output);
            // step 3: we open the document
            document.open();
        }
        // step 4: we add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        PRAcroForm form = reader.getAcroForm();
        if (form != null)
            writer.copyAcroForm(reader);
    }
    if (master.size() > 0)
        writer.setOutlines(master);
    // step 5: we close the document
    if (document != null)
        document.close();
    return output.toByteArray();
}

From source file:org.jrimum.bopepo.pdf.PDFUtil.java

License:Apache License

/**
 * <p>//from  w ww  . j a v a2  s.  co m
 * Junta varios arquivos pdf em um soh.
 * </p>
 * 
 * @param pdfFiles
 *            Lista de array de bytes
 * 
 * @return Arquivo PDF em forma de byte
 * @since 0.2
 */
@SuppressWarnings("unchecked")
public static byte[] mergeFiles(List<byte[]> pdfFiles) {

    // retorno
    byte[] bytes = null;

    if (isNotNull(pdfFiles) && !pdfFiles.isEmpty()) {

        int pageOffset = 0;
        boolean first = true;

        ArrayList master = null;
        Document document = null;
        PdfCopy writer = null;
        ByteArrayOutputStream byteOS = null;

        try {

            byteOS = new ByteArrayOutputStream();
            master = new ArrayList();

            for (byte[] doc : pdfFiles) {

                if (isNotNull(doc)) {

                    // cria-se um reader para cada documento

                    PdfReader reader = new PdfReader(doc);

                    if (reader.isEncrypted()) {
                        reader = new PdfReader(doc, "".getBytes());
                    }

                    reader.consolidateNamedDestinations();

                    // pega-se o numero total de paginas
                    int n = reader.getNumberOfPages();
                    List bookmarks = SimpleBookmark.getBookmark(reader);

                    if (isNotNull(bookmarks)) {
                        if (pageOffset != 0) {
                            SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                        }
                        master.addAll(bookmarks);
                    }

                    pageOffset += n;

                    if (first) {

                        // passo 1: criar um document-object
                        document = new Document(reader.getPageSizeWithRotation(1));

                        // passo 2: criar um writer que observa o documento
                        writer = new PdfCopy(document, byteOS);
                        document.addAuthor("JRimum Group");
                        document.addSubject("JRimum Merged Document");
                        document.addCreator("JRimum Utilix");

                        // passo 3: abre-se o documento
                        document.open();
                        first = false;
                    }

                    // passo 4: adciona-se o conteudo
                    PdfImportedPage page;
                    for (int i = 0; i < n;) {
                        ++i;
                        page = writer.getImportedPage(reader, i);

                        writer.addPage(page);
                    }
                }
            }

            if (master.size() > 0) {
                writer.setOutlines(master);
            }

            // passo 5: fecha-se o documento
            if (isNotNull(document)) {
                document.close();
            }

            bytes = byteOS.toByteArray();

        } catch (Exception e) {
            LOG.error("", e);
        }
    }
    return bytes;
}

From source file:org.kuali.ext.mm.document.web.struts.CountWorksheetPrintAction.java

License:Educational Community License

private void combineAndFlushReportPDFFiles(List<File> fileList, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    long startTime = System.currentTimeMillis();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArrayList master = new ArrayList();
    int pageOffset = 0;
    int f = 0;/*from w w w.  j a v a 2  s  .c om*/
    PdfCopy writer = null;
    com.lowagie.text.Document document = null;
    for (File file : fileList) {
        // we create a reader for a certain document
        String reportName = file.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0) {
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            }
            master.addAll(bookmarks);
        }
        pageOffset += n;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, baos);
            // step 3: we open the document
            document.open();
        }
        // step 4: we add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        f++;
    }

    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    document.close();

    StringBuffer sbContentDispValue = new StringBuffer();
    String useJavascript = request.getParameter("useJavascript");
    if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
        sbContentDispValue.append("attachment");
    } else {
        sbContentDispValue.append("inline");
    }
    sbContentDispValue.append("; filename=");
    sbContentDispValue.append(MMUtil.getFileName());

    String contentDisposition = sbContentDispValue.toString();

    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", contentDisposition);
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(baos.size());

    // write to output
    ServletOutputStream sos = response.getOutputStream();
    baos.writeTo(sos);
    sos.flush();
    baos.close();
    sos.close();
    long endTime = System.currentTimeMillis();
    loggerAc.debug("Time taken for report Parameter settings in action " + (endTime - startTime));
}

From source file:org.kuali.ext.mm.service.impl.CountWorksheetReportServiceImpl.java

License:Educational Community License

public ByteArrayOutputStream combineAndFlushReportPDFFiles(List<File> fileList) throws Exception {

    long startTime = System.currentTimeMillis();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArrayList master = new ArrayList();
    int pageOffset = 0;
    int f = 0;//from   w ww.j av a2  s  .co  m
    PdfCopy writer = null;
    com.lowagie.text.Document document = null;
    for (File file : fileList) {
        // we create a reader for a certain document
        String reportName = file.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0) {
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            }
            master.addAll(bookmarks);
        }
        pageOffset += n;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, baos);
            // step 3: we open the document
            document.open();
        }
        // step 4: we add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        f++;
    }

    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    document.close();
    return baos;
}

From source file:org.kuali.ext.mm.service.impl.CountWorksheetReportServiceImpl.java

License:Educational Community License

public ByteArrayOutputStream combineAndFlushReportPDFStreams(List<ByteArrayOutputStream> fileList)
        throws Exception {

    long startTime = System.currentTimeMillis();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArrayList master = new ArrayList();
    int pageOffset = 0;
    int f = 0;/*  w  w  w  .  j a v  a2 s. c om*/
    PdfCopy writer = null;
    com.lowagie.text.Document document = null;
    for (ByteArrayOutputStream file : fileList) {
        // we create a reader for a certain document
        // String reportName = file.getAbsolutePath();
        PdfReader reader = new PdfReader(file.toByteArray());
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0) {
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            }
            master.addAll(bookmarks);
        }
        pageOffset += n;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, baos);
            // step 3: we open the document
            document.open();
        }
        // step 4: we add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        f++;
    }

    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    document.close();
    return baos;
}

From source file:org.kuali.kfs.gl.web.struts.TrialBalanceReportAction.java

License:Open Source License

/**
 * Generate pdf for sending response using itext
 *
 * @param reportFileFullName/*from  w  w w. java 2 s  .c  o  m*/
 * @return
 * @throws IOException
 * @throws DocumentException
 * @throws BadPdfFormatException
 */
protected ByteArrayOutputStream generatePdfOutStream(String reportFileFullName)
        throws IOException, DocumentException, BadPdfFormatException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // we create a reader for a certain document
    PdfReader reader = new PdfReader(reportFileFullName);
    reader.consolidateNamedDestinations();

    // step 1: creation of a document-object
    Document document = new Document(reader.getPageSizeWithRotation(1));
    // step 2: we create a writer that listens to the document
    PdfCopy writer = new PdfCopy(document, baos);
    // step 3: we open the document
    document.open();

    // we retrieve the total number of pages
    int n = reader.getNumberOfPages();

    // step 4: we add content
    PdfImportedPage page;
    for (int i = 0; i < n;) {
        ++i;
        page = writer.getImportedPage(reader, i);
        writer.addPage(page);
    }
    writer.freeReader(reader);

    // step 5: we close the document
    document.close();
    return baos;
}

From source file:org.kuali.kfs.module.ar.document.web.struts.CustomerCreditMemoDocumentAction.java

License:Educational Community License

/**
 * //from  w ww.  j a  v a 2 s. com
 * This method...
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ActionForward printCreditMemoPDF(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String creditMemoDocId = request.getParameter(KFSConstants.PARAMETER_DOC_ID);
    CustomerCreditMemoDocument customerCreditMemoDocument = (CustomerCreditMemoDocument) SpringContext
            .getBean(DocumentService.class).getByDocumentHeaderId(creditMemoDocId);

    AccountsReceivableReportService reportService = SpringContext
            .getBean(AccountsReceivableReportService.class);
    File report = reportService.generateCreditMemo(customerCreditMemoDocument);

    StringBuilder fileName = new StringBuilder();
    fileName.append(customerCreditMemoDocument.getFinancialDocumentReferenceInvoiceNumber());
    fileName.append("-");
    fileName.append(customerCreditMemoDocument.getDocumentNumber());
    fileName.append(".pdf");

    if (report.length() == 0) {
        //csForm.setMessage("No Report Generated");
        return mapping.findForward(KFSConstants.MAPPING_BASIC);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String contentDisposition = "";
    try {
        ArrayList master = new ArrayList();
        PdfCopy writer = null;

        // create a reader for the document
        String reportName = report.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null)
            master.addAll(bookmarks);

        // step 1: create a document-object
        Document document = new Document(reader.getPageSizeWithRotation(1));
        // step 2: create a writer that listens to the document
        writer = new PdfCopy(document, baos);
        // step 3: open the document
        document.open();
        // step 4: add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        if (!master.isEmpty())
            writer.setOutlines(master);
        // step 5: we close the document
        document.close();

        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(fileName);

        contentDisposition = sbContentDispValue.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", contentDisposition);
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(baos.size());

    // write to output
    ServletOutputStream sos;
    sos = response.getOutputStream();
    baos.writeTo(sos);
    sos.flush();
    sos.close();

    return null;
}

From source file:org.kuali.kfs.module.ar.document.web.struts.CustomerInvoiceDocumentAction.java

License:Educational Community License

/**
 * /* ww  w.ja  v  a 2s.  c  o m*/
 * This method...
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ActionForward printInvoicePDF(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String invoiceDocId = request.getParameter(KFSConstants.PARAMETER_DOC_ID);
    CustomerInvoiceDocument customerInvoiceDocument = (CustomerInvoiceDocument) SpringContext
            .getBean(DocumentService.class).getByDocumentHeaderId(invoiceDocId);

    AccountsReceivableReportService reportService = SpringContext
            .getBean(AccountsReceivableReportService.class);
    File report = reportService.generateInvoice(customerInvoiceDocument);

    StringBuilder fileName = new StringBuilder();
    fileName.append(customerInvoiceDocument.getOrganizationInvoiceNumber());
    fileName.append("-");
    fileName.append(customerInvoiceDocument.getDocumentNumber());
    fileName.append(".pdf");

    if (report.length() == 0) {
        //csForm.setMessage("No Report Generated");
        return mapping.findForward(KFSConstants.MAPPING_BASIC);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String contentDisposition = "";
    try {
        ArrayList master = new ArrayList();
        PdfCopy writer = null;

        // create a reader for the document
        String reportName = report.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            master.addAll(bookmarks);
        }

        // step 1: create a document-object
        Document document = new Document(reader.getPageSizeWithRotation(1));
        // step 2: create a writer that listens to the document
        writer = new PdfCopy(document, baos);
        // step 3: open the document
        document.open();
        // step 4: add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        if (!master.isEmpty()) {
            writer.setOutlines(master);
        }
        // step 5: we close the document
        document.close();

        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(fileName);

        contentDisposition = sbContentDispValue.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", contentDisposition);
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(baos.size());

    // write to output
    ServletOutputStream sos;
    sos = response.getOutputStream();
    baos.writeTo(sos);
    sos.flush();
    sos.close();

    return null;
}