Example usage for com.lowagie.text Rectangle getWidth

List of usage examples for com.lowagie.text Rectangle getWidth

Introduction

In this page you can find the example usage for com.lowagie.text Rectangle getWidth.

Prototype

public float getWidth() 

Source Link

Document

Returns the width of the rectangle.

Usage

From source file:org.geomajas.plugin.print.component.PdfContext.java

License:Open Source License

/**
 * Draws the specified image with the first rectangle's bounds, clipping with the second one.
 *
 * @param img image//  w  w  w  .ja  v  a 2s  .  c  o  m
 * @param rect rectangle
 * @param clipRect clipping bounds
 * @param opacity opacity of the image (1 = opaque, 0= transparent)
 */
public void drawImage(Image img, Rectangle rect, Rectangle clipRect, float opacity) {
    try {
        template.saveState();
        // opacity
        PdfGState state = new PdfGState();
        state.setFillOpacity(opacity);
        state.setBlendMode(PdfGState.BM_NORMAL);
        template.setGState(state);
        // clipping code
        if (clipRect != null) {
            template.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(),
                    clipRect.getHeight());
            template.clip();
            template.newPath();
        }
        template.addImage(img, rect.getWidth(), 0, 0, rect.getHeight(), origX + rect.getLeft(),
                origY + rect.getBottom());
    } catch (DocumentException e) {
        log.warn("could not draw image", e);
    } finally {
        template.restoreState();
    }
}

From source file:org.geomajas.plugin.print.component.PdfContext.java

License:Open Source License

private float getAbsoluteX(float f, Rectangle rect) {
    return rect.getLeft() + f * rect.getWidth();
}

From source file:org.geomajas.plugin.print.component.PdfContext.java

License:Open Source License

/**
 * Draw the specified geometry./*from  ww w . j  av a 2 s  . c  o m*/
 *
 * @param geometry geometry to draw
 * @param symbol symbol for geometry
 * @param fillColor fill colour
 * @param strokeColor stroke colour
 * @param lineWidth line width
 * @param clipRect clipping rectangle
 */
public void drawGeometry(Geometry geometry, SymbolInfo symbol, Color fillColor, Color strokeColor,
        float lineWidth, float[] dashArray, Rectangle clipRect) {
    template.saveState();
    // clipping code
    if (clipRect != null) {
        template.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(),
                clipRect.getHeight());
        template.clip();
        template.newPath();
    }
    setStroke(strokeColor, lineWidth, dashArray);
    setFill(fillColor);
    drawGeometry(geometry, symbol);
    template.restoreState();
}

From source file:org.geomajas.plugin.print.component.PdfContext.java

License:Open Source License

public Graphics2D getGraphics2D(Rectangle clipRect) {
    Graphics2D graphics = template.createGraphics(template.getWidth(), template.getHeight());
    graphics.translate(origX, template.getHeight() - origY - clipRect.getHeight());
    graphics.clipRect(0, 0, (int) clipRect.getWidth(), (int) clipRect.getHeight());
    return graphics;
}

From source file:org.geomajas.plugin.printing.command.print.PrintGetTemplateCommand.java

License:Open Source License

private float getPageSizeRelativeToA3(PrintGetTemplateRequest request) {
    Rectangle r;
    if (request.getPageSize() != null) {
        r = PageSize.getRectangle(request.getPageSize());
    } else {//from  w ww .jav a2s .c  o  m
        float width = request.getTemplate().getPage().getLayoutConstraint().getWidth();
        float height = request.getTemplate().getPage().getLayoutConstraint().getHeight();
        r = new Rectangle(0, 0, width, height);
    }
    return (r.getWidth() / PageSize.A3.getWidth() + r.getHeight() / PageSize.A3.getHeight()) / 2;
}

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  . 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.
 *//*from  w ww . j a  va 2  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.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java

License:Open Source License

/**
 * /*from w  ww .j a  va2s .c o m*/
 * This method for Decorating the PDF with watermark.
 * 
 * @param watermarkPdfStamper - wrapper for pdf content byte and assists in decorating PDF LOg the exception if cannot open/read the file
 *        for decoration
 */
private void decorateWatermark(PdfStamper watermarkPdfStamper, WatermarkBean watermarkBean) {
    watermarkPdfStamper.setFormFlattening(true);
    PdfReader pdfReader = watermarkPdfStamper.getReader();
    int pageCount = pdfReader.getNumberOfPages();
    int pdfPageNumber = 0;

    PdfContentByte pdfContents;
    Rectangle rectangle;
    while (pdfPageNumber < pageCount) {
        pdfPageNumber++;
        pdfContents = watermarkPdfStamper.getOverContent(pdfPageNumber);
        rectangle = pdfReader.getPageSizeWithRotation(pdfPageNumber);
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) {
            decoratePdfWatermarkImage(pdfContents, (int) rectangle.getWidth(), (int) rectangle.getHeight(),
                    watermarkBean);
        }
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) {
            decoratePdfWatermarkText(pdfContents, rectangle, watermarkBean);
        }
        watermarkPdfStamper.setFormFlattening(true);
    }
    try {
        watermarkPdfStamper.close();
    } catch (IOException decorateWatermark) {
        LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: "
                + decorateWatermark.getMessage());
    } catch (DocumentException documentException) {
        LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: "
                + documentException.getMessage());
    }

}

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

License:Open Source License

/**
 * This method is for setting the properties of watermark Text.
 *//*from   w  ww .  j av  a 2  s .c  o m*/
