@Test public void test() throws Exception{ Map<String, Object> content = new HashMap<>(); content.put("list", Lists.newArrayList(new PersonDO("100001", "吴","桂花"), new PersonDO("100002", "刘","桂花"))); VelocityContext context = new VelocityContext(content); //设置velocity资源加载器 Properties prop = new Properties(); prop.setProperty(Velocity.INPUT_ENCODING, "UTF-8"); prop.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8"); prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" ); Velocity.init(prop); Template template = Velocity.getTemplate("template/table.vm"); StringWriter sw = new StringWriter(); template.merge(context, sw); File file = new File("table.html"); if (file.exists()) { file.delete(); } file.createNewFile(); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.write(sw.toString(), outputStream, "UTF-8" ); // vm -> html Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("table.pdf")); document.open(); // 支持中文 XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider() { @Override public Font getFont(final String fontname, String encoding, float size, final int style) { try { BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); return new Font(bfChinese, size, style); } catch (Exception e) { } return super.getFont(fontname, encoding, size, style); } }; XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream("table.html"), null, Charset.forName("UTF-8"), fontProvider); // html -> pdf // step 5 document.close(); }
pom:
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.11</version> </dependency> <dependency> <groupId>com.itextpdf.tool</groupId> <artifactId>xmlworker</artifactId> <version>5.5.11</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>