0

I am trying to convert html to pdf, while doing so I am not able to see the images in the pdf. When I use a simple html file , then the image is shown in the pdf but in case of having html as string, the image is not coming. I am using following code:

public static final String DEST = "C://temp/rounded_corners.pdf";
public static final String HTML = "<html><head><title>Summary log</title></head><body><h1 style='margin-top:-5px'>Trading & Liqidity</h1><p style='margin-bottom:-3px'><img src='areaOfFocus.PNG' height=35 width=235 alt='Area of Focus'/></p></body>";
public static void main(String[] args) throws IOException, DocumentException {
    File file = new File(DEST);
    file.getParentFile().mkdirs();
    new SamplePDFGEneration().createPdf(DEST);
}

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document(PageSize.A4.rotate());
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
    htmlContext.setImageProvider(new AbstractImageProvider() {
        public String getImageRootPath() { return "/samplePDF/src/samplePDF/"; }
    });
   XMLWorkerHelper.getInstance().parseXHtml(writer, document,
          new StringReader(HTML));     
   document.close();
}

When instead of above I use

public static final String HTML = "C://temp/sample_final7.html";

and have the tag "img src="C://Temp/areaofFocus.png" height=35 width=158 alt="Programs"/> in my html, then the image is displayed.

Amedee Van Gasse
  • 7,280
  • 5
  • 55
  • 101
Suvriti Gandhi
  • 185
  • 1
  • 2
  • 10
  • The old iText 5 XML Worker isn't really smart when searching for images. iText 7 + the pdfHTML addon are much easier to use. Consider upgrading. If you can't upgrade, you'll have to write an `ImageProvider` implementation. – Bruno Lowagie Nov 15 '17 at 14:45
  • Can you please guide me to an example where ImageProvider has been implemented. It would of great help. – Suvriti Gandhi Dec 04 '17 at 08:20
  • There are some examples in the answer to the question [Handling embedded images in IText XMLWorker](https://stackoverflow.com/questions/14864369/handling-embedded-images-in-itext-xmlworker), [How can I use iText to convert HTML with images and hyperlinks to PDF?](https://stackoverflow.com/a/35594043/1622493), and [iText – HTML to PDF - Image is not displayed in PDF](https://stackoverflow.com/a/36479239/1622493). However **DO NOT COPY / PASTE CODE YOU DON'T UNDERSTAND!!!** Show us what you did, and **why** you did it that way, so that we can see that you did an effort. – Bruno Lowagie Dec 04 '17 at 14:37

0 Answers0