Example usage for com.lowagie.text.pdf PdfContentByte addTemplate

List of usage examples for com.lowagie.text.pdf PdfContentByte addTemplate

Introduction

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

Prototype

public void addTemplate(PdfTemplate template, float a, float b, float c, float d, float e, float f) 

Source Link

Document

Adds a template to this content.

Usage

From source file:org.efaps.esjp.common.file.FileUtil_Base.java

License:Apache License

/**
 * N up./*  ww w  .  jav a 2 s.  c  o m*/
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _file the file
 * @param _fileName the file name
 * @return the file
 * @throws EFapsException on error
 */
public File nUpPdf(final Parameter _parameter, final File _file, final String _fileName) throws EFapsException {
    final File ret = getFile(_fileName, "pdf");
    try {
        final int pow = Integer.parseInt(getProperty(_parameter, "NUpPow", "1"));
        final boolean duplicate = "true".equalsIgnoreCase(getProperty(_parameter, "NUpDuplicate", "true"));
        final File destFile = new File(_file.getPath() + ".tmp");
        FileUtils.copyFile(_file, destFile);
        final OutputStream outputStream = new FileOutputStream(ret);
        final PdfReader pdfReader = new PdfReader(new FileInputStream(destFile));

        final Rectangle pageSize = pdfReader.getPageSize(1);

        final Rectangle newSize = pow % 2 == 0 ? new Rectangle(pageSize.getWidth(), pageSize.getHeight())
                : new Rectangle(pageSize.getHeight(), pageSize.getWidth());

        Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight());

        for (int i = 0; i < pow; i++) {
            unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth());
        }

        final int n = (int) Math.pow(2, pow);
        final int r = (int) Math.pow(2, pow / 2);
        final int c = n / r;

        final Document document = new Document(newSize, 0, 0, 0, 0);

        // Create a writer for the outputstream
        final PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        PdfImportedPage page;
        final PdfContentByte cb = writer.getDirectContent();
        // Create a new page in the target for each source page.
        Rectangle currentSize;
        float offsetX;
        float offsetY;
        float factor;

        final int total = pdfReader.getNumberOfPages();
        for (int i = 0; i < total;) {
            if (i % n == 0) {
                document.newPage();
            }
            currentSize = pdfReader.getPageSize(++i);

            factor = Math.min(unitSize.getWidth() / currentSize.getWidth(),
                    unitSize.getHeight() / currentSize.getHeight());
            offsetX = unitSize.getWidth() * (i % n % c)
                    + (unitSize.getWidth() - currentSize.getWidth() * factor) / 2f;
            offsetY = newSize.getHeight() - (unitSize.getHeight() * (i % n % c) + 1)
                    + (unitSize.getHeight() - currentSize.getHeight() * factor) / 2f;

            page = writer.getImportedPage(pdfReader, i);

            cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);

            if (duplicate) {
                for (int y = i + 1; y <= pow + 1; y++) {
                    factor = Math.min(unitSize.getWidth() / currentSize.getWidth(),
                            unitSize.getHeight() / currentSize.getHeight());
                    offsetX = unitSize.getWidth() * (y % n % c)
                            + (unitSize.getWidth() - currentSize.getWidth() * factor) / 2f;
                    offsetY = newSize.getHeight() - unitSize.getHeight() * (y % n / c + 1)
                            + (unitSize.getHeight() - currentSize.getHeight() * factor) / 2f;
                    cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
                }
            }
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (final FileNotFoundException e) {
        LOG.error("FileNotFoundException", e);
    } catch (final IOException e) {
        LOG.error("IOException", e);
    } catch (final DocumentException e) {
        LOG.error("DocumentException", e);
    }
    return ret;
}

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

License:Open Source License

/**
 * Any work to start off printing a page of the document
 * m_currentPage will contain the page being printed, and
 * m_currentTemplatePage will contain the template page number to base this
 * new page on.//  w  ww .  j a  v  a2s  . co m
 * @throws FormPrintException Thrown if there is any form processing problems
 */
