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);
	}
  • 0
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值