Example usage for com.lowagie.text Rectangle Rectangle

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

Introduction

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

Prototype

public Rectangle(float urx, float ury) 

Source Link

Document

Constructs a Rectangle -object starting from the origin (0, 0).

Usage

From source file:org.geomajas.plugin.print.component.impl.LegendGraphicComponentImpl.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override//from   w  ww. j  a  va2 s  .c  om
public void calculateSize(PdfContext context) {
    LegendComponent legendComponent = getLegend();
    assert (null != legendComponent) : "LegendGraphicComponent must be an instance of LegendComponent";
    assert (null != legendComponent
            .getFont()) : "LegendGraphicComponent must be an instance of LegendComponent";

    Rectangle textSize = context.getTextSize(label, legendComponent.getFont());
    float margin = 0.25f * legendComponent.getFont().getSize();
    getConstraint().setMarginX(margin);
    getConstraint().setMarginY(margin);
    setBounds(new Rectangle(textSize.getHeight(), textSize.getHeight()));
}

From source file:org.geomajas.plugin.print.component.impl.LegendIconComponentImpl.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override//from   ww  w  .  j  av  a  2  s  .c om
public void calculateSize(PdfContext context) {
    LegendComponent legendComponent = getLegend();
    assert (null != legendComponent) : "LegendGraphicComponent must be a descendant of a LegendComponent";

    Rectangle textSize = context.getTextSize(label, legendComponent.getFont());
    float margin = 0.25f * legendComponent.getFont().getSize();
    if (getConstraint().getMarginX() <= 0.0) {
        getConstraint().setMarginX(margin);
    }
    if (getConstraint().getMarginY() <= 0.0) {
        getConstraint().setMarginY(margin);
    }
    setBounds(new Rectangle(textSize.getHeight(), textSize.getHeight()));
}

From source file:org.geomajas.plugin.print.component.impl.LegendViaUrlComponentImpl.java

License:Open Source License

@Override
public void calculateSize(PdfContext context) {

    if (null == getLegendImageServiceUrl()) {
        log.error("getLegendImageServiceUrl() returns unexpectedly with NULL");
        setBounds(new Rectangle(0, 0));
        return; // Abort
    }/*  w w w  .j av a2 s. c om*/

    String locale = getLocale();
    try {
        if (null != locale && !locale.isEmpty()) {
            resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME, new Locale(locale));
        } else {
            resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME);
        }
    } catch (MissingResourceException e) {
        resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME, new Locale("en'"));
    }

    if (getConstraint().getMarginX() <= 0.0f) {
        getConstraint().setMarginX(MARGIN_LEFT_IMAGE_RELATIVE_TO_FONTSIZE * getLegend().getFont().getSize());
    }
    if (getConstraint().getMarginY() <= 0.0f) {
        getConstraint().setMarginY(MARGIN_TOP_IMAGE_RELATIVE_TO_FONTSIZE * getLegend().getFont().getSize());
    }

    @SuppressWarnings("deprecation")
    float width = getConstraint().getWidth();
    @SuppressWarnings("deprecation")
    float height = getConstraint().getHeight();

    // Retrieve legend image from URL if not yet retrieved
    if (null == image && visible && null == warning) {
        if (getLegendImageServiceUrl().contains("=image/png")) {
            // Its approx. 2 times faster to use PngImage.getImage() instead of Image.getInstance()
            // since the latter will retrieve the URL twice!
            try {
                image = PngImage.getImage(new URL(getLegendImageServiceUrl()));
                // Image.getInstance(new URL(getLegendImageServiceUrl()));
                image.setDpi(DPI_FOR_IMAGE, DPI_FOR_IMAGE); // Increase the precision
            } catch (MalformedURLException e) {
                log.error("Error in Image.getInstance() for URL " + getLegendImageServiceUrl(), e);
                e.printStackTrace();
            } catch (IOException e) {
                // This exception is OK if no legend image is generated because out of scale range
                // for a dynamic layer, then a text message which indicates an invisible legend is referred
                // to by the URL 
                visible = !hasInVisibleResponse();
                if (visible) {
                    log.warn("Unexpected IOException for Image.getInstance() for URL "
                            + getLegendImageServiceUrl(), e);
                }
            }
        } else {
            try {
                image = Image.getInstance(new URL(getLegendImageServiceUrl()));
                image.setDpi(DPI_FOR_IMAGE, DPI_FOR_IMAGE); // Increase the precision
            } catch (BadElementException e) {
                log.error("Error in Image.getInstance() for URL " + getLegendImageServiceUrl(), e);
                e.printStackTrace();
            } catch (MalformedURLException e) {
                log.error("Error in Image.getInstance() for URL " + getLegendImageServiceUrl(), e);
                e.printStackTrace();
            } catch (IOException e) {
                // This exception is OK if no legend image is generated because out of scale range
                // for a dynamic layer, then a text message which indicates an invisible legend is referred
                // to by the URL 
                visible = !hasInVisibleResponse();
                if (visible) {
                    log.warn("Unexpected IOException for Image.getInstance() for URL "
                            + getLegendImageServiceUrl(), e);
                }
            }

        }
    }
    if (!visible) {
        setBounds(new Rectangle(0, 0));
    } else if (null == image) {
        generateWarningMessage(context);
    } else {

        if (width <= 0 && height <= 0) {
            // when / 2.0f: The image is generated with a scale of 1:0.5 (but looks awful!)
            width = image.getWidth(); // 2.0f;
            height = image.getHeight(); // 2.0f;
        } else if (width <= 0) {
            width = image.getWidth() / image.getHeight() * height;
        } else if (height <= 0) {
            height = image.getHeight() / image.getWidth() * width;
        }

        setBounds(new Rectangle(width, height)); // excluding the marginX
    }
}