protected void startPage() throws FormPrintException {
    log.debug("startPage: Page=" + getCurrentPage());

    Rectangle r = m_templateReader.getPageSize(getCurrentTemplatePage());
    log.debug("Page Size      : t=" + r.getTop() + ",l=" + r.getLeft() + ",b=" + r.getBottom() + ",r="
            + r.getRight() + ", rot=" + r.getRotation());
    r = m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage());
    log.debug("Page Size w/Rot: t=" + r.getTop() + ",l=" + r.getLeft() + ",b=" + r.getBottom() + ",r="
            + r.getRight() + ", rot=" + r.getRotation());

    // Get rotation quadrent 0..3
    int q = (m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()).getRotation() % 360) / 90;
    float tX = (q == 2 ? r.getTop() : 0) + (q == 3 ? r.getRight() : 0);
    float tY = (q == 1 ? r.getTop() : 0) + (q == 2 ? r.getRight() : 0);
    float sX = 1f, sY = 1f;
    double angle = -r.getRotation() * (Math.PI / 180f);
    double transformA = sX * Math.cos(angle);
    double transformB = sY * Math.sin(angle);
    double transformC = -sX * Math.sin(angle);
    double transformD = sY * Math.cos(angle);
    double transformE = tX;
    double transformF = tY;

    m_generatedDoc.setPageSize(m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()));
    //m_generatedDoc.setPageSize(m_templateReader.getPageSize(getCurrentTemplatePage()) );
    /**
     * try {
     * m_generatedDoc.newPage();
     * } catch (DocumentException e) {
     * log.error("Error Creating New Page - " + e.getMessage() ,e);
     * throw new EngineProcessingException("Error Creating New Page - " + e.getMessage());
     * }
     **/
    m_generatedDoc.newPage();

    PdfImportedPage page = m_writer.getImportedPage(m_templateReader, getCurrentTemplatePage());
    PdfContentByte cb = m_writer.getDirectContent();
    //cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
    cb.addTemplate(page, (float) transformA, (float) transformB, (float) transformC, (float) transformD,
            (float) transformE, (float) transformF);
    log.debug("Matrix = [A=" + transformA + ", B=" + transformB + ", C=" + transformC + ", D=" + transformD
            + ", E=" + transformE + ", F=" + transformF + " ]");
}

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

License:Open Source License

/**
 * Scale the pages of the input pdfOutput document to the given pageSize.
 * @param pdfOutput The PDF document to rescale, in the form of a ByteArrayOutputStream.
 * @param pageSize The new page size to which to scale to PDF document, e.g. "A4".
 * @param noEnlarge If true, center pages instead of enlarging them.
 *        Use noEnlarge if the new page size is larger than the old one
 *        and the pages should be centered instead of enlarged.
 * @param preserveAspectRatio If true, the aspect ratio will be preserved.
 * @return The PDF document with its pages scaled to the input pageSize.
 *///from   w  w w  .java2 s.  c o  m
