Example usage for com.lowagie.text.pdf PdfDestination PdfDestination

List of usage examples for com.lowagie.text.pdf PdfDestination PdfDestination

Introduction

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

Prototype


public PdfDestination(int type) 

Source Link

Document

Constructs a new PdfDestination.

Usage

From source file:org.kuali.coeus.s2sgen.impl.print.S2SPrintingServiceImpl.java

License:Educational Community License

/**
 * @param pdfBytesList List containing the PDF data bytes
 * @param bookmarksList List of bookmarks corresponding to the PDF bytes.
 *//*  w  w w.j av a2s .  co m*/
protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = Calendar.getInstance();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new Document(reader.getPageSizeWithRotation(1)) : new Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new S2SException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.kuali.kra.printing.service.impl.PrintingServiceImpl.java

License:Educational Community License

/**
 * @param pdfBytesList//from   www  . ja  v  a 2  s  .  com
 *            List containing the PDF data bytes
 * @param bookmarksList
 *            List of bookmarks corresponding to the PDF bytes.
 * @return
 * @throws PrintingException
 */

protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = dateTimeService.getCurrentCalendar();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                    : new com.lowagie.text.Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new PrintingException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            // writer.setPageEvent(new Watermark());  //  add watermark object here
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.schreibubi.JCombinations.ui.GridChartPanel.java

License:Open Source License

/**
 * Create PDF//from w ww. j a v a  2 s  .  c  om
 * 
 * @param name
 *            Filename
 * @param selection
 *            Selected Nodes
 * @param dm
 *            DataModel
 * @param pl
 *            ProgressListener
 */
@SuppressWarnings("unchecked")
public static void generatePDF(File name, DataModel dm, ArrayList<TreePath> selection, ProgressListener pl) {
    com.lowagie.text.Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);
    try {
        ArrayList<ExtendedJFreeChart> charts = dm.getCharts(selection);
        if (charts.size() > 0) {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name));
            writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
            document.addAuthor("Jrg Werner");
            document.addSubject("Created by JCombinations");
            document.addKeywords("JCombinations");
            document.addCreator("JCombinations using iText");

            // we define a header and a footer
            HeaderFooter header = new HeaderFooter(new Phrase("JCombinations by Jrg Werner"), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));
            footer.setAlignment(Element.ALIGN_CENTER);
            document.setHeader(header);
            document.setFooter(footer);

            document.open();
            DefaultFontMapper mapper = new DefaultFontMapper();
            FontFactory.registerDirectories();
            mapper.insertDirectory("c:\\WINNT\\fonts");

            PdfContentByte cb = writer.getDirectContent();

            pl.progressStarted(new ProgressEvent(GridChartPanel.class, 0, charts.size()));
            for (int i = 0; i < charts.size(); i++) {
                ExtendedJFreeChart chart = charts.get(i);
                PdfTemplate tp = cb.createTemplate(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                Graphics2D g2d = tp.createGraphics(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN), mapper);
                Rectangle2D r2d = new Rectangle2D.Double(0, 0,
                        document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                chart.draw(g2d, r2d);
                g2d.dispose();
                cb.addTemplate(tp, document.left(EXTRA_MARGIN), document.bottom(EXTRA_MARGIN));
                PdfDestination destination = new PdfDestination(PdfDestination.FIT);
                TreePath treePath = chart.getTreePath();
                PdfOutline po = cb.getRootOutline();
                for (int j = 0; j < treePath.getPathCount(); j++) {
                    ArrayList<PdfOutline> lpo = po.getKids();
                    PdfOutline cpo = null;
                    for (PdfOutline outline : lpo)
                        if (outline.getTitle().compareTo(treePath.getPathComponent(j).toString()) == 0)
                            cpo = outline;
                    if (cpo == null)
                        cpo = new PdfOutline(po, destination, treePath.getPathComponent(j).toString());
                    po = cpo;
                }
                document.newPage();
                pl.progressIncremented(new ProgressEvent(GridChartPanel.class, i));
            }
            document.close();
            pl.progressEnded(new ProgressEvent(GridChartPanel.class));

        }
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:questions.importpages.ConcatenateWithTOC.java

