1. 添加dependency在pom.xml文件中
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.6</version>
</dependency>
<dependency>
<groupId>net.sf.jtidy</groupId>
<artifactId>jtidy</artifactId>
<version>r938</version>
</dependency>
2. 创建Util 目录并添加下面的工具类
2.1 FreeMarkToHtml.java
public class FreeMarkToHtml {
public static Template getTemplate(String templateFilePath, String templateFileName) {
try {
Configuration cfg = new Configuration();
cfg.setClassicCompatible(true);
TemplateLoader templateLoader = new FileTemplateLoader(new File(
templateFilePath));
cfg.setTemplateLoader(templateLoader);
return cfg.getTemplate(templateFileName);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String freemarkToHtml(String templateFilePath, String templateFileName, Map<String, Object> replaceData,
String outFile) {
String path = null;
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile), "UTF-8"));
Template temp = getTemplate(templateFilePath, templateFileName);
temp.setEncoding("UTF-8");
temp.process(replaceData, out);
path = outFile;
} catch (IOException e) {
e.printStackTrace();
path = null;
} catch (TemplateException e) {
e.printStackTrace();
path = null;
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return path;
}
}
2.2 Html2Xhtml.java
public class Html2Xhtml {
public static String html2Xhtml(String html, String xhtml) {
String path = null;
try {
FileInputStream fin = new FileInputStream(html);
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
int data = -1;
while ((data = fin.read()) != -1) {
byteArrayOut.write(data);
}
fin.close();
byte[] htmlFileData = byteArrayOut.toByteArray();
byteArrayOut.close();
ByteArrayInputStream tidyInput = new ByteArrayInputStream(
htmlFileData);
ByteArrayOutputStream tidyOut = new ByteArrayOutputStream();
Tidy tidy = new Tidy();
tidy.setInputEncoding("UTF-8");
tidy.setOutputEncoding("UTF-8");
tidy.setShowWarnings(false);
tidy.setIndentContent(true);
tidy.setSmartIndent(true);
tidy.setIndentAttributes(false);
tidy.setMakeClean(true);
tidy.setQuiet(true);
tidy.setWord2000(true);
tidy.setXHTML(true);
tidy.setErrout(new PrintWriter(System.out));
tidy.parse(tidyInput, tidyOut);
tidyInput.close();
tidyOut.writeTo(new FileOutputStream(xhtml));
tidyOut.flush();
tidyOut.close();
path = xhtml;
} catch (FileNotFoundException e) {
e.printStackTrace();
path = null;
} catch (IOException e) {
e.printStackTrace();
path = null;
}
return path;
}
}
2.3 MyFontsProvider.java (这里可以解决中文乱码的问题)
public class MyFontsProvider extends XMLWorkerFontProvider {
public MyFontsProvider(){
super(null,null);
}
@Override
public Font getFont(final String fontname, String encoding, float size, final int style) {
String fntname = fontname;
if(fntname==null){
fntname="宋体";
}
return super.getFont(fntname, encoding, size, style);
}
}
2.4
public class XHtml2Pdf {
/**
* 转化方法
*
* @param html html文件输入路径(带文件名称)
* @param pdf pdf文件输出路径(带文件名称)
*/
public static void XHtml2Pdf(String html, String pdf)
throws FileNotFoundException, IOException, DocumentException,
CssResolverException {
int i = html.lastIndexOf(".html");
String xhtml = null;
xhtml = html.substring(0, i) + ".xhtml";
xhtml = Html2Xhtml.html2Xhtml(html, xhtml);
if (xhtml != null) {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(pdf));
document.open();
MyFontsProvider fontProvider = new MyFontsProvider();
fontProvider.addFontSubstitute("lowagie", "garamond");
fontProvider.setUseUnicode(true);
// 使用我们的字体提供器,并将其设置为unicode字体样式
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(
cssAppliers);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
CSSResolver cssResolver = XMLWorkerHelper.getInstance()
.getDefaultCssResolver(true);
Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
new HtmlPipeline(htmlContext, new PdfWriterPipeline(
document, writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser p = new XMLParser(worker);
File input = new File(xhtml);
p.parse(new InputStreamReader(new FileInputStream(input), "UTF-8"));
document.close();
}
}
}
3. 调用入口:
URL url = ResourceUtils.getURL("classpath:templates");
Map replaceData = initData();
FreeMarkToHtml.freemarkToHtml(url.getPath(), "test.ftl", replaceData, url.getPath() + "report.html");
try {
XHtml2Pdf.XHtml2Pdf(url.getPath() + "report.html", url.getPath() + "report.pdf");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (CssResolverException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
记住ftl文件在 resouce 目录下面的templates目录下面。如何过需要交换数据,自己重写initData方法既可以,返回一个 “
HashMap<String, Object> needReplaceMapData = new HashMap<String, Object>();
”