maven依赖
com.itextpdf
itextpdf
5.5.10
com.itextpdf
itext-asian
5.2.0
com.itextpdf.tool
xmlworker
5.5.8
org.xhtmlrenderer
flying-saucer-pdf-itext5
9.1.6
org.freemarker
freemarker
2.3.28
1.通过freemaker模板生成html
//获取模板并填充数据
public static String getContent(String fileName, Object data) throws Exception {
// 创建一个Configuration对象
Configuration configuration = new Configuration(Configuration.getVersion());
// 告诉config对象模板文件存放的路径。
// configuration.setDirectoryForTemplateLoading(new File(Test3.class.getClassLoader().getResource("/").getPath()));
configuration.setClassForTemplateLoading(Test3.class, "/");
// 设置config的默认字符集。一般是utf-8
configuration.setDefaultEncoding("utf-8");
//从config对象中获得模板对象。需要制定一个模板文件的名字。
Template template = configuration.getTemplate(fileName + ".ftl");
StringWriter writer = new StringWriter();
//模版和数据匹配
template.process(data, writer);
writer.flush();
String html = writer.toString();
return getImgs(html);
}
//替换html中的图片路径
private static String getImgs(String content) {
String img = "";
Pattern p_image;
Matcher m_image;
String str = "";
String[] images = null;
String regEx_img = "(]*?>)";
p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
m_image = p_image.matcher(content);
if (m_image != null) {
while (m_image.find()) {
img = m_image.group();
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)")
.matcher(img);
if (m != null) {
while (m.find()) {
String tempSelected = m.group(1);
str = tempSelected;
String classpath = getRootPath();
String ulr = classpath.substring(5, classpath.length());
content = content.replace(str, ulr + "templates/" + str);
}
}
}
}
return content;
}
2.生成pdf
public static void exportToResponse(String templateName, Object data) throws Exception {
String html = getContent(templateName, data);
FileOutputStream out = new FileOutputStream("d:/test3.pdf");
try {
//设置文档大小
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, out);
writer.setStrictImageSequence(true);
//输出为PDF文件
convertToPDF(writer, document, html);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
out.close();
}
}
private static void convertToPDF(PdfWriter writer, Document document, String htmlString) throws Exception {
out.println(htmlString);
document.open();
MyFontsProvider fontProvider = new MyFontsProvider();
fontProvider.addFontSubstitute("lowagie", "garamond");
fontProvider.setUseUnicode(true);
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
// if (TEMPLATENAMES.equals("合同") || TEMPLATENAMES.equals("合同模版"))
// writer.setPageEvent(new BackGroundImage());
// if (TEMPLATENAMES.equals("设计合同"))
// writer.setPageEvent(new SheJiGroundImage()); //这里初始化分页监听类
//指定文件预设开档时的缩放为100%
try {
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new ByteArrayInputStream(htmlString.getBytes("UTF-8")),
// XMLWorkerHelper.class.getResourceAsStream("/default.css"),
Charset.forName("UTF-8"), fontProvider);
} catch (IOException e) {
e.printStackTrace();
} finally {
document.close();
}
}
3.解决中文乱码
/**
* 设置字符集
*/
public static class MyFontsProvider extends XMLWorkerFontProvider {
public MyFontsProvider() {
super(null, null);
}
@Override
public Font getFont(final String fontname, String encoding, float size, final int style) {
String fntnames = fontname;
Font FontChinese = null;
if (fntnames == null) {
fntnames = "宋体";
}
if (size == 0) {
size = 4;
}
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
FontChinese = new Font(bfChinese, size, style);
} catch (Exception e) {
e.printStackTrace();
}
if (FontChinese == null) {
FontChinese = super.getFont(fntnames, encoding, size, style);
}
return FontChinese;
}
}