import com.csii.pe.core.PeException;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class VelocityPdfUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(VelocityPdfUtils.class);
private static final String FONT_FILE_PATH = "c:/Windows/Fonts/simsun.ttc"; // 字体文件可以拷贝出来放到相对路径下
private static final VelocityEngine VELOCITY_ENGINE;
static {
VELOCITY_ENGINE = new VelocityEngine();
VELOCITY_ENGINE.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
VELOCITY_ENGINE.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
VELOCITY_ENGINE.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
VELOCITY_ENGINE.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
VELOCITY_ENGINE.init();
}
/**
* 使用Velocity模板引擎渲染模板文件
*
* @param templateFileName 模板文件
* @param data 渲染数据模型
* @return 渲染后的字符串结果
*/
public static String renderTemplateToString(String templateFileName, Map<String, Object> data) {
Template t = VELOCITY_ENGINE.getTemplate(templateFileName);
VelocityContext ctx = new VelocityContext();
ctx.put("data", data);
StringWriter sw = new StringWriter();
t.merge(ctx, sw);
return sw.toString();
}
/**
* 根据文档内容生成pdf文件
*
* @param documentContent 文档内容
* @param pdfPath 生成的pdf路径
* @param pdfName 生成的pdf文件名称
*/
public static void generatePDFFileFromDocumentToFileSystem(String documentContent, String pdfPath, String pdfName) throws PeException {
ITextRenderer renderer = new ITextRenderer();
// renderer.setDocument(new File(htmlFile).toURI().toString());
renderer.setDocumentFromString(documentContent);
ITextFontResolver fontResolver = renderer.getFontResolver();
try {
fontResolver.addFont(FONT_FILE_PATH, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) {
LOGGER.error("文档处理失败", e);
throw new PeException(e);
} catch (IOException e) {
LOGGER.error("字体文件读取失败", e);
throw new PeException(e);
}
renderer.layout();
String pdfFile = pdfPath + pdfName;
LOGGER.info("准备创建PDF文件至{}", pdfPath);
try (OutputStream os = new FileOutputStream(new File(pdfFile));) {
renderer.createPDF(os);
renderer.finishPDF();
os.flush();
} catch (DocumentException | IOException e) {
LOGGER.error("PDF生成失败", e);
throw new PeException(e);
}
}
public static void main(String[] args) throws Exception {
String content = renderTemplateToString("/pdf/template/test.vm", new HashMap<String, Object>() {{
List list = new ArrayList();
for (int i = 0; i < 100; i++) {
list.add(new HashMap<String, Object>() {{
put("stdbillnum", "C101111111\n111111111");
put("stdpmmoney", "400,000.00");
put("acceptmoney", "204,000.00");
put("stdissdate", "2020-08-02");
put("stdduedate", "2020-08-02");
put("stdpyeenam", "啦啦啦德玛西亚公司");
put("stdpyeeacc", "79999999999999");
put("stdpyeebnm", "苏中农村商业\n银行同理支行");
}});
}
put("List", list);
}});
System.out.println(content);
generatePDFFileFromDocumentToFileSystem(content, "E:\\", "test1.pdf");
}
}