From source file:org.geomajas.plugin.print.component.impl.LegendViaUrlComponentImpl.java

License:Open Source License

@SuppressWarnings("deprecation")
private void generateWarningMessage(PdfContext context) {
    warning = resourceBundle.getString("ErrorRetrievingLegend");

    Rectangle textSize = context.getTextSize(warning, getFont());
    float margin = 0.5f * getFont().getSize();

    setBounds(new Rectangle(textSize.getWidth() + 2.0f * margin, textSize.getHeight() + 2 * margin));
}

From source file:org.geomajas.plugin.print.component.impl.PrintComponentImpl.java

License:Open Source License

/**
 * Return a rectangle with the size of this component and origin (0,0).
 * //from  w  w  w  .  j av  a2 s .  c om
 * @return rectangle with the size of this component
 */
protected Rectangle getSize() {
    return new Rectangle(getBounds().getWidth(), getBounds().getHeight());
}

From source file:org.geomajas.plugin.print.component.impl.VectorLayerComponentImpl.java

License:Open Source License

private Rectangle calculateLabelRect(PdfContext context, InternalFeature f, String label, Font font) {
    Rectangle textSize = context.getTextSize(label, font);
    float margin = 0.25f * font.getSize();
    Rectangle rect = new Rectangle(textSize.getWidth() + 2 * margin, textSize.getHeight() + 2 * margin);
    Coordinate labelPosition = geoService.calcDefaultLabelPosition(f);
    // SPRINT-53 Labels should be rendered in Screen Space
    new MapToUserFilter().filter(labelPosition);

    context.moveRectangleTo(rect, (float) labelPosition.x - rect.getWidth() / 2f,
            (float) labelPosition.y - rect.getHeight() / 2f);
    if (f.getGeometry() instanceof Point) {
        float shiftHeight = 0.5f * (rect.getHeight() + getSymbolHeight(f));
        // move up 15 pixels to make the symbol visible
        context.moveRectangleTo(rect, rect.getLeft(), rect.getBottom() + shiftHeight + SYMBOL_CONNECT_LENGTH);
    }//  w w w. j a va  2 s  .  c o  m
    if (rect.getLeft() < 0) {
        context.moveRectangleTo(rect, 10, rect.getBottom());
    }
    if (rect.getBottom() < 0) {
        context.moveRectangleTo(rect, rect.getLeft(), 10);
    }
    if (rect.getTop() > getBounds().getHeight()) {
        context.moveRectangleTo(rect, rect.getLeft(), getBounds().getHeight() - rect.getHeight() - 10);
    }
    if (rect.getRight() > getBounds().getWidth()) {
        context.moveRectangleTo(rect, getBounds().getWidth() - rect.getWidth() - 10, rect.getBottom());
    }
    return rect;
}

