org.freemarker
freemarker
2.3.31
2.html转pdf依赖
com.itextpdf
itextpdf
5.5.13
com.itextpdf.tool
xmlworker
5.5.13
com.itextpdf
html2pdf
3.0.4
com.itextpdf
kernel
7.1.15
org.xhtmlrenderer
flying-saucer-pdf
9.1.20
二、代码实现
1.Spring提供的工具类用来完成pdf的一些操作
public class FreeMarkerUtil {
private static final Logger logger = LoggerFactory.getLogger(FreeMarkerUtil.class);
private static final String WINDOWS_SPLIT = "\";
private static final String UTF_8 = "UTF-8";
private static Map fileTemplateLoaderCache = Maps.newConcurrentMap();
private static Map configurationCache = Maps.newConcurrentMap();
public static Configuration getConfiguration(String templateFilePath) {
if (null != configurationCache.get(templateFilePath)) {
return configurationCache.get(templateFilePath);
}
Configuration config = new Configuration(Configuration.VERSION_2_3_25);
config.setDefaultEncoding(UTF_8);
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
config.setLogTemplateExceptions(false);
FileTemplateLoader fileTemplateLoader = null;
if (null != fileTemplateLoaderCache.get(templateFilePath)) {
fileTemplateLoader = fileTemplateLoaderCache.get(templateFilePath);
}
try {
fileTemplateLoader = new FileTemplateLoader(new File(templateFilePath));
fileTemplateLoaderCache.put(templateFilePath, fileTemplateLoader);
} catch (IOException e) {
logger.error("fileTemplateLoader init error! : [{}]", e.getMessage(), e);
}
config.setTemplateLoader(fileTemplateLoader);
configurationCache.put(templateFilePath, config);
return config;
}
2.获取模板先准备一个html的静态页面模板ftl文件,进行获取模板文件
public static String getContent(String fileName, Object data) {
StringWriter writer = null;
try {
// 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
// 指定FreeMarker模板文件的位置
cfg.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates");
Template template = cfg.getTemplate(fileName);
writer = new StringWriter();
template.process(data, writer);
} catch (Exception e) {
e.printStackTrace();
}
if (writer != null) {
writer.flush();
return writer.toString();
}
return "";
}
public static String getContent1(String fileName1, Object data1) {
StringWriter writer = null;
try {
// 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
// 指定FreeMarker模板文件的位置
cfg.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates");
Template template = cfg.getTemplate(fileName1);
writer = new StringWriter();
template.process(data1, writer);
} catch (Exception e) {
e.printStackTrace();
}
if (writer != null) {
writer.flush();
return writer.toString();
}
return "";
}
private static String getTemplatePath(String templatePath) {
if (StringUtils.isEmpty(templatePath)) {
return "";
}
if (templatePath.contains(WINDOWS_SPLIT)) {
return templatePath.substring(0, templatePath.lastIndexOf(WINDOWS_SPLIT));
}
return templatePath.substring(0, templatePath.lastIndexOf("/"));
}
private static String getTemplateName(String templatePath) {
if (StringUtils.isEmpty(templatePath)) {
return "";
}
if (templatePath.contains(WINDOWS_SPLIT)) {
return templatePath.substring(templatePath.lastIndexOf(WINDOWS_SPLIT) + 1);
}
return templatePath.substring(templatePath.lastIndexOf("/") + 1);
}
3.按照名字和路径匹配对应的模板
public static String getPDFTemplatePath(String fileName) {
String classpath = FreeMarkerUtil.class.getClassLoader().getResource("").getPath();
String templatePath = classpath + "/templates";
File file = new File(templatePath);
if (!file.isDirectory()) {
logger.error("PDF模板文件不存在,请检查templates文件夹!");
}
String pdfFileName = fileName.substring(0, fileName.lastIndexOf("."));
File defaultTemplate = null;
File matchTemplate = null;
for (File f : file.listFiles()) {
if (!f.isFile()) {
continue;
}
String templateName = f.getName();
if (templateName.lastIndexOf(".ftl") == -1) {
continue;
}
if (defaultTemplate == null) {
defaultTemplate = f;
}
if (StringUtils.isEmpty(fileName) && defaultTemplate != null) {
break;
}
templateName = templateName.substring(0, templateName.lastIndexOf("."));
if (templateName.toLowerCase().equals(pdfFileName.toLowerCase())) {
matchTemplate = f;
break;
}
}
if (matchTemplate != null) {
return matchTemplate.getAbsolutePath();
}
if (defaultTemplate != null) {
return defaultTemplate.getAbsolutePath();
}
return null;
}
}
4.生成pdf
public String createPDF(Object data, String fileName, String pdfPath) {
//pdf保存路径
try {
//设置输出路径
String saveFilePath = exportToFile(fileName, data, pdfPath);
return saveFilePath;
} catch (Exception e) {
logger.error("PDF生成失败{}", ExceptionUtils.getFullStackTrace(e));
return null;
}
}
5.输出pdf文件名路径纸张大小和设置字体
public String exportToFile(String fileName, Object data, String saveFilePath) {
String htmlData = FreeMarkerUtil.getContent(fileName, data);
// System.out.println(htmlData1);
if (StringUtils.isEmpty(saveFilePath)) {
saveFilePath = getDefaultSavePath(fileName);
}
File file = new File(saveFilePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileOutputStream outputStream = null;
try {
//设置输出路径
outputStream = new FileOutputStream(saveFilePath);
//设置文档大小
Document document = new Document(PageSize.A4);
Rectangle pageSize = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth());
//横向打印
pageSize.rotate();
//分页
//设置页面
document.setPageSize(pageSize);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
//输出为PDF文件
convertToPDF(writer, document, htmlData);
} catch (Exception e) {
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return saveFilePath;
}
6.获取字体路径
public static String getFontPath() {
String classpath = PdfUtil.class.getClassLoader().getResource("").getPath();
String fontpath = classpath + "fonts";
return fontpath;
}
7.设置分页
public static void createPdf(String baseuri, List最后创建方法测试调用这些方法就可以生成pdf了,逻辑思路吸纳用freemaker将数据生成html,再用itext html转成pdf,src, String dest) throws IOException { ConverterProperties properties = new ConverterProperties(); // properties.setBaseUri(baseuri); //add font FontProvider font = new FontProvider(); font.addStandardPdfFonts(); // String a = PdfUtil.class.getClassLoader().getResource("").getPath(); // font.addFont(a + "/static/fonts/SIMSUN.TTC");// 你的字体文件 String a = PdfUtil.class.getClassLoader().getResource("").getPath(); font.addFont(FontProgramFactory.createFont( a + "/static/fonts/simsun.ttc,0")); properties.setFontProvider(font); //set media print style MediaDeviceDescription mediaDeviceDescription = new MediaDeviceDescription(MediaType.SCREEN); properties.setMediaDeviceDescription(mediaDeviceDescription); com.itextpdf.kernel.pdf.PdfWriter writer = new com.itextpdf.kernel.pdf.PdfWriter(dest); PdfDocument pdf = new PdfDocument(writer); PdfMerger merger = new PdfMerger(pdf); //use foreach to create pdf and merge the pdf which converted yet // for (String html : src) { // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // PdfDocument temp = new PdfDocument(new PdfWriter(baos)); // HtmlConverter.convertToPdf(new FileInputStream(html), temp, properties); // temp = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray()))); // merger.merge(temp, 1, temp.getNumberOfPages()); // temp.close(); // } for (String html : src) { com.itextpdf.io.source.ByteArrayOutputStream baos = new com.itextpdf.io.source.ByteArrayOutputStream(); PdfDocument temp = new PdfDocument(new com.itextpdf.kernel.pdf.PdfWriter(baos)); HtmlConverter.convertToPdf(new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)), temp, properties); temp = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray()))); merger.merge(temp, 1, temp.getNumberOfPages()); temp.close(); } pdf.close(); }
有什么不足的地方希望大家能指出问题互相学习