public static byte[] scalePdfPages(byte[] pdfOutput, String pageSize, boolean noEnlarge,
        boolean preserveAspectRatio) throws FormPrintException {
    if (pageSize == null || pdfOutput == null) {
        return pdfOutput;
    }

    // Get the dimensions of the given pageSize in PostScript points.
    // A PostScript point is a 72th of an inch.
    float dimX;
    float dimY;
    Rectangle rectangle;
    try {
        rectangle = PageSize.getRectangle(pageSize);
    } catch (Exception ex) {
        FormPrintException e = new PdfProcessingException(
                "scalePdfPages  - Invalid page size = " + pageSize + "  ");
        log.error(" scalePdfPages  - Invalid page size: " + pageSize + ".  " + ex.getMessage() + ". ");
        throw e;
    }
    if (rectangle != null) {
        dimX = rectangle.getWidth();
        dimY = rectangle.getHeight();
    } else {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Invalid page size: " + pageSize);
        log.error(" scalePdfPages  - Invalid page size: " + pageSize);
        throw e;
    }
    //Create portrait and landscape rectangles for the given page size.
    Rectangle portraitPageSize;
    Rectangle landscapePageSize;
    if (dimY > dimX) {
        portraitPageSize = new Rectangle(dimX, dimY);
        landscapePageSize = new Rectangle(dimY, dimX);
    } else {
        portraitPageSize = new Rectangle(dimY, dimX);
        landscapePageSize = new Rectangle(dimX, dimY);
    }

    // Remove the document rotation before resizing the document.
    byte[] output = removeRotation(pdfOutput);
    PdfReader currentReader = null;
    try {
        currentReader = new PdfReader(output);
    } catch (IOException ex) {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Failed to create a PDF Reader");
        log.error(" scalePdfPages  - Failed to create a PDF Reader ");
        throw e;
    }

    OutputStream baos = new ByteArrayOutputStream();
    Rectangle newSize = new Rectangle(dimX, dimY);
    Document document = new Document(newSize, 0, 0, 0, 0);
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baos);
    } catch (DocumentException ex) {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Failed to create a PDF Writer");
        log.error(" scalePdfPages  - Failed to create a PDF Writer ");
        throw e;
    }
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    PdfImportedPage page;
    float offsetX, offsetY;
    for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
        Rectangle currentSize = currentReader.getPageSizeWithRotation(i);
        if (currentReader.getPageRotation(i) != 0) {
            FormPrintException e = new PdfProcessingException("Page Rotation, "
                    + currentReader.getPageRotation(i) + ", must be removed to re-scale the form.");
            log.error(" Page Rotation, " + currentReader.getPageRotation(i)
                    + ", must be removed to re-scale the form. ");
            throw e;
        }
        //Reset the page size for each page because there may be a mix of sizes in the document.
        float currentWidth = currentSize.getWidth();
        float currentHeight = currentSize.getHeight();
        if (currentWidth > currentHeight) {
            newSize = landscapePageSize;
        } else {
            newSize = portraitPageSize;
        }
        document.setPageSize(newSize);
        document.newPage();
        float factorX = newSize.getWidth() / currentSize.getWidth();
        float factorY = newSize.getHeight() / currentSize.getHeight();
        // Use noEnlarge if the new page size is larger than the old one
        // and the pages should be centered instead of enlarged.
        if (noEnlarge) {
            if (factorX > 1) {
                factorX = 1;
            }
            if (factorY > 1) {
                factorY = 1;
            }
        }
        if (preserveAspectRatio) {
            factorX = Math.min(factorX, factorY);
            factorY = factorX;
        }
        offsetX = (newSize.getWidth() - (currentSize.getWidth() * factorX)) / 2f;
        offsetY = (newSize.getHeight() - (currentSize.getHeight() * factorY)) / 2f;
        page = writer.getImportedPage(currentReader, i);
        cb.addTemplate(page, factorX, 0, 0, factorY, offsetX, offsetY);
    }
    document.close();
    return ((ByteArrayOutputStream) baos).toByteArray();
}

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

License:Open Source License

/**
 * Remove the rotation from the pdfOutput document pages.
 *//*from  w w w . ja  v  a 2  s.co m*/
