html生成pdf java_java 中实现HTML 生成pdf

本文介绍了如何在Java中使用flying-saucer库将HTML转换为PDF,通过Freemarker模板和数据整合生成HTML,然后利用ITextRenderer创建PDF。文章详细展示了从引入依赖、配置Freemarker到生成PDF的完整代码流程。
摘要由CSDN通过智能技术生成

JAVA 中生成pdf 的方法很多,iText是一个生成PDF文档的开源Java库。但是用iText生成pdf,有时候很难控制页面的样式。听说flying-saucer 可以对样式进行简单的支持。由于项目需要,用flying-saucer 体验 了一把,感觉还不错。生成pdf 的整体思路:1.利用freemaker 将模版和数据整合成html 2.利用flying-saucer将生成的html 转换pdf .不废话上代码

1.项目需要引入的包

e3277687a7bfa881b4e595aabe707348.png

2.书写利用freemarker 生成html 的html 生成器

package com.jscredit.zxypt.freemaker;

import java.io.BufferedWriter;

import java.io.File;

import java.io.IOException;

import java.io.StringWriter;

import java.util.Map;

import com.jscredit.zxypt.utils.ResourceLoader;

import freemarker.template.Configuration;

import freemarker.template.Template;

import freemarker.template.TemplateException;

//html 的生成器

public class HtmlGenerator {

public static void main(String[] args) throws Exception {

// classpath 中模板路径

String temp = "temple/overseaAssistance.html";

// classpath 路径

String outputFileClass = ResourceLoader.getPath("");

System.out.println(outputFileClass);

String ss = new File(outputFileClass).getParentFile().getParent();

System.out.println(ss);

/* String htmlStr = HtmlGenerator.generate(template, variables);

System.out.println(htmlStr);*/

// 生成pdf路径

//outputFile = outputFile == null ? new File(outputFileClass).getParentFile().getParent()+ "/tmp/"+ System.currentTimeMillis() + ".pdf" : outputFile;

// 生成pdf路径

/* OutputStream out = new FileOutputStream(outputFile);

PdfDocumentGenerator.pdfgenerate(htmlStr, out);*/

}

/**

*

* 根据上面的main 方法抽出的通用方法

* 传入模版路径 和数据生成html 返回html 的内容

* template 模版的路径 variables数据

*/

public static String generate(String template, Map variables) throws IOException, TemplateException{

Configuration config = FreemarkerConfiguration.getConfiguation();

//Template tp = configuration.getTemplate("overseaAssistance.html");

Template tp = config.getTemplate(template);

StringWriter stringWriter = new StringWriter();

BufferedWriter writer = new BufferedWriter(stringWriter);

tp.setEncoding("UTF-8");

tp.process(variables, writer);

String htmlStr = stringWriter.toString();

writer.flush();

writer.close();

return htmlStr;

}

}

3.书写生成pdf 的生成器

package com.jscredit.zxypt.freemaker;

import java.io.ByteArrayInputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.util.Map;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;

import org.w3c.dom.Document;

import org.xhtmlrenderer.pdf.ITextRenderer;

import com.jscredit.zxypt.utils.ResourceLoader;

import com.lowagie.text.pdf.BaseFont;

import freemarker.template.TemplateException;

//pdf的生成器

public class PdfDocumentGenerator {

private final static Logger logger = Logger.getLogger(PdfDocumentGenerator.class);

private final static HtmlGenerator htmlGenerator;

static {

htmlGenerator = new HtmlGenerator();

}

/*

*

* 根据html的内容生成pdf

*

*/

public static void pdfgenerate(String htmlContent, String outputFile)throws Exception{

OutputStream out = null;

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

Document doc = builder.parse(new ByteArrayInputStream(htmlContent.getBytes("UTF-8")));

ITextRenderer iTextRenderer = new ITextRenderer();

// classpath 路径

String outputFileClass = ResourceLoader.getPath("");

//添加字体,以支持中文

iTextRenderer.getFontResolver().addFont(outputFileClass+"fronts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

iTextRenderer.getFontResolver().addFont(outputFileClass+"fronts/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

File f = new File(outputFile);

if (f != null && !f.getParentFile().exists()) {

f.getParentFile().mkdir();

}

out = new FileOutputStream(outputFile);

iTextRenderer.setDocument(doc, null);

iTextRenderer.layout();

iTextRenderer.createPDF(out);

out.close();

}

/*

*

* 对上面的方法再进行封装

*

*/

public boolean generate(String template, Map variables,String outputFile) throws IOException, TemplateException{

String htmlContent = this.htmlGenerator.generate(template,variables);

System.out.println("+++++++++"+htmlContent);//打印出html 的内容方便查看是否是html 的时候已经出现乱码

try {

this.pdfgenerate(htmlContent, outputFile);

} catch (Exception e) {

e.printStackTrace();

}

return true;

}

}

4.书写freemarker的基本配置

package com.jscredit.zxypt.freemaker;

import java.io.File;

import java.io.IOException;

import com.jscredit.zxypt.utils.ResourceLoader;

import freemarker.template.Configuration;

/*

* freemaker 的配置

*/

public class FreemarkerConfiguration {

private static Configuration config = null;

/**

* 获取 FreemarkerConfiguration

*

* @Title: getConfiguation

* @Description:

* @return

*/

public static synchronized Configuration getConfiguation() {

if (config == null) {

setConfiguation();

}

return config;

}

/**

* 设置 配置

* @Title: setConfiguation

* @Description:

*/

private static void setConfiguation() {

config = new Configuration();

String path = ResourceLoader.getPath("");

System.out.println(">>>>>>>>>>>>>>>>>>>"+path);

try {

config.setDirectoryForTemplateLoading(new File(path));

} catch (IOException e) {

e.printStackTrace();

}

}

}

5.书写获取资源的resources工具类

package com.jscredit.zxypt.utils;

import java.net.URL;

//获取项目资源的工具类

public class ResourceLoader {

public static String CLASS_PATH_PREFIX ="classpath:";

/**

* classpath中获取资源

* @Title: getResource

* @Description: classpath中获取资源

* @param resource

* @return

*/

public static URL getResource(String resource) {

ClassLoader classLoader = null;

classLoader = Thread.currentThread().getContextClassLoader();

return classLoader.getResource(resource);

}

/**

* classpath 中搜索路径

* @Title: getPath

* @Description:

* @param resource

* @return

*/

public static String getPath(String resource){

if(resource!=null){

if(resource.startsWith(CLASS_PATH_PREFIX)){

resource = getPath("")+resource.replaceAll(CLASS_PATH_PREFIX, "");

}

}

URL url = getResource(resource);

if(url==null)

return null;

return url.getPath().replaceAll("%20", " ");

}

/**

*

* @Title: getPath

* @Description:

* @param resource

* @param clazz

* @return

*/

public static String getPath(String resource,Class clazz){

URL url = getResource(resource, clazz);

if(url==null)

return null;

return url.getPath().replaceAll("%20", " ");

}

/**

* 指定class中获取资源

* @Title: getResource

* @Description: 指定class中获取资源

* @param resource

* @param clazz

* @return

*/

public static URL getResource(String resource,Class clazz){

return clazz.getResource(resource);

}

}

这样就可以轻松实现Java 的html转pdf 了。附上生成 的效果图:

10b8b44f1e241a13978d03cb7e7001c6.png

另外需要jar 的可以再我博客里面去下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值