rendering images XmlWorkerHelper(itextpdf)

天大地大妈咪最大 提交于 2021-02-08 07:53:02

问题


please help me.

I have problem with rendering image in pdf im usung itextpdf 5.5.6 and itext 5.5.6

my code is:

    .
    .
    .


    URL url = new URL("http://some.html");

    URLConnection uc = url.openConnection();
    InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
     XMLWorkerHelper worker = XMLWorkerHelper.getInstance();

     worker.parseXHtml(pdrwriter, doc, inputStreamReader);

     doc.close();
        //close the writer
     pdrwriter.close();

my html has:

<table><tr><td><img src="http://mysite/logo.jpg" /></td</tr></table>

and i get error: Invalid nested tag td found, expected closing tag img.

I have tried

<table><tr><td><img src="http://mysite/logo.jpg"></img</td</tr></table> 

the sam error..

do You know how to handel it? Thx for help!!!


回答1:


This is wrong:

<table><tr><td><img src="http://mysite/logo.jpg" /></td</tr></table>

It should be:

<table><tr><td><img src="http://mysite/logo.jpg" /></td></tr></table>

This is also wrong:

<table><tr><td><img src="http://mysite/logo.jpg"></img</td</tr></table>

It should be:

<table><tr><td><img src="http://mysite/logo.jpg"></img></td></tr></table> 



回答2:


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 method.

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. You have to implement it yourself, as is done in the following snippet

htmlContext.setImageProvider(new AbstractImageProvider() {

public String getImageRootPath() {

    return "src/main/resources/html/";

}
});


来源:https://stackoverflow.com/questions/30545588/rendering-images-xmlworkerhelperitextpdf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!