private static byte[] removeRotation(byte[] pdfOutput) throws FormPrintException {
    PdfReader currentReader = null;
    try {
        currentReader = new PdfReader(pdfOutput);
    } catch (IOException ex) {
        FormPrintException e = new PdfProcessingException(
                "Remove PDF Page Rotation  - Failed to create a PDF Reader");
        log.error(" Remove PDF Page Rotation  - Failed to create a PDF Reader ");
        throw e;
    }
    boolean needed = false;
    for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
        if (currentReader.getPageRotation(i) != 0) {
            needed = true;
        }
    }
    if (!needed) {
        return pdfOutput;
    }

    OutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baos);
    } catch (DocumentException ex) {
        FormPrintException e = new PdfProcessingException(
                "Remove PDF Page Rotation  - Failed to create a PDF Writer");
        log.error(" Remove PDF Page Rotation  - Failed to create a PDF Writer ");
        throw e;
    }
    PdfContentByte cb = null;
    PdfImportedPage page;
    for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
        Rectangle currentSize = currentReader.getPageSizeWithRotation(i);
        currentSize = new Rectangle(currentSize.getWidth(), currentSize.getHeight()); // strip rotation
        document.setPageSize(currentSize);
        if (cb == null) {
            document.open();
            cb = writer.getDirectContent();
        } else {
            document.newPage();
        }
        int rotation = currentReader.getPageRotation(i);
        page = writer.getImportedPage(currentReader, i);
        float a, b, c, d, e, f;
        if (rotation == 0) {
            a = 1;
            b = 0;
            c = 0;
            d = 1;
            e = 0;
            f = 0;
        } else if (rotation == 90) {
            a = 0;
            b = -1;
            c = 1;
            d = 0;
            e = 0;
            f = currentSize.getHeight();
        } else if (rotation == 180) {
            a = -1;
            b = 0;
            c = 0;
            d = -1;
            e = currentSize.getWidth();
            f = currentSize.getHeight();
        } else if (rotation == 270) {
            a = 0;
            b = 1;
            c = -1;
            d = 0;
            e = currentSize.getWidth();
            f = 0;
        } else {
            FormPrintException ex = new PdfProcessingException(
                    "Remove PDF Page Rotation - Unparsable rotation value: " + rotation);
            log.error(" Remove PDF Page Rotation - Unparsable form rotation value: " + rotation);
            throw ex;
        }
        cb.addTemplate(page, a, b, c, d, e, f);
    }
    document.close();
    return ((ByteArrayOutputStream) baos).toByteArray();
}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void nup(int pageCount, PdfPageData currentPageData, ExtractPDFPagesNup extractPage) {

    try {/*from ww w . j a va 2s  .c  o m*/

        int[] pgsToEdit = extractPage.getPages();

        if (pgsToEdit == null)
            return;

        //get user choice
        final String output_dir = extractPage.getRootDir() + separator + fileName + separator + "PDFs"
                + separator;

        File testDirExists = new File(output_dir);
        if (!testDirExists.exists())
            testDirExists.mkdirs();

        List pagesToEdit = new ArrayList();
        for (int i = 0; i < pgsToEdit.length; i++)
            pagesToEdit.add(new Integer(pgsToEdit[i]));

        PdfReader reader = new PdfReader(selectedFile);

        File fileToSave = new File(output_dir + "export_" + fileName + ".pdf");

        if (fileToSave.exists()) {
            int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(), false);

            if (n == 0) {
                // clicked yes so just carry on
            } else {
                // clicked no, so exit
                return;
            }
        }

        int rows = extractPage.getLayoutRows();
        int coloumns = extractPage.getLayoutColumns();

        int paperWidth = extractPage.getPaperWidth();
        int paperHeight = extractPage.getPaperHeight();

        Rectangle pageSize = new Rectangle(paperWidth, paperHeight);

        String orientation = extractPage.getPaperOrientation();

        Rectangle newSize = null;
        if (orientation.equals(Messages.getMessage("PdfViewerNUPOption.Auto"))) {
            if (coloumns > rows)
                newSize = new Rectangle(pageSize.height(), pageSize.width());
            else
                newSize = new Rectangle(pageSize.width(), pageSize.height());
        } else if (orientation.equals("Portrait")) {
            newSize = new Rectangle(pageSize.width(), pageSize.height());
        } else if (orientation.equals("Landscape")) {
            newSize = new Rectangle(pageSize.height(), pageSize.width());
        }

        String scale = extractPage.getScale();

        float leftRightMargin = extractPage.getLeftRightMargin();
        float topBottomMargin = extractPage.getTopBottomMargin();
        float horizontalSpacing = extractPage.getHorizontalSpacing();
        float verticalSpacing = extractPage.getVerticalSpacing();

        Rectangle unitSize = null;
        if (scale.equals("Auto")) {
            float totalHorizontalSpacing = (coloumns - 1) * horizontalSpacing;

            int totalWidth = (int) (newSize.width() - leftRightMargin * 2 - totalHorizontalSpacing);
            int unitWidth = totalWidth / coloumns;

            float totalVerticalSpacing = (rows - 1) * verticalSpacing;

            int totalHeight = (int) (newSize.height() - topBottomMargin * 2 - totalVerticalSpacing);
            int unitHeight = totalHeight / rows;

            unitSize = new Rectangle(unitWidth, unitHeight);

        } else if (scale.equals("Use Original Size")) {
            unitSize = null;
        } else if (scale.equals("Specified")) {
            unitSize = new Rectangle(extractPage.getScaleWidth(), extractPage.getScaleHeight());
        }

        int order = extractPage.getPageOrdering();

        int pagesPerPage = rows * coloumns;

        int repeats = 1;
        if (extractPage.getRepeat() == REPEAT_AUTO)
            repeats = coloumns * rows;
        else if (extractPage.getRepeat() == REPEAT_SPECIFIED)
            repeats = extractPage.getCopies();

        Document document = new Document(newSize, 0, 0, 0, 0);

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileToSave));

        document.open();

        PdfContentByte cb = writer.getDirectContent();
        PdfImportedPage importedPage;
        float offsetX = 0, offsetY = 0, factor;
        int actualPage = 0, page = 0;
        Rectangle currentSize;

        boolean isProportional = extractPage.isScaleProportional();

        for (int i = 1; i <= pageCount; i++) {
            if (pagesToEdit.contains(new Integer(i))) {
                for (int j = 0; j < repeats; j++) {

                    int currentUnit = page % pagesPerPage;

                    if (currentUnit == 0) {
                        document.newPage();
                        actualPage++;
                    }

                    currentSize = reader.getPageSizeWithRotation(i);
                    if (unitSize == null)
                        unitSize = currentSize;

                    int currentColoumn = 0, currentRow = 0;
                    if (order == ORDER_DOWN) {
                        currentColoumn = currentUnit / rows;
                        currentRow = currentUnit % rows;

                        offsetX = unitSize.width() * currentColoumn;
                        offsetY = newSize.height() - (unitSize.height() * (currentRow + 1));

                    } else if (order == ORDER_ACCROS) {
                        currentColoumn = currentUnit % coloumns;
                        currentRow = currentUnit / coloumns;

                        offsetX = unitSize.width() * currentColoumn;
                        offsetY = newSize.height() - (unitSize.height() * ((currentUnit / coloumns) + 1));

                    }

                    factor = Math.min(unitSize.width() / currentSize.width(),
                            unitSize.height() / currentSize.height());

                    float widthFactor = factor, heightFactor = factor;
                    if (!isProportional) {
                        widthFactor = unitSize.width() / currentSize.width();
                        heightFactor = unitSize.height() / currentSize.height();
                    } else {
                        offsetX += ((unitSize.width() - (currentSize.width() * factor)) / 2f);
                        offsetY += ((unitSize.height() - (currentSize.height() * factor)) / 2f);
                    }

                    offsetX += (horizontalSpacing * currentColoumn) + leftRightMargin;
                    offsetY -= ((verticalSpacing * currentRow) + topBottomMargin);

                    importedPage = writer.getImportedPage(reader, i);

                    double rotation = currentSize.getRotation() * Math.PI / 180;

                    /**
                     * see 
                     * http://itextdocs.lowagie.com/tutorial/directcontent/coordinates/index.html 
                     * for information about transformation matrices, and the coordinate system
                     */

                    int mediaBoxX = -currentPageData.getMediaBoxX(i);
                    int mediaBoxY = -currentPageData.getMediaBoxY(i);

                    float a, b, c, d, e, f;
                    switch (currentSize.getRotation()) {
                    case 0:
                        a = widthFactor;
                        b = 0;
                        c = 0;
                        d = heightFactor;
                        e = offsetX + (mediaBoxX * widthFactor);
                        f = offsetY + (mediaBoxY * heightFactor);

                        cb.addTemplate(importedPage, a, b, c, d, e, f);

                        break;
                    case 90:
                        a = 0;
                        b = (float) (Math.sin(rotation) * -heightFactor);
                        c = (float) (Math.sin(rotation) * widthFactor);
                        d = 0;
                        e = offsetX + (mediaBoxY * widthFactor);
                        f = ((currentSize.height() * heightFactor) + offsetY) - (mediaBoxX * heightFactor);

                        cb.addTemplate(importedPage, a, b, c, d, e, f);

                        break;
                    case 180:
                        a = (float) (Math.cos(rotation) * widthFactor);
                        b = 0;
                        c = 0;
                        d = (float) (Math.cos(rotation) * heightFactor);
                        e = (offsetX + (currentSize.width() * widthFactor)) - (mediaBoxX * widthFactor);
                        f = ((currentSize.height() * heightFactor) + offsetY) - (mediaBoxY * heightFactor);

                        cb.addTemplate(importedPage, a, b, c, d, e, f);

                        break;
                    case 270:
                        a = 0;
                        b = (float) (Math.sin(rotation) * -heightFactor);
                        c = (float) (Math.sin(rotation) * widthFactor);
                        d = 0;
                        e = (offsetX + (currentSize.width() * widthFactor)) - (mediaBoxY * widthFactor);
                        f = offsetY + (mediaBoxX * heightFactor);

                        cb.addTemplate(importedPage, a, b, c, d, e, f);

                        break;
                    }

                    page++;
                }
            }
        }

        document.close();

        currentGUI.showMessageDialog(
                Messages.getMessage("PdfViewerMessage.PagesSavedAsPdfTo") + " " + output_dir);

    } catch (Exception e) {

        e.printStackTrace();

    }
}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void handouts(String file) {
    try {//from w  w  w .j a v  a 2s  .com
        File src = new File(selectedFile);

        File dest = new File(file);

        int pages = 4;

        float x1 = 30f;
        float x2 = 280f;
        float x3 = 320f;
        float x4 = 565f;

        float[] y1 = new float[pages];
        float[] y2 = new float[pages];

        float height = (778f - (20f * (pages - 1))) / pages;
        y1[0] = 812f;
        y2[0] = 812f - height;

        for (int i = 1; i < pages; i++) {
            y1[i] = y2[i - 1] - 20f;
            y2[i] = y1[i] - height;
        }

        // we create a reader for a certain document
        PdfReader reader = new PdfReader(src.getAbsolutePath());
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();

        // step 1: creation of a document-object
        Document document = new Document(PageSize.A4);
        // step 2: we create a writer that listens to the document
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        // step 3: we open the document
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfImportedPage page;
        int rotation;
        int i = 0;
        int p = 0;
        // step 4: we add content
        while (i < n) {
            i++;
            Rectangle rect = reader.getPageSizeWithRotation(i);
            float factorx = (x2 - x1) / rect.width();
            float factory = (y1[p] - y2[p]) / rect.height();
            float factor = (factorx < factory ? factorx : factory);
            float dx = (factorx == factor ? 0f : ((x2 - x1) - rect.width() * factor) / 2f);
            float dy = (factory == factor ? 0f : ((y1[p] - y2[p]) - rect.height() * factor) / 2f);
            page = writer.getImportedPage(reader, i);
            rotation = reader.getPageRotation(i);
            if (rotation == 90 || rotation == 270) {
                cb.addTemplate(page, 0, -factor, factor, 0, x1 + dx, y2[p] + dy + rect.height() * factor);
            } else {
                cb.addTemplate(page, factor, 0, 0, factor, x1 + dx, y2[p] + dy);
            }
            cb.setRGBColorStroke(0xC0, 0xC0, 0xC0);
            cb.rectangle(x3 - 5f, y2[p] - 5f, x4 - x3 + 10f, y1[p] - y2[p] + 10f);
            for (float l = y1[p] - 19; l > y2[p]; l -= 16) {
                cb.moveTo(x3, l);
                cb.lineTo(x4, l);
            }
            cb.rectangle(x1 + dx, y2[p] + dy, rect.width() * factor, rect.height() * factor);
            cb.stroke();

            p++;
            if (p == pages) {
                p = 0;
                document.newPage();
            }
        }
        // step 5: we close the document
        document.close();
    } catch (Exception e) {

        System.err.println(e.getMessage());
    }
}

