iText – HTML to PDF - Image is not displayed in PDF

前端 未结 5 1976
感动是毒
感动是毒 2020-12-31 02:03

I have a html page with text, image and I am parsing the HTML content to iText to generate the PDF. In the generated PDF,Included images are not getting displayed and , only

5条回答
  •  自闭症患者
    2020-12-31 02:44

    Here are some examples: https://developers.itextpdf.com/examples/xml-worker-itext5/html-images

    htmlContext.setImageProvider(new AbstractImageProvider() {
        public String getImageRootPath() { return "src/main/resources/html/"; }
    }); 
    

    If the HTML file you're parsing is stored in a directory that is different from the working directory, iText won't be able to create Image objects. We have to supply an implementation of the ImageProvider interface that tells iText what to do if an img tag is encountered. This interface has the following methods:

    Image retrieve(final String src);
    String getImageRootPath();
    void store(String src, Image img);
    void reset();
    

    You can write your own class implementing these four methods, or you can subclass AbstractImageProvider. It is preferred to do the latter. XML Worker will use the store() method of the AbstractImageProvider class to cache all the Image objects that are encountered in a Map. These objects will be reused when the retrieve() method is called for an image with the same src. If you don't cache images, your PDF will be bloated. The same image bits and bytes will be written to the PDF more than once. The reset() method clears the cache; it is used when an ImageProvider is cloned. Finally, the getImageRootPath() method isn't implemented.

    If the HTML file you're parsing is stored in a directory that is different from the working directory, iText won't be able to create Image objects. We have to supply an implementation of the ImageProvider interface that tells iText what to do if an img tag is encountered. This interface has the following methods:

    You can write your own class implementing these four methods, or you can subclass AbstractImageProvider. It is preferred to do the latter. XML Worker will use the store() method of the AbstractImageProvider class to cache all the Image objects that are encountered in a Map. These objects will be reused when the retrieve() method is called for an image with the same src. If you don't cache images, your PDF will be bloated. The same image bits and bytes will be written to the PDF more than once. The reset() method clears the cache; it is used when an ImageProvider is cloned. Finally, the getImageRootPath() method isn't implemented. You have to implement it yourself, as is done in the following snippet:

提交回复
热议问题