Example usage for com.lowagie.text Image getInstance

List of usage examples for com.lowagie.text Image getInstance

Introduction

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

Prototype

public static Image getInstance(Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:org.freeeed.print.Html2Pdf.java

License:Apache License

/**
 * Bad rendering, perhaps used only for Windows
 *//*from w w w .ja  va 2  s . co m*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private static void convertHtml2Pdf(Reader htmlReader, File outputFile) throws Exception {
    Document pdfDocument = new Document();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(pdfDocument, baos);
    pdfDocument.open();
    StyleSheet styles = new StyleSheet();
    styles.loadTagStyle("body", "font", "Times New Roman");

    ImageProvider imageProvider = new ImageProvider() {
        @Override
        public Image getImage(String src, HashMap arg1, ChainedProperties arg2, DocListener arg3) {

            try {
                return Image.getInstance(IOUtils.toByteArray(
                        getClass().getClassLoader().getResourceAsStream(ParameterProcessing.NO_IMAGE_FILE)));
            } catch (IOException | BadElementException e) {
                logger.warn("Problem with html to pdf rendering.", e);
            }

            return null;
        }
    };

    HashMap interfaceProps = new HashMap();
    interfaceProps.put("img_provider", imageProvider);

    ArrayList arrayElementList = HTMLWorker.parseToList(htmlReader, styles, interfaceProps);
    for (int i = 0; i < arrayElementList.size(); ++i) {
        Element e = (Element) arrayElementList.get(i);
        pdfDocument.add(e);
    }
    pdfDocument.close();
    byte[] bs = baos.toByteArray();
    FileOutputStream out = new FileOutputStream(outputFile);
    out.write(bs);
    out.close();
}

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

License:Open Source License

@Override
public void render(PdfContext context) {
    final float w = getSize().getWidth();
    final float h = getSize().getHeight();
    Rectangle iconRect = new Rectangle(0, 0, w, h);
    RenderedImage img;//from w  ww .j  a va  2 s  . c  o  m
    try {
        img = legendGraphicService.getLegendGraphic(new RuleMetadata(h, w));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "PNG", baos);
        context.drawImage(Image.getInstance(baos.toByteArray()), iconRect, null);
    } catch (Exception e) { // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

License:Open Source License

private void drawPoint(PdfContext context, Rectangle iconRect, Color fillColor, Color strokeColor) {
    float baseWidth = iconRect.getWidth() / 10;
    SymbolInfo symbol = styleInfo.getSymbol();
    if (symbol.getImage() != null) {
        try {/*w  w w .ja v  a  2s . co m*/
            Image pointImage = Image.getInstance(symbol.getImage().getHref());
            context.drawImage(pointImage, iconRect, iconRect);
        } catch (Exception ex) { // NOSONAR
            log.error("Not able to create image for POINT Symbol", ex);
        }
    } else if (symbol.getRect() != null) {
        context.fillRectangle(iconRect, fillColor);
        context.strokeRectangle(iconRect, strokeColor, baseWidth / 2);
    } else {
        context.fillEllipse(iconRect, fillColor);
        context.strokeEllipse(iconRect, strokeColor, baseWidth / 2);
    }
}

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  a 2  s. c  o m*/

    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.RasterLayerComponentImpl.java

License:Open Source License

/**
 * Add image in the document./*from  w w w.  ja v  a2  s . c  o m*/
 * 
 * @param context
 *            PDF context
 * @param imageResult
 *            image
 * @throws BadElementException
 *             PDF construction problem
 * @throws IOException
 *             PDF construction problem
 */
