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

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

Introduction

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

Prototype

public Rectangle getPageSizeWithRotation(PdfDictionary page) 

Source Link

Document

Gets the rotated page from a page dictionary.

Usage

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  .j a v  a2  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 .  j  ava2 s .c  o 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 {/*  w ww. j  a  v a2s  .  c om*/

        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  ww  . j av a2 s  . c o m
        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.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void add(int pageCount, PdfPageData currentPageData, InsertBlankPDFPage addPage) {
    File tempFile = null;/*from   w w w. j  a  v a2 s.co  m*/

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    int pageToInsertBefore = addPage.getInsertBefore();

    boolean insertAsLastPage = false;
    if (pageToInsertBefore == -1)
        return;
    else if (pageToInsertBefore == -2)
        insertAsLastPage = true;

    try {
        PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));

        if (insertAsLastPage)
            stamp.insertPage(pageCount + 1, reader.getPageSizeWithRotation(pageCount));
        else
            stamp.insertPage(pageToInsertBefore, reader.getPageSizeWithRotation(pageToInsertBefore));

        stamp.close();
    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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

License:Open Source License

public void addHeaderFooter(int pageCount, PdfPageData currentPageData,
        final AddHeaderFooterToPDFPages addHeaderFooter) {
    File tempFile = null;/* w w w. j  ava  2  s .  c o m*/

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {

        int[] pgsToEdit = addHeaderFooter.getPages();

        if (pgsToEdit == null)
            return;

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

        final PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));

        String chosenFont = addHeaderFooter.getFontName();
        Color chosenFontColor = addHeaderFooter.getFontColor();
        int chosenFontSize = addHeaderFooter.getFontSize();

        float chosenLeftRightMargin = addHeaderFooter.getLeftRightMargin();
        float chosenTopBottomMargin = addHeaderFooter.getTopBottomMargin();

        String text[] = new String[6];
        text[0] = addHeaderFooter.getLeftHeader();
        text[1] = addHeaderFooter.getCenterHeader();
        text[2] = addHeaderFooter.getRightHeader();
        text[3] = addHeaderFooter.getLeftFooter();
        text[4] = addHeaderFooter.getCenterFooter();
        text[5] = addHeaderFooter.getRightFooter();

        Date date = new Date();
        String shortDate = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
        String longDate = DateFormat.getDateInstance(DateFormat.LONG).format(date);

        SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
        String time12 = formatter.format(date);

        formatter = new SimpleDateFormat("HH.mm.ss");
        String time24 = formatter.format(date);

        String fileName = new File(selectedFile).getName();

        BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false);

        for (int page = 1; page <= pageCount; page++) {
            if (pagesToEdit.contains(new Integer(page))) {
                String[] textCopy = new String[text.length];
                System.arraycopy(text, 0, textCopy, 0, text.length);

                for (int i = 0; i < 6; i++) {
                    textCopy[i] = textCopy[i].replaceAll("<d>", shortDate);
                    textCopy[i] = textCopy[i].replaceAll("<D>", longDate);
                    textCopy[i] = textCopy[i].replaceAll("<t>", time12);
                    textCopy[i] = textCopy[i].replaceAll("<T>", time24);
                    textCopy[i] = textCopy[i].replaceAll("<f>", fileName);
                    textCopy[i] = textCopy[i].replaceAll("<F>", selectedFile);
                    textCopy[i] = textCopy[i].replaceAll("<p>", "" + page);
                    textCopy[i] = textCopy[i].replaceAll("<P>", "" + pageCount);
                }

                PdfContentByte cb = stamp.getOverContent(page);

                cb.beginText();
                cb.setColorFill(chosenFontColor);
                cb.setFontAndSize(font, chosenFontSize);

                Rectangle pageSize = reader.getPageSizeWithRotation(page);

                cb.showTextAligned(Element.ALIGN_LEFT, textCopy[0], chosenLeftRightMargin,
                        pageSize.height() - chosenTopBottomMargin, 0);
                cb.showTextAligned(Element.ALIGN_CENTER, textCopy[1], pageSize.width() / 2,
                        pageSize.height() - chosenTopBottomMargin, 0);
                cb.showTextAligned(Element.ALIGN_RIGHT, textCopy[2], pageSize.width() - chosenLeftRightMargin,
                        pageSize.height() - chosenTopBottomMargin, 0);

                cb.showTextAligned(Element.ALIGN_LEFT, textCopy[3], chosenLeftRightMargin,
                        chosenTopBottomMargin, 0);
                cb.showTextAligned(Element.ALIGN_CENTER, textCopy[4], pageSize.width() / 2,
                        chosenTopBottomMargin, 0);
                cb.showTextAligned(Element.ALIGN_RIGHT, textCopy[5], pageSize.width() - chosenLeftRightMargin,
                        chosenTopBottomMargin, 0);

                cb.endText();
            }
        }

        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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

License:Apache License

/**
 * <p>/*from   w w  w  .j a v  a2s.  c  om*/
 * 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.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.
 * //from  ww w.  jav a  2  s .c o m
 * (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   w w w  .j av  a2  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 for attach watermark with PDF with the help of PdfReader and PdfStamper
 * //from   w  ww .j a v  a  2s.  c o  m
 * @param pdfContent pdfContent
 * @throws DocumentException throws this exception if cannot decorate the pdf
 * @return byteArrayOutputStream
 */
private ByteArrayOutputStream attachWatermarking(WatermarkBean watermarkBean, byte pdfContent[]) {

    PdfReader pdfReader;
    PdfReader reader;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream copyByteArrayOutputStream = new ByteArrayOutputStream();
    PdfStamper pdfStamp;
    Document document = null;
    PdfWriter writer = null;
    int nop;
    try {
        reader = new PdfReader(pdfContent);
        pdfReader = new PdfReader(pdfContent);
        nop = reader.getNumberOfPages();
        document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                : new com.lowagie.text.Document();
        writer = PdfWriter.getInstance(document, byteArrayOutputStream);
        watermarkPageDocument(document, writer, reader);
        byte[] bs = byteArrayOutputStream.toByteArray();
        pdfReader = new PdfReader(bs);
        pdfStamp = new PdfStamper(pdfReader, copyByteArrayOutputStream);
        decorateWatermark(pdfStamp, watermarkBean);
    } catch (IOException decorateWatermark) {
        LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: "
                + decorateWatermark.getMessage());
    } catch (DocumentException documentException) {
        LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: "
                + documentException.getMessage());
    }
    return copyByteArrayOutputStream;
}