使用 com.Lowagie.itext 导出html的内容到word
在导出的时候,使用com.Lowagie.itext 将html字符串的内容导出到word上,html里面常常会有图片等内容,改如何处理呢?
处理: 1,引入itext: <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.0.8</version></dependency>
2,代码: public static void main(String[] args) throws Exception { OutputStream out = new FileOutputStream("d://exportFile//img"+System.currentTimeMillis()+".doc"); Document document = new Document(PageSize.A4); RtfWriter2.getInstance(document, out); document.open(); String content = "<p>图片导出</p>n<p> </p>n<p>啦啦</p>n<p> </p>n<p> </p>n<p><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2F20170105%2Fb01b-fxzkfuk2266724.png&refer=http%3A%2F%2Fn.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623917122&t=0eef227b3c5f25073c174523fd5410c7" alt="" width="640" height="640" /></p>n<p> </p>n<p>发放</p>n<p> </p>n<p><img src="F://temp//back2.jpg" alt="" width="300" height="108" /></p>n<p>第三方</p>n<p> </p>"; System.out.println(content); Paragraph context = new Paragraph(); StyleSheet styleSheet = new StyleSheet(); List htmlList = HTMLWorker.parseToList(new StringReader(content), styleSheet); for (Object aHtmlList : htmlList) { Element e = (Element) aHtmlList; context.add(e); } document.add(context); document.close(); System.out.println("ok");}
如果html带有<table></table>的标签的话,会报错,无法直接识别。需要拎出来,再对table里面的内容一一处理。这个比较复杂,后面有时间再整理。
总结:
使用 com.Lowagie.itext 可以较好的导出html的内容到word上,处理上也比较方便,不过带表格就得额外处理了,需要手动拼接。如果是使用其导出html内容到pdf上,可以直接用吗?
关联文章: 《Lowagie 导出html的内容到 pdf》