protected void addImage(PdfContext context, ImageResult imageResult) throws BadElementException, IOException {
    Bbox imageBounds = imageResult.getRasterImage().getBounds();
    float scaleFactor = (float) (72 / getMap().getRasterResolution());
    float width = (float) imageBounds.getWidth() * scaleFactor;
    float height = (float) imageBounds.getHeight() * scaleFactor;
    // subtract screen position of lower-left corner
    float x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;
    // shift y to lowerleft corner, flip y to user space and subtract
    // screen position of lower-left
    // corner
    float y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY())
            * scaleFactor;
    if (log.isDebugEnabled()) {
        log.debug("adding image, width=" + width + ",height=" + height + ",x=" + x + ",y=" + y);
    }
    // opacity
    log.debug("before drawImage");
    context.drawImage(Image.getInstance(imageResult.getImage()), new Rectangle(x, y, x + width, y + height),
            getSize(), getOpacity());
    log.debug("after drawImage");
}

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

License:Open Source License

public Image getImage(String path) {
    try {/*from w w w. j  a v  a2 s  .  co  m*/
        URL url = getClass().getResource(path);
        if (url == null) {
            url = Utilities.toURL(path);
        }
        return Image.getInstance(url);
    } catch (Exception e) { // NOSONAR
        log.warn("could not fetch image", e);
        return null;
    }
}

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

License:Open Source License

private void drawPoint(Coordinate coord, SymbolInfo symbol) {
    if (symbol.getImage() != null) {
        try {/*from   ww  w  .  ja  va 2  s.c  o m*/
            Image pointImage = Image.getInstance(symbol.getImage().getHref());
            //template.addImage(image, width, 0, 0, height, x, y)
            template.addImage(pointImage, symbol.getImage().getWidth(), 0, 0, symbol.getImage().getHeight(),
                    origX + (float) coord.x, origY + (float) coord.y);
        } catch (Exception ex) { // NOSONAR
            log.error("Not able to create POINT image for rendering", ex);
        }
    } else if (symbol.getCircle() != null) {
        float radius = symbol.getCircle().getR();

        template.circle(origX + (float) coord.x, origY + (float) coord.y, radius);

    } else if (symbol.getRect() != null) {
        float width = symbol.getRect().getW();
        float height = symbol.getRect().getW();

        template.rectangle(origX + (float) coord.x - (width / 2), origY + (float) coord.y - (height / 2), width,
                height);

    }

}

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

License:Open Source License

/**
 * Return this context as an image.//from www  .  j  av a 2s  . c o m
 *
 * @return this context as image
 * @throws BadElementException oops
 */
public Image getImage() throws BadElementException {
    return Image.getInstance(template);
}

From source file:org.goodoldai.jeff.report.pdf.PDFImageChunkBuilder.java

License:Open Source License

/**
 * This method transforms an image explanation chunk into a PDF report
 * piece and writes this piece into the provided output stream which is, in 
 * this case, an instance of com.lowagie.text.Document. The method first
 * collects all general chunk data (context, rule, group, tags) and inserts 
 * them into the report, and then retrieves the chunk content. Since the 
 * content is, in this case, an ImageData instance, the image it relates to 
 * (caption and URL) gets inserted into the report. If the image caption is 
 * missing, it doesn't get inserted into the report.
 *
 * @param echunk image explanation chunk that needs to be transformed
 * @param stream output stream to which the transformed chunk will be
 * written as output (in this case com.lowagie.text.Document)
 * @param insertHeaders denotes if chunk headers should be inserted into the
 * report (true) or not (false)//from  w  w  w. j  a  v  a 2  s  . co m
 *
 * @throws org.goodoldai.jeff.explanation.ExplanationException if any of the arguments are
 * null, if the entered chunk is not an ImageExplanationChunk instance or 
 * if the entered output stream type is not com.lowagie.text.Document
 */
