Java将html转换成pdf、html转换成图片

一、html转成pdf

使用的jar包

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.5.13</version>
</dependency>

可以将已生成的html文件或者自己写的html格式的字符串转成pdf。 注意:自己写的html格式的字符串转成pdf时,html语法要正确否则会导致转换失败。

/**
	 * 将html转成pdf
	 * @param html	html文件路径或者html格式的字符串
	 * @param outpath	要生成的pdf路径
	 * @throws Exception
	 */
	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包

<dependency>
    <groupId>gui.ava</groupId>
    <artifactId>html2image</artifactId>
    <version>0.9</version>
</dependency>

将自己写的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

/**
	 * 将html转成图片
	 * @param html	html格式的字符串
	 * @param outpath	要生成的图片路径
	 * @throws Exception
	 */
	public void html2image(String html ,String outpath) throws Exception {
          
   
		HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        imageGenerator.loadHtml(html);
        imageGenerator.getBufferedImage();
        imageGenerator.saveAsImage(outpath);
	}
经验分享 程序员 微信小程序 职场和发展