public static void main(String[] args) {
    try {/*w ww .j  a v a2s .  co  m*/
        // suppose we have some TEST PDF files
        for (int i = 0; i < TEST.length; i++) {
            createTestPdf(i);
        }
        // and we want to concatenate them
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
        copy.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        document.open();
        // but we want to create an outline tree
        PdfOutline root = copy.getRootOutline();
        // we also want an extra page with the file name
        Document coverpage;
        ByteArrayOutputStream baos;
        PdfReader reader;
        // we want to add page numbers too
        int pagenumber = 0;
        BaseFont bf = BaseFont.createFont();
        for (int i = 0; i < TEST.length; i++) {
            // we create the coverpage in memory
            coverpage = new Document();
            baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(coverpage, baos);
            coverpage.open();
            coverpage.add(new Paragraph("file: " + TEST[i]));
            coverpage.close();
            // we import that page
            reader = new PdfReader(baos.toByteArray());
            pagenumber++;
            copy.addPage(getStampedPage(reader, copy, 1, pagenumber, bf));
            // we create the bookmark to that page
            PdfDestination dest = new PdfDestination(PdfDestination.FIT);
            new PdfOutline(root, PdfAction.gotoLocalPage(pagenumber, dest, copy), TEST[i]);
            // we import the document itself
            reader = new PdfReader(TEST[i]);
            for (int j = 1; j <= reader.getNumberOfPages(); j++) {
                pagenumber++;
                copy.addPage(getStampedPage(reader, copy, j, pagenumber, bf));
            }
        }
        document.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (DocumentException de) {
        de.printStackTrace();
    }
}

From source file:questions.importpages.ConcatenateWithTOC2.java

public static void main(String[] args) {
    try {// www  .  ja v  a 2  s .  c  o m
        // suppose we have some TEST PDF files
        for (int i = 0; i < TEST.length; i++) {
            createTestPdf(i);
        }
        // and we want to concatenate them
        Document document = new Document();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfCopy copy = new PdfCopy(document, os);
        copy.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        document.open();
        // but we want to create an outline tree
        PdfOutline root = copy.getRootOutline();
        // we also want an extra page with the file name
        Document coverpage;
        ByteArrayOutputStream baos;
        PdfReader reader;
        // we want keep track of the page numbers
        int pagenumber = 0;
        for (int i = 0; i < TEST.length; i++) {
            // we create the coverpage in memory
            coverpage = new Document();
            baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(coverpage, baos);
            coverpage.open();
            coverpage.add(new Paragraph("file: " + TEST[i]));
            coverpage.close();
            // we import that page
            reader = new PdfReader(baos.toByteArray());
            pagenumber++;
            copy.addPage(copy.getImportedPage(reader, 1));
            // we create the bookmark to that page
            PdfDestination dest = new PdfDestination(PdfDestination.FIT);
            new PdfOutline(root, PdfAction.gotoLocalPage(pagenumber, dest, copy), TEST[i]);
            // we import the document itself
            reader = new PdfReader(TEST[i]);
            for (int j = 1; j <= reader.getNumberOfPages(); j++) {
                pagenumber++;
                copy.addPage(copy.getImportedPage(reader, j));
            }
        }
        document.close();

        // we want to add page X of Y
        reader = new PdfReader(os.toByteArray());
        int n = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        BaseFont bf = BaseFont.createFont();
        for (int i = 1; i <= n; i++) {
            PdfContentByte canvas = stamper.getOverContent(i);
            canvas.beginText();
            canvas.setFontAndSize(bf, 12);
            canvas.showTextAligned(Element.ALIGN_LEFT, "page " + i + " of " + n, 36, 26, 0);
            canvas.endText();
        }
        stamper.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (DocumentException de) {
        de.printStackTrace();
    }
}

From source file:webBoltOns.server.reportWriter.JRivetWriter.java

License:Open Source License

/**
 * <h2><code>buildReport</code></h2>
 * //from   w w  w . j  av  a 2s .  c o m
 * <p>
 *  Create the PDF report        
 * </p>
 * 
 * @param   ServletRequest request  - the HTTP request
 * @param   ServletResponse response - the HTTP respones
 * 
 */
private void buildReport(ServletRequest request, ServletResponse response, DataSet reportTable) {
    try {

        rowCount = 999;
        totalRows = 0;
        document = new Document(PageSize.LEGAL.rotate());
        document.setMargins(8.0f, 8.0f, 8.0f, 18.0f);

        outputStream = new ByteArrayOutputStream();
        writer = PdfWriter.getInstance(document, outputStream);
        writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        buildReportTitles(reportTable);

        document.open();

        contentByte = writer.getDirectContent();
        root = new PdfOutline(contentByte.getRootOutline(), new PdfDestination(PdfDestination.FIT), "Report");

        topA.setOutline(root);

        ResultSet resultSet;
        Statement statement = dataAccess.execConnectReadOnly();

        sql = new StringBuffer(reportTable.getStringField(ReportColumn.SQL_QUERY));

        sql = DataSet.removeFormat(sql, "\n");
        sql = DataSet.removeFormat(sql, "\t");

        Enumeration parameters = request.getParameterNames();
        while (parameters.hasMoreElements()) {
            String p = (String) parameters.nextElement();
            String v = request.getParameter(p);
            if (!p.equals("ReportScript") && !p.equals("") && !v.equals(""))
                sql = mergeTagValues(sql, p, v);
        }

        resultSet = statement.executeQuery(sql.toString().trim());
        String[] record = new String[reportColumns.length];

        while (resultSet.next()) {
            for (int c = 0; c < reportColumns.length; c++) {
                ReportColumn column = (ReportColumn) reportColumns[c];
                String value = (String) DataAccess.getFieldValue(resultSet, column.getFeildName(),
                        column.getDataType());
                record[c] = formatField(value, column.getDataType(), column.getDecimals());
            }

            topA.recursiveLevelBreaks(record);
            buildDetilLine(record);
            accumulateReportTotals(record);
            totalRows++;
        }

        if (totalRows == 0) {
            buildEmptyPage(request, response);

        } else {
            topA.fireGrandTotalBreak();
            resultSet.close();
            dataAccess.execClose(statement);
            document.add(reportBody);
            document.close();
            buildPDFReportPage(request, response, outputStream.toByteArray());
        }

    } catch (DocumentException e) {
        gs.log("** DocumentException: " + e);
        buildErrorPage(request, response, e.toString());
    } catch (IOException e) {
        gs.log("** IOException: " + e);
        buildErrorPage(request, response, e.toString());
    } catch (Exception e) {
        gs.log("** Exception: " + e);
        buildErrorPage(request, response, e.toString());
    }

}