From source file:org.kuali.coeus.common.committee.impl.web.struts.action.CommitteeActionsActionBase.java

License:Open Source License

/**
 * This method merged the pdf bytes without creating page numbers and dates.
 * // www . j av  a 2  s  .com
 * (This is a slimed down version of MergePdfBytes() in PrintingServiceImpl.java)
 * 
 * @param pdfBytesList
 *            List containing the PDF data bytes
 * @param bookmarksList
 *            List of bookmarks corresponding to the PDF bytes.
 * @return
 * @throws PrintingException
 */
private byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    for (int count = 0; count < pdfBytesList.size(); count++) {
        PdfReader reader;
        try {
            reader = new PdfReader(pdfBytesList.get(count));
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            break;
            //              throw new PrintingException(e.getMessage(), e);
        }
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF bytes 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);
            }
            document.open();
        }
        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            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) {
        document.close();
        return mergedPdfReport.toByteArray();
    }

    return null;
}

From source file:org.kuali.coeus.common.impl.print.PrintingServiceImpl.java

License:Open Source License

/**
 * @param pdfBytesList List containing the PDF data bytes
 * @param bookmarksList List of bookmarks corresponding to the PDF bytes.
 * @return/*from  ww w .  j  av a 2  s  .  c o  m*/
 * @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.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java

License:Open Source License

/**
 * This method is for setting the page properties of the document.
 *//*from w ww . jav a 2  s . c  om*/
private void watermarkPageDocument(Document document, PdfWriter writer, PdfReader reader) {
    document.open();
    int totalPages;
    totalPages = reader.getNumberOfPages();
    for (int pageCount = 1; pageCount <= totalPages; pageCount++) {
        PdfContentByte contents = writer.getDirectContent();
        document.setPageSize(reader.getPageSize(pageCount));
        document.newPage();
        PdfImportedPage page = writer.getImportedPage(reader, pageCount);
        contents.addTemplate(page, 1, 0, 0, 1, 0, 0);
    }
    document.close();
}

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.
 *///from  w w w  . j a  v  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;
}