分页打印PDF模板

tech2023-02-22  102

分页打印PDF模板

PDF模板应用Freemarker编写,具体教程参考https://www.iteye.com/blog/demojava-800204,用法类似HTML。 demo可参考博文,了解如何使用FreeMarker生成Html web 页面

本文主要介绍如何用Java控制分页,因为freemarker自动分页不会带上表头部分,如果想要打印模板输出列表的时候,每页都带上表头部分,就需要使用Java控制分页

这里写一个公用类,对列表进行分组,就是把一位数组分成二维数组

public static <T> List<List<T>> fixedGrouping(List<T> source, int n) { if (null == source || source.size() == 0 || n <= 0) { return new ArrayList<>(); } List<List<T>> result = new ArrayList<>(); int remainder = source.size() % n; int size = (source.size() / n); for (int i = 0; i < size; i++) { List<T> subset = source.subList(i * n, (i + 1) * n); result.add(subset); } if (remainder > 0) { List<T> subset = source.subList(size * n, size * n + remainder); result.add(subset); } return result; }``` 接下来在传入HTML模板时循环传入 ```java List<List<AVInvoice>> avInvocieLists = CollectionUtil.fixedGrouping(avInvoiceList, 25); List<String> htmlPages = new ArrayList<>(); for (List<AVInvoice> datas : avInvocieLists) { HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("list", datas); htmlStr = HtmlGenerator.generate("invoice.ftl", hashMap); htmlStr = htmlStr.replaceAll("&", "&amp;");//"&"为非法字符,需转换 htmlPages.add(htmlStr); } out = PDFUtil.html2Pdf(htmlPages, response); return out;```

公用类HtmlGenerator

public class HtmlGenerator { public static String generate(String template, Map<String,Object> variables) throws Exception{ Configuration config = FreemarkerConfiguration.getConfiguation(); 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; } }``` 输出PDF ```java public static OutputStream htmlToPdf(List<String> htmlStrs, HttpServletResponse response) { OutputStream os = null; if (htmlStrs.size() > 0) { try { os = response.getOutputStream(); ITextRenderer renderer = new ITextRenderer(); //显示中文 ITextFontResolver fontResolver = renderer.getFontResolver(); fontResolver.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); for (int i = 0; i < htmlStrs.size(); i++) { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(htmlStrs.get(i).getBytes())); renderer.setDocument(doc, null); renderer.layout(); if (i == 0) { renderer.createPDF(os, false); } else { renderer.writeNextDocument(); } } renderer.finishPDF(); os.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (os != null) try { os.close(); } catch (Exception e) { os = null; } } } return os; }
最新回复(0)