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

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

Introduction

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

Prototype

int getPageRotation(PdfDictionary page) 

Source Link

Usage

From source file:br.gov.jfrj.itextpdf.Documento.java

License:Open Source License

public static byte[] stamp(byte[] abPdf, String sigla, boolean rascunho, boolean cancelado, boolean semEfeito,
        boolean internoProduzido, String qrCode, String mensagem, Integer paginaInicial, Integer paginaFinal,
        Integer cOmitirNumeracao, String instancia, String orgaoUsu) throws DocumentException, IOException {

    PdfReader pdfIn = new PdfReader(abPdf);
    Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
    // final SimpleDateFormat sdf = new SimpleDateFormat(
    // "EEE MMM dd HH:mm:ss zzz yyyy");
    // doc.add(new Meta("creationdate", sdf.format(new Date(0L))));
    final ByteArrayOutputStream boA4 = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(doc, boA4);
    doc.open();//from  w  ww .  j av a  2 s .  c o  m
    PdfContentByte cb = writer.getDirectContent();

    // Resize every page to A4 size
    //
    // double thetaRotation = 0.0;
    for (int i = 1; i <= pdfIn.getNumberOfPages(); i++) {
        int rot = pdfIn.getPageRotation(i);
        float left = pdfIn.getPageSize(i).getLeft();
        float bottom = pdfIn.getPageSize(i).getBottom();
        float top = pdfIn.getPageSize(i).getTop();
        float right = pdfIn.getPageSize(i).getRight();

        PdfImportedPage page = writer.getImportedPage(pdfIn, i);
        float w = page.getWidth();
        float h = page.getHeight();

        // Logger.getRootLogger().error("----- dimensoes: " + rot + ", " + w
        // + ", " + h);

        doc.setPageSize((rot != 0 && rot != 180) ^ (w > h) ? PageSize.A4.rotate() : PageSize.A4);
        doc.newPage();

        cb.saveState();

        if (rot != 0 && rot != 180) {
            float swap = w;
            w = h;
            h = swap;
        }

        float pw = doc.getPageSize().getWidth();
        float ph = doc.getPageSize().getHeight();
        double scale = Math.min(pw / w, ph / h);

        // do my transformations :
        cb.transform(AffineTransform.getScaleInstance(scale, scale));

        if (!internoProduzido) {
            cb.transform(AffineTransform.getTranslateInstance(pw * SAFETY_MARGIN, ph * SAFETY_MARGIN));
            cb.transform(AffineTransform.getScaleInstance(1.0f - 2 * SAFETY_MARGIN, 1.0f - 2 * SAFETY_MARGIN));
        }

        if (rot != 0) {
            double theta = -rot * (Math.PI / 180);
            if (rot == 180) {
                cb.transform(AffineTransform.getRotateInstance(theta, w / 2, h / 2));
            } else {
                cb.transform(AffineTransform.getRotateInstance(theta, h / 2, w / 2));
            }
            if (rot == 90) {
                cb.transform(AffineTransform.getTranslateInstance((w - h) / 2, (w - h) / 2));
            } else if (rot == 270) {
                cb.transform(AffineTransform.getTranslateInstance((h - w) / 2, (h - w) / 2));
            }
        }

        // Logger.getRootLogger().error(
        // "----- dimensoes: " + rot + ", " + w + ", " + h);
        // Logger.getRootLogger().error("----- page: " + pw + ", " + ph);

        // cb.transform(AffineTransform.getTranslateInstance(
        // ((pw / scale) - w) / 2, ((ph / scale) - h) / 2));

        // put the page
        cb.addTemplate(page, 0, 0);

        // draw a red rectangle at the page borders
        //
        // cb.saveState();
        // cb.setColorStroke(Color.red);
        // cb.rectangle(pdfIn.getPageSize(i).getLeft(), pdfIn.getPageSize(i)
        // .getBottom(), pdfIn.getPageSize(i).getRight(), pdfIn
        // .getPageSize(i).getTop());
        // cb.stroke();
        // cb.restoreState();

        cb.restoreState();
    }
    doc.close();

    abPdf = boA4.toByteArray();

    final ByteArrayOutputStream bo2 = new ByteArrayOutputStream();

    final PdfReader reader = new PdfReader(abPdf);

    final int n = reader.getNumberOfPages();
    final PdfStamper stamp = new PdfStamper(reader, bo2);

    // adding content to each page
    int i = 0;
    PdfContentByte under;
    PdfContentByte over;
    final BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);

    // Image img = Image.getInstance("watermark.jpg");
    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    byte maskr[] = { (byte) 0xff };
    Image mask = Image.getInstance(1, 1, 1, 1, maskr);
    mask.makeMask();
    mask.setInverted(true);

    while (i < n) {
        i++;
        // watermark under the existing page
        under = stamp.getUnderContent(i);
        over = stamp.getOverContent(i);

        final Barcode39 code39 = new Barcode39();
        // code39.setCode(doc.getCodigo());
        code39.setCode(sigla.replace("-", "").replace("/", "").replace(".", ""));
        code39.setStartStopText(false);
        final Image image39 = code39.createImageWithBarcode(over, null, null);
        Rectangle r = stamp.getReader().getPageSizeWithRotation(i);

        image39.setInitialRotation((float) Math.PI / 2.0f);
        image39.setAbsolutePosition(
                r.getWidth() - image39.getHeight() + (STAMP_BORDER_IN_CM - PAGE_BORDER_IN_CM) * CM_UNIT,
                BARCODE_HEIGHT_IN_CM * CM_UNIT);

        image39.setBackgroundColor(Color.green);
        image39.setBorderColor(Color.RED);
        image39.setBorderWidth(0.5f * CM_UNIT);

        image39.setImageMask(mask);

        over.setRGBColorFill(255, 255, 255);
        mask.setAbsolutePosition(r.getWidth() - image39.getHeight() - (PAGE_BORDER_IN_CM) * CM_UNIT,
                (BARCODE_HEIGHT_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
        mask.scaleAbsolute(image39.getHeight() + 2 * STAMP_BORDER_IN_CM * CM_UNIT,
                image39.getWidth() + 2 * STAMP_BORDER_IN_CM * CM_UNIT);
        over.addImage(mask);

        over.setRGBColorFill(0, 0, 0);
        over.addImage(image39);

        // over.addImage(mask, mask.getScaledWidth() * 8, 0, 0,
        // mask.getScaledHeight() * 8, 100, 450);

        if (qrCode != null) {
            java.awt.Image imgQRCode = createQRCodeImage(qrCode);
            Image imageQRCode = Image.getInstance(imgQRCode, Color.BLACK, true);
            imageQRCode.scaleAbsolute(QRCODE_SIZE_IN_CM * CM_UNIT, QRCODE_SIZE_IN_CM * CM_UNIT);
            imageQRCode.setAbsolutePosition(QRCODE_LEFT_MARGIN_IN_CM * CM_UNIT, PAGE_BORDER_IN_CM * CM_UNIT);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition((QRCODE_LEFT_MARGIN_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute((QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    (QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT);
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            over.addImage(imageQRCode);
        }

        if (mensagem != null) {
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(r.getWidth() - image39.getHeight() - (QRCODE_LEFT_MARGIN_IN_CM
                    + QRCODE_SIZE_IN_CM + 4 * STAMP_BORDER_IN_CM + PAGE_BORDER_IN_CM) * CM_UNIT);
            PdfPCell cell = new PdfPCell(new Paragraph(mensagem,
                    FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.BLACK)));
            cell.setBorderWidth(0);
            table.addCell(cell);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition(
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute(2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalWidth(),
                    2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalHeight());
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            table.writeSelectedRows(0, -1,
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    table.getTotalHeight() + PAGE_BORDER_IN_CM * CM_UNIT, over);
        }

        if (cancelado) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "CANCELADO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (rascunho) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "MINUTA", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (semEfeito) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "SEM EFEITO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // if (!rascunho
        // && request.getRequestURL().indexOf("http://laguna/") == -1) {

        if (!rascunho && !cancelado && !semEfeito && ((!Contexto.resource("isVersionTest").equals("false"))
                || (!Contexto.resource("isBaseTest").equals("false")))) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "INVLIDO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // Imprime um circulo com o numero da pagina dentro.

        if (paginaInicial != null) {
            String sFl = String.valueOf(paginaInicial + i - 1);
            // Se for a ultima pagina e o numero nao casar, acrescenta "-" e
            // pagina final
            if (n == i) {
                if (paginaFinal != paginaInicial + n - 1) {
                    sFl = sFl + "-" + String.valueOf(paginaFinal);
                }
            }
            if (i > cOmitirNumeracao) {

                // Raio do circulo interno
                final float radius = 18f;

                // Distancia entre o circulo interno e o externo
                final float circleInterspace = Math.max(helv.getAscentPoint(instancia, TEXT_HEIGHT),
                        helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT))
                        - Math.min(helv.getDescentPoint(instancia, TEXT_HEIGHT),
                                helv.getDescentPoint(orgaoUsu, TEXT_HEIGHT))
                        + 2 * TEXT_TO_CIRCLE_INTERSPACE;

                // Centro do circulo
                float xCenter = r.getWidth() - 1.8f * (radius + circleInterspace);
                float yCenter = r.getHeight() - 1.8f * (radius + circleInterspace);

                over.saveState();
                final PdfGState gs = new PdfGState();
                gs.setFillOpacity(1f);
                over.setGState(gs);
                over.setColorFill(Color.BLACK);

                over.saveState();
                over.setColorStroke(Color.black);
                over.setLineWidth(1f);
                over.setColorFill(Color.WHITE);

                // Circulo externo
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.fill();
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.stroke();

                // Circulo interno
                over.circle(xCenter, yCenter, radius);
                over.stroke();
                over.restoreState();

                {
                    over.saveState();
                    over.beginText();
                    over.setFontAndSize(helv, TEXT_HEIGHT);

                    // Escreve o texto superior do carimbo
                    float fDescent = helv.getDescentPoint(instancia, TEXT_HEIGHT);
                    showTextOnArc(over, instancia, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius - fDescent + TEXT_TO_CIRCLE_INTERSPACE, true);

                    // Escreve o texto inferior
                    float fAscent = helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT);
                    showTextOnArc(over, orgaoUsu, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius + fAscent + TEXT_TO_CIRCLE_INTERSPACE, false);
                    over.endText();
                    over.restoreState();
                }

                over.beginText();
                int textHeight = 23;

                // Diminui o tamanho do font ate que o texto caiba dentro do
                // circulo interno
                while (helv.getWidthPoint(sFl, textHeight) > (2 * (radius - TEXT_TO_CIRCLE_INTERSPACE)))
                    textHeight--;
                float fAscent = helv.getAscentPoint(sFl, textHeight) + helv.getDescentPoint(sFl, textHeight);
                over.setFontAndSize(helv, textHeight);
                over.showTextAligned(Element.ALIGN_CENTER, sFl, xCenter, yCenter - 0.5f * fAscent, 0);
                over.endText();
                over.restoreState();
            }
        }

    }
    stamp.close();
    return bo2.toByteArray();
}

From source file:com.moss.pdf.template.core.Renderer.java

License:Open Source License

public void render(InputStream in, List<? extends PropertyMapping> fields, OutputStream out) throws Exception {

    PdfReader reader = new PdfReader(in);

    Document document = new Document(reader.getPageSizeWithRotation(1));

    PdfWriter writer = PdfWriter.getInstance(document, out);

    document.open();/* w  w  w  . ja va2 s.  c o  m*/

    for (int i = 1; i <= reader.getNumberOfPages(); i++) {

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage customPage = writer.getImportedPage(reader, i);

        /*
         * add the page to our new document, turning this page to its 
         * original rotation
         */
        int pageRotation = reader.getPageRotation(i);

        if (pageRotation > 0) {

            System.out.println("page rotation found: " + pageRotation);

            double angle = -((2 * Math.PI) * pageRotation / 360);
            //         double angle = -(Math.PI / 2);

            cb.addTemplate(customPage, (float) Math.cos(angle), (float) Math.sin(angle),
                    (float) -Math.sin(angle), (float) Math.cos(angle), 0f, // x
                    document.top() + document.topMargin() // y
            );
        } else {
            cb.addTemplate(customPage, 0f, 0f);
        }

        Map<FontName, BaseFont> fonts = new HashMap<FontName, BaseFont>();

        for (PropertyMapping field : fields) {

            if (field.getPageNumber() != i) {
                continue;
            }

            /*
             * Only builtin fonts are supported at the moment
             */
            BaseFont font;
            int fontSize;
            int alignment;
            String text;
            float x, y;
            float rotation;

            {
                font = fonts.get(field.getFontName());

                if (font == null) {

                    FontName e = field.getFontName();
                    String name = null;

                    if (FontName.COURIER == e) {
                        name = BaseFont.COURIER;
                    } else if (FontName.COURIER_BOLD == e) {
                        name = BaseFont.COURIER_BOLD;
                    } else if (FontName.COURIER_BOLD_OBLIQUE == e) {
                        name = BaseFont.COURIER_BOLDOBLIQUE;
                    } else if (FontName.COURIER_OBLIQUE == e) {
                        name = BaseFont.COURIER_OBLIQUE;
                    } else if (FontName.HELVETICA == e) {
                        name = BaseFont.HELVETICA;
                    } else if (FontName.HELVETICA_BOLD == e) {
                        name = BaseFont.HELVETICA_BOLD;
                    } else if (FontName.HELVETICA_BOLD_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_BOLDOBLIQUE;
                    } else if (FontName.HELVETICA_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_OBLIQUE;
                    } else if (FontName.TIMES_BOLD == e) {
                        name = BaseFont.TIMES_BOLD;
                    } else if (FontName.TIMES_BOLD_ITALIC == e) {
                        name = BaseFont.TIMES_BOLDITALIC;
                    } else if (FontName.TIMES_ITALIC == e) {
                        name = BaseFont.TIMES_ITALIC;
                    } else if (FontName.TIMES_ROMAN == e) {
                        name = BaseFont.TIMES_ROMAN;
                    }

                    if (name == null) {
                        throw new RuntimeException("Unknown font type: " + e);
                    }

                    font = BaseFont.createFont(name, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
                    fonts.put(field.getFontName(), font);
                }

                fontSize = field.getFontSize();

                if (TextAlignment.LEFT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_LEFT;
                } else if (TextAlignment.CENTER == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_CENTER;
                } else if (TextAlignment.RIGHT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_RIGHT;
                } else {
                    alignment = PdfContentByte.ALIGN_LEFT;
                }

                Object value = p.eval(field.getExpr());

                if (value == null) {
                    text = "";
                } else {
                    text = value.toString();
                }

                x = field.getX() * POINTS_IN_A_CM;
                y = field.getY() * POINTS_IN_A_CM;

                rotation = 0;
            }

            cb.beginText();

            cb.setFontAndSize(font, fontSize);

            cb.showTextAligned(alignment, text, x, y, rotation);

            cb.endText();
        }

        document.newPage();
    }

    reader.close();
    document.close();
}

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  .ja  v a 2 s  .co  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.
 *//*  w ww  .j a  va2  s  . c om*/
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 handouts(String file) {
    try {/*from  www  . ja  va  2s . 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.sejda.impl.itext.component.AbstractPdfCopier.java

License:Apache License

public void addBlankPage(PdfReader reader) {
    pdfCopy.addPage(reader.getPageSize(1), reader.getPageRotation(1));
    numberOfCopiedPages++;
}

From source file:questions.importpages.HelloWorldImportedPages.java

public static void main(String[] args) {
    // we create a PDF file
    createPdf(SOURCE);/*from   w  w  w  .  j a v  a 2 s . c o  m*/
    // step 1
    Document document = new Document(PageSize.A4);
    try {
        // we create a PdfReader object
        PdfReader reader = new PdfReader(SOURCE);
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // step 3
        document.open();
        // step 4
        PdfImportedPage page;
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            page = writer.getImportedPage(reader, i);
            Image image = Image.getInstance(page);
            image.scalePercent(15f);
            image.setBorder(Rectangle.BOX);
            image.setBorderWidth(3f);
            image.setBorderColor(new GrayColor(0.5f));
            image.setRotationDegrees(-reader.getPageRotation(i));
            document.add(image);
            document.add(new Paragraph("This is page: " + i));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    // step 5
    document.close();
}

From source file:s2s.luna.reports.Stampa_documento.java

License:GNU General Public License

@SuppressWarnings("CallToThreadDumpStack")
private boolean addPDF(String titolo, byte[] fileContent, Document document, PdfWriter writer) {
    try {//from   ww  w  .  j a va2  s .c  o  m
        // Inizializzo il contenitore del pdf da importare.
        PdfContentByte cb = writer.getDirectContent();

        // Inizializzo la variabile dove appogger (una alla volta)
        // le pagine del pdf da importare.
        PdfImportedPage page;

        // Apro in lettura il pdf da importare.
        PdfReader pdfReader = new PdfReader(fileContent);

        // Ne determino il numero di pagine totali.
        int pdfPageNumber = pdfReader.getNumberOfPages();

        // Inzializzo il contatore delle pagine.
        int pageOfCurrentReaderPDF = 1;

        // Per ogni pagina...
        while (pageOfCurrentReaderPDF <= pdfPageNumber) {
            // Creo una nuova pagina vuota sul pdf di destinazione.
            document.newPage();
            // Estraggo la pagina dal pdf da importare.
            page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
            // Coverto la pagina in un immagine.
            Image pageImg = Image.getInstance(page);
            // Aggiungo la pagina estratta al pdf di destinazione, ruotandola se necessario.
            PdfPTable table = new PdfPTable(1);
            PdfPCell defaultCell = table.getDefaultCell();
            defaultCell.setRotation(-pdfReader.getPageRotation(pageOfCurrentReaderPDF));
            defaultCell.setBorder(Rectangle.NO_BORDER);
            table.addCell(pageImg);
            document.add(table);
            // Incremento il contatore delle pagine
            pageOfCurrentReaderPDF++;
        }
        return true;
    } catch (Exception ex) {
        // Eccezione silenziosa.
        // Gestisce il caso in cui si verifica un errore non previsto
        ex.printStackTrace();
        return false;
    }
}