public void buildReportChunk(ExplanationChunk echunk, Object stream, boolean insertHeaders) {
    if (echunk == null) {
        throw new ExplanationException("The entered chunk must not be null");
    }

    if (stream == null) {
        throw new ExplanationException("The entered stream must not be null");
    }

    if (!(echunk instanceof ImageExplanationChunk)) {
        throw new ExplanationException("The entered chunk must be an ImageExplanationChunk instance");
    }

    if (!(stream instanceof com.lowagie.text.Document)) {
        throw new ExplanationException("The entered stream must be a com.lowagie.text.Document instance");
    }

    com.lowagie.text.Document doc = ((com.lowagie.text.Document) stream);

    //Insert general chunk data
    if (insertHeaders)
        PDFChunkUtility.insertChunkHeader(echunk, doc);

    try {
        //Insert content - in this case an image
        ImageData imdata = (ImageData) (echunk.getContent());

        //Get image data
        Image img = Image.getInstance(getClass().getResource(imdata.getURL()));

        //Scale the image in order to fit the page
        img.scaleToFit(doc.getPageSize().getRight(doc.leftMargin() + doc.rightMargin()),
                doc.getPageSize().getTop(doc.topMargin() + doc.bottomMargin()));

        //Add image
        doc.add(img);

        //If a caption is present, insert it below the image
        if ((imdata.getCaption() != null) && (!imdata.getCaption().equals(""))) {
            doc.add(new Paragraph("IMAGE: " + imdata.getCaption()));
        }
    } catch (NullPointerException e) {
        throw new ExplanationException(
                "The image '" + ((ImageData) (echunk.getContent())).getURL() + "' could not be found");
    } catch (Exception e) {
        throw new ExplanationException(e.getMessage());
    }

}

From source file:org.goodoldai.jeff.report.pdf.RTFImageChunkBuilder.java

License:Open Source License

/**
 * This method transforms an image explanation chunk into a PDF report
 * piece and writes this piece into the provided output stream which is, in 
 * this case, an instance of com.lowagie.text.Document. The method first
 * collects all general chunk data (context, rule, group, tags) and inserts 
 * them into the report, and then retrieves the chunk content. Since the 
 * content is, in this case, an ImageData instance, the image it relates to 
 * (caption and URL) gets inserted into the report. If the image caption is 
 * missing, it doesn't get inserted into the report.
 *
 * @param echunk image explanation chunk that needs to be transformed
 * @param stream output stream to which the transformed chunk will be
 * written as output (in this case com.lowagie.text.Document)
 * @param insertHeaders denotes if chunk headers should be inserted into the
 * report (true) or not (false)/*  w w w  .ja  v a  2  s .  c  o  m*/
 *
 * @throws org.goodoldai.jeff.explanation.ExplanationException if any of the arguments are
 * null, if the entered chunk is not an ImageExplanationChunk instance or 
 * if the entered output stream type is not com.lowagie.text.Document
 */
public void buildReportChunk(ExplanationChunk echunk, Object stream, boolean insertHeaders) {
    if (echunk == null) {
        throw new ExplanationException("The entered chunk must not be null");
    }

    if (stream == null) {
        throw new ExplanationException("The entered stream must not be null");
    }

    if (!(echunk instanceof ImageExplanationChunk)) {
        throw new ExplanationException("The entered chunk must be an ImageExplanationChunk instance");
    }

    if (!(stream instanceof com.lowagie.text.Document)) {
        throw new ExplanationException("The entered stream must be a com.lowagie.text.Document instance");
    }

    com.lowagie.text.Document doc = ((com.lowagie.text.Document) stream);

    //Insert general chunk data
    if (insertHeaders)
        RTFChunkUtility.insertChunkHeader(echunk, doc);

    try {
        //Insert content - in this case an image
        ImageData imdata = (ImageData) (echunk.getContent());

        //Get image data
        Image img = Image.getInstance(getClass().getResource(imdata.getURL()));

        //Scale the image in order to fit the page
        img.scaleToFit(doc.getPageSize().getRight(doc.leftMargin() + doc.rightMargin()),
                doc.getPageSize().getTop(doc.topMargin() + doc.bottomMargin()));

        //Add image
        doc.add(img);

        //If a caption is present, insert it below the image
        if ((imdata.getCaption() != null) && (!imdata.getCaption().equals(""))) {
            doc.add(new Paragraph("IMAGE: " + imdata.getCaption()));
        }
    } catch (NullPointerException e) {
        throw new ExplanationException(
                "The image '" + ((ImageData) (echunk.getContent())).getURL() + "' could not be found");
    } catch (Exception e) {
        throw new ExplanationException(e.getMessage());
    }

}