How do I add html images to a pdf using iTextPDF 5.5.13 in Java?

573 Views Asked by At

I am getting HTML strings from another method and some of the strings contain links to images. Those images do not appear in the PDF but no errors are being thrown.

The images that I am using are coming in as base64 encoded images. I thought that maybe that was the issue but after trying with local images and images from links, it still does not work. Is it something to do with how the images are being parsed? Am I able to print these images using iText's XMLWorkerHelper?

public static void main(String[] args) throws Exception {

        String str1 = "<p>Red Dot</p><img src=\"data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==\" alt=\"Red dot\" />";
        String str2 = "<p>W3 Logo</p><img src=\"https://www.w3schools.com/images/w3schools_green.jpg\" alt=\"W3Schools.com\" style=\"width:104px;height:142px;\">";
        String str3 = "<p>Cow</p><img src=\"cow.jpg\" alt=\"Cow\">";

        System.out.println("Open File");
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("test.pdf"));
        document.open();

        System.out.println("Write To File");
        InputStream is = new ByteArrayInputStream(str3.getBytes());
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);

        System.out.println("Close File");
        document.close();
    }

The pdf was always generated with the text preceding the image, but the image never printed. The real instances are much more complex than this, so I would need a solution that preserves the original format of the html string. Any help is greatly appreciated!

0

There are 0 best solutions below