Peyush Goel
Peyush Goel

Reputation: 413

issue with rendering image inside html text in Jeditorpane

I have a string with html contents and i am setting it to JeditorPane. The string contains an image source. I am facing a lot of issues rendering it.

I need to send the image to a printer. Everything looks good but the logo which is always a broken image.

this is the html code

<td style="width:20%; height: auto" colspan="1">
<img src = "images/client-logo1.png" />
</td>

and this is how i am utilizing it after reading the html into a string name html

    protected byte[] createImage(String html, String imageName) {
    final String methodName = "createImage";
    if (LOG.isTraceEnabled()) {
        LOG.trace("enter\n\t{}",  new Object[] {html, imageName});
    }
    StringReader reader = new StringReader("");
    JEditorPane pane = new JEditorPane();
    // pane.setEditable(false);
    pane.setEditorKit(new HTMLEditorKit());
    pane.setContentType("text/html");
    pane.setText(html);
    pane.setSize(IMAGE_WIDTH, IMAGE_HEIGHT);
    pane.setBackground(Color.white);

    // Create a BufferedImage
    BufferedImage image = new BufferedImage(pane.getWidth(), pane
            .getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = image.createGraphics();

    // Have the image painted by SwingUtilities
    JPanel container = new JPanel();
    SwingUtilities.paintComponent(g, pane, container, 0, 0, image
            .getWidth(), image.getHeight());
    g.dispose();
    byte[] imageInByte = null;
    try {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "PNG", baos);
    baos.flush();
    imageInByte = baos.toByteArray();
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new CVProxyApplicationException(
                "Not able to create image due to: "
                        + e1.getLocalizedMessage());
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("exit\n\t{}");
    }
    /*
     * // If printer supports bytes, no need to create an image.
     * ByteArrayOutputStream os = new ByteArrayOutputStream();
     * image.flush(); try { ImageIO.write(image, "png", os); os.flush(); }
     * catch (IOException e1) { e1.printStackTrace(); } return
     * os.toByteArray();
     */
    return imageInByte;
}

any help???

Upvotes: 2

Views: 925

Answers (1)

HQCasanova
HQCasanova

Reputation: 1158

I suspect the problem might be in the SRC attribute. Make sure images/client-logo1.png is the actual path of the image. If it's stored locally, remember to use the prefix file:.

For example, if the image is stored on Windows under the path C:\images\client-logo1.png, the img tag would be:

<img src="file:C:\images\client-logo1.png" />

Upvotes: 1

Related Questions