From source file:org.geomajas.plugin.print.document.SinglePageDocument.java

License:Open Source License

/**
 * Prepare the document before rendering.
 * /* ww w  .  j  av  a2 s  .  c  o  m*/
 * @param outputStream output stream to render to, null if only for layout
 * @param format format
 * @throws DocumentException oops
 * @throws IOException oops
 * @throws PrintException oops
 */
private void doRender(OutputStream outputStream, Format format)
        throws IOException, DocumentException, PrintException {
    // first render or re-render for different layout
    if (outputStream == null || baos == null || null != format) {
        if (baos == null) {
            baos = new ByteArrayOutputStream(); // let it grow as much as needed
        }
        baos.reset();
        boolean resize = false;
        if (page.getBounds().getWidth() == 0 || page.getBounds().getHeight() == 0) {
            resize = true;
        }
        // Create a document in the requested ISO scale.
        Document document = new Document(page.getBounds(), 0, 0, 0, 0);
        PdfWriter writer;
        writer = PdfWriter.getInstance(document, baos);

        // Render in correct colors for transparent rasters
        writer.setRgbTransparencyBlending(true);

        // The mapView is not scaled to the document, we assume the mapView
        // has the right ratio.

        // Write document title and metadata
        document.open();
        PdfContext context = new PdfContext(writer);
        context.initSize(page.getBounds());
        // first pass of all children to calculate size
        page.calculateSize(context);
        if (resize) {
            // we now know the bounds of the document
            // round 'm up and restart with a new document
            int width = (int) Math.ceil(page.getBounds().getWidth());
            int height = (int) Math.ceil(page.getBounds().getHeight());
            page.getConstraint().setWidth(width);
            page.getConstraint().setHeight(height);

            document = new Document(new Rectangle(width, height), 0, 0, 0, 0);
            writer = PdfWriter.getInstance(document, baos);
            // Render in correct colors for transparent rasters
            writer.setRgbTransparencyBlending(true);

            document.open();
            baos.reset();
            context = new PdfContext(writer);
            context.initSize(page.getBounds());
        }
        //int compressionLevel = writer.getCompressionLevel(); // For testing
        //writer.setCompressionLevel(0); 

        // Actual drawing
        document.addTitle("Geomajas");
        // second pass to layout
        page.layout(context);
        // finally render (uses baos)
        page.render(context);

        document.add(context.getImage());
        // Now close the document
        document.close();

        // convert to non-pdf format
        switch (format) {
        case PDF:
            break;
        case PNG:
        case JPG:

            BufferedImage bufferedImage = null;
            // Use JPedal lib for converting the PDF to PNG or JPG
            /** instance of PdfDecoder to convert PDF into image */
            PdfDecoder decodePdf = new PdfDecoder(true);

            /** set mappings for non-embedded fonts to use */
            PdfDecoder.setFontReplacements(decodePdf);
            decodePdf.useHiResScreenDisplay(true);
            decodePdf.getDPIFactory().setDpi(2 * 72);
            decodePdf.setPageParameters(1, 1);
            try {
                decodePdf.openPdfArray(baos.toByteArray());
                /** get page 1 as an image */
                bufferedImage = decodePdf.getPageAsImage(1);

                /** close the pdf file */
                decodePdf.closePdfFile();

            } catch (PdfException e) {
                throw new PrintException(e, PrintException.DOCUMENT_RENDER_PROBLEM);
            }

            baos.reset();

            // Update the DPI to  DPI_FOR_PNG_OUTPUT of bufferedImage, output written to baos

            final String formatName = format.getExtension();
            boolean convertedDPI = false;

            for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
                ImageWriter writer1 = iw.next();
                ImageWriteParam writeParam = writer1.getDefaultWriteParam();
                ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier
                        .createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
                IIOMetadata metadata = writer1.getDefaultImageMetadata(typeSpecifier, writeParam);
                if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
                    continue;
                }

                setDPI(metadata);
                // Convert bufferedImage to baos
                final ImageOutputStream stream = ImageIO.createImageOutputStream(baos/*output*/);
                try {
                    writer1.setOutput(stream);
                    writer1.write(metadata,
                            new IIOImage(bufferedImage/*input*/, null/* No thumbnails*/, metadata), writeParam);
                    convertedDPI = true;
                } finally {
                    stream.flush();
                    stream.close();
                }
                break;
            }
            if (!convertedDPI) {
                baos.reset();
                //ImageIO.setUseCache(false);
                ImageIO.write(bufferedImage, format.getExtension(), baos);
            }
            break;
        default:
            throw new IllegalStateException(
                    "Oops, software error, need to support extra format at end of render" + format);
        }
        if (outputStream != null) {
            try {
                baos.writeTo(outputStream);
            } catch (IOException e) {
                throw e;
            }
        }
    } else {
        baos.writeTo(outputStream);
    }
}