private void decoratePdfWatermarkText(PdfContentByte pdfContentByte, Rectangle rectangle,
        WatermarkBean watermarkBean) {
    float x, y, x1, y1, angle;
    final float OPACITY = 0.3f;
    PdfGState pdfGState = new PdfGState();
    pdfGState.setFillOpacity(OPACITY);
    int pageWidth = (int) rectangle.getWidth();
    int pageHeight = (int) rectangle.getHeight();
    try {
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) {
            pdfContentByte.beginText();
            pdfContentByte.setGState(pdfGState);
            Color fillColor = watermarkBean.getFont().getColor() == null
                    ? WatermarkConstants.DEFAULT_WATERMARK_COLOR
                    : watermarkBean.getFont().getColor();
            pdfContentByte.setColorFill(fillColor);

            if (watermarkBean.getPosition().equals(WatermarkConstants.WATERMARK_POSITION_FOOTER)) {

                pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(),
                        watermarkBean.getPositionFont().getSize());
                if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_CENTER)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkBean.getText(),
                            (rectangle.getLeft(rectangle.getBorderWidthLeft())
                                    + rectangle.getRight(rectangle.getBorderWidthRight())) / 2,
                            rectangle.getBottom(rectangle.getBorderWidthBottom()
                                    + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_RIGHT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_RIGHT, watermarkBean.getText(),
                            rectangle.getRight(rectangle.getBorderWidthRight()),
                            rectangle.getBottom(rectangle.getBorderWidthBottom()
                                    + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_LEFT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(),
                            rectangle.getLeft(rectangle.getBorderWidthLeft()),
                            rectangle.getBottom(rectangle.getBorderWidthBottom()
                                    + watermarkBean.getPositionFont().getSize()),
                            0);
                }
            } else if (watermarkBean.getPosition().equals(WatermarkConstants.WATERMARK_POSITION_HEADER)) {
                pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(),
                        watermarkBean.getPositionFont().getSize());
                if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_CENTER)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkBean.getText(),
                            (rectangle.getLeft(rectangle.getBorderWidthLeft())
                                    + rectangle.getRight(rectangle.getBorderWidthRight())) / 2,
                            rectangle.getTop(
                                    rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_RIGHT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_RIGHT, watermarkBean.getText(),
                            rectangle.getRight(rectangle.getBorderWidthRight()),
                            rectangle.getTop(
                                    rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_LEFT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(),
                            rectangle.getLeft(rectangle.getBorderWidthLeft()),
                            rectangle.getTop(
                                    rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()),
                            0);
                }
            } else {
                pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(),
                        watermarkBean.getFont().getSize());
                int textWidth = (int) pdfContentByte.getEffectiveStringWidth(watermarkBean.getText(), false);
                int diagonal = (int) Math.sqrt((pageWidth * pageWidth) + (pageHeight * pageHeight));
                int pivotPoint = (diagonal - textWidth) / 2;

                angle = (float) Math.atan((float) pageHeight / pageWidth);

                x = (float) (pivotPoint * pageWidth) / diagonal;
                y = (float) (pivotPoint * pageHeight) / diagonal;

                x1 = (float) (((float) watermarkBean.getFont().getSize() / 2) * Math.sin(angle));
                y1 = (float) (((float) watermarkBean.getFont().getSize() / 2) * Math.cos(angle));

                pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(), x + x1, y - y1,
                        (float) Math.toDegrees(angle));
            }
            pdfContentByte.endText();
        }
    } catch (Exception exception) {
        LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: " + exception.getMessage());
    }

}

From source file:org.locationtech.udig.printing.ui.pdf.ExportPDFWizard.java

License:Open Source License

@Override
public boolean performFinish() {

    //create the document                 
    Rectangle suggestedPageSize = getITextPageSize(page1.getPageSize());
    Rectangle pageSize = rotatePageIfNecessary(suggestedPageSize); //rotate if we need landscape

    Document document = new Document(pageSize);

    try {//from  w  w  w. jav  a 2 s.c  o m

        //Basic setup of the Document, and get instance of the iText Graphics2D
        //   to pass along to uDig's standard "printing" code.
        String outputFile = page1.getDestinationDir() + System.getProperty("file.separator") + //$NON-NLS-1$
                page1.getOutputFile();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();
        Graphics2D graphics = null;
        Template template = getTemplate();

        int i = 0;
        int numPages = 1;
        do {

            //sets the active page
            template.setActivePage(i);

            PdfContentByte cb = writer.getDirectContent();

            Page page = makePage(pageSize, document, template);

            graphics = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight());

            //instantiate a PrinterEngine (pass in the Page instance)
            PrintingEngine engine = new PrintingEngine(page);

            //make page format
            PageFormat pageFormat = new PageFormat();
            pageFormat.setOrientation(PageFormat.PORTRAIT);
            java.awt.print.Paper awtPaper = new java.awt.print.Paper();
            awtPaper.setSize(pageSize.getWidth() * 3, pageSize.getHeight() * 3);
            awtPaper.setImageableArea(0, 0, pageSize.getWidth(), pageSize.getHeight());
            pageFormat.setPaper(awtPaper);

            //run PrinterEngine's print function
            engine.print(graphics, pageFormat, 0);

            graphics.dispose();
            document.newPage();
            if (i == 0) {
                numPages = template.getNumPages();
            }
            i++;

        } while (i < numPages);

        //cleanup
        document.close();
        writer.close();
    } catch (DocumentException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (PrinterException e) {
        e.printStackTrace();
    }
    return true;
}