使用的jar包
com.itextpdf itextpdf 5.5.13 com.itextpdf.tool xmlworker 5.5.13
可以将已生成的html文件或者自己写的html格式的字符串转成pdf。
注意:自己写的html格式的字符串转成pdf时,html语法要正确否则会导致转换失败。
public void html2pdf(String html ,String outpath) throws Exception {
Document document = null; FileOutputStream fos = null; InputStream is = null; PdfWriter writer = null;
try {
document = new Document();
fos = new FileOutputStream(outpath);
writer = PdfWriter.getInstance(document, fos);
document.open();
is = new ByteArrayInputStream(html.toString().getBytes("UTF-8"));//html是拼接的html内容字符串的时候
//is = new FileInputStream(html);//html是html文件地址时
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is, Charset.forName("UTF-8"));
} catch (Exception e) {
//e.printStackTrace();
} finally {
if (document != null) { try { document.close(); } catch(Exception ex) {}}
if (fos != null) { try { fos.close(); } catch(Exception ex) {}}
if (is != null) { try { is.close(); } catch(Exception ex) {}}
if (writer != null) { try { writer.close(); } catch(Exception ex) {}}
}
}
二、html转成图片
使用的jar包
gui.ava html2image 0.9
将自己写的html格式的字符串转成图片。
注意:程序在本地运行时没有问题,如果在weblogic上部署运行时报错java.lang.NoClassDefFoundError:Could not initialize class javax.swing.RepaintManager。
该类是jdk中rt.jar包中的类,该报错可能是weblogic启动时-Djava.awt.headless默认是FALSE,同时还可能会导致验证码也无法正常显示。解决办法是在weblogic的startWebLogic.sh文件中添加JAVA_OPTIONS=-Djava.awt.headless=true。然后重启weblogic
public void html2image(String html ,String outpath) throws Exception {
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml(html);
imageGenerator.getBufferedImage();
imageGenerator.saveAsImage(outpath);
}