From source file:org.geomajas.plugin.printing.document.SinglePageDocument.java

License:Open Source License

/**
 * Prepare the document before rendering.
 * //w  ww.j  a  v  a2s .  c  om
 * @param outputStream output stream to render to, null if only for layout
 * @param format format
 * @throws DocumentException oops
 * @throws IOException oops
 * @throws PrintingException oops
 */
private void doRender(OutputStream outputStream, Format format)
        throws IOException, DocumentException, PrintingException {
    // first render or re-render for different layout
    if (outputStream == null || baos == null || null != format) {
        if (baos == null) {
            baos = new ByteArrayOutputStream(); // let it grow as much as needed
        }
        baos.reset();
        boolean resize = false;
        if (page.getBounds().getWidth() == 0 || page.getBounds().getHeight() == 0) {
            resize = true;
        }
        // Create a document in the requested ISO scale.
        Document document = new Document(page.getBounds(), 0, 0, 0, 0);
        PdfWriter writer;
        writer = PdfWriter.getInstance(document, baos);

        // Render in correct colors for transparent rasters
        writer.setRgbTransparencyBlending(true);

        // The mapView is not scaled to the document, we assume the mapView
        // has the right ratio.

        // Write document title and metadata
        document.open();
        PdfContext context = new PdfContext(writer);
        context.initSize(page.getBounds());
        // first pass of all children to calculate size
        page.calculateSize(context);
        if (resize) {
            // we now know the bounds of the document
            // round 'm up and restart with a new document
            int width = (int) Math.ceil(page.getBounds().getWidth());
            int height = (int) Math.ceil(page.getBounds().getHeight());
            page.getConstraint().setWidth(width);
            page.getConstraint().setHeight(height);

            document = new Document(new Rectangle(width, height), 0, 0, 0, 0);
            writer = PdfWriter.getInstance(document, baos);
            // Render in correct colors for transparent rasters
            writer.setRgbTransparencyBlending(true);

            document.open();
            baos.reset();
            context = new PdfContext(writer);
            context.initSize(page.getBounds());
        }
        //int compressionLevel = writer.getCompressionLevel(); // For testing
        //writer.setCompressionLevel(0); 

        // Actual drawing
        document.addTitle("Geomajas");
        // second pass to layout
        page.layout(context);
        // finally render (uses baos)
        page.render(context);

        document.add(context.getImage());
        // Now close the document
        document.close();

        // convert to non-pdf format
        switch (format) {
        case PDF:
            break;
        case PNG:
        case JPG:

            BufferedImage bufferedImage = null;
            // Use JPedal lib for converting the PDF to PNG or JPG
            /** instance of PdfDecoder to convert PDF into image */
            PdfDecoder decodePdf = new PdfDecoder(true);

            /** set mappings for non-embedded fonts to use */
            PdfDecoder.setFontReplacements(decodePdf);
            decodePdf.useHiResScreenDisplay(true);
            decodePdf.getDPIFactory().setDpi(2 * 72);
            decodePdf.setPageParameters(1, 1);
            try {
                decodePdf.openPdfArray(baos.toByteArray());
                /** get page 1 as an image */
                bufferedImage = decodePdf.getPageAsImage(1);

                /** close the pdf file */
                decodePdf.closePdfFile();

            } catch (PdfException e) {
                throw new PrintingException(e, PrintingException.DOCUMENT_RENDER_PROBLEM);
            }

            baos.reset();

            // Update the DPI to  DPI_FOR_PNG_OUTPUT of bufferedImage, output written to baos

            final String formatName = format.getExtension();
            boolean convertedDPI = false;

            for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
                ImageWriter writer1 = iw.next();
                ImageWriteParam writeParam = writer1.getDefaultWriteParam();
                ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier
                        .createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
                IIOMetadata metadata = writer1.getDefaultImageMetadata(typeSpecifier, writeParam);
                if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
                    continue;
                }

                setDPI(metadata);
                // Convert bufferedImage to baos
                final ImageOutputStream stream = ImageIO.createImageOutputStream(baos/*output*/);
                try {
                    writer1.setOutput(stream);
                    writer1.write(metadata,
                            new IIOImage(bufferedImage/*input*/, null/* No thumbnails*/, metadata), writeParam);
                    convertedDPI = true;
                } finally {
                    stream.flush();
                    stream.close();
                }
                break;
            }
            if (!convertedDPI) {
                baos.reset();
                //ImageIO.setUseCache(false);
                ImageIO.write(bufferedImage, format.getExtension(), baos);
            }
            break;
        default:
            throw new IllegalStateException(
                    "Oops, software error, need to support extra format at end of render" + format);
        }
        if (outputStream != null) {
            try {
                baos.writeTo(outputStream);
            } catch (IOException e) {
                throw e;
            }
        }
    } else {
        baos.writeTo(outputStream);
    }
}

From source file:org.goobi.managedbeans.ProcessBean.java

License:Open Source License

public void generateResultAsPdf() {
    FacesContext facesContext = FacesContextHelper.getCurrentFacesContext();
    if (!facesContext.getResponseComplete()) {

        /*/*from   w  w w  .j  a  v a  2  s .c o  m*/
         * -------------------------------- Vorbereiten der Header-Informationen --------------------------------
         */
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        try {
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
            String contentType = servletContext.getMimeType("search.pdf");
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=\"search.pdf\"");
            ServletOutputStream out = response.getOutputStream();
            SearchResultHelper sch = new SearchResultHelper();
            HSSFWorkbook wb = sch.getResult(prepareSearchColumnData(), this.filter, sortList(),
                    this.showClosedProcesses, this.showArchivedProjects);

            List<List<HSSFCell>> rowList = new ArrayList<>();
            HSSFSheet mySheet = wb.getSheetAt(0);
            Iterator<Row> rowIter = mySheet.rowIterator();
            while (rowIter.hasNext()) {
                HSSFRow myRow = (HSSFRow) rowIter.next();
                Iterator<Cell> cellIter = myRow.cellIterator();
                List<HSSFCell> row = new ArrayList<>();
                while (cellIter.hasNext()) {
                    HSSFCell myCell = (HSSFCell) cellIter.next();
                    row.add(myCell);
                }
                rowList.add(row);
            }
            Document document = new Document();
            Rectangle a4quer = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth());
            PdfWriter.getInstance(document, out);
            document.setPageSize(a4quer);
            document.open();
            if (rowList.size() > 0) {
                //                    Paragraph p = new Paragraph(rowList.get(0).get(0).toString());
                //                    document.add(p);
                PdfPTable table = new PdfPTable(rowList.get(0).size());
                table.setSpacingBefore(20);

                for (int i = 0; i < rowList.size(); i++) {

                    List<HSSFCell> row = rowList.get(i);
                    table.completeRow();
                    for (int j = 0; j < row.size(); j++) {
                        HSSFCell myCell = row.get(j);
                        String stringCellValue = myCell.toString();
                        table.addCell(stringCellValue);
                    }

                }
                document.add(table);
            }

            document.close();
            out.flush();
            facesContext.responseComplete();

        } catch (Exception e) {
        }
    }
}

From source file:org.gtdfree.addons.PDFExportAddOn.java

License:Open Source License

public void setPageSize(float width, float height) {
    this.pageSize = new Rectangle(width, height);
}