ps:之前研究了使用itext html转PDF 对中文和css的支持不很好,果然Google了一把,发现flying-saucer-pdf这个效果好,研究了一下果然行,运用到项目中基本上能满足需求。

 

1、pom.xml 文件 

  1. 1 1   <dependency>
  2. 2 2 <groupId>com.itextpdf</groupId>
  3. 3 3 <artifactId>itextpdf</artifactId>
  4. 4 4 <version>5.5.13</version>
  5. 5 5 </dependency>
  6. 6 6 <dependency>
  7. 7 7 <groupId>com.itextpdf.tool</groupId>
  8. 8 8 <artifactId>xmlworker</artifactId>
  9. 9 9 <version>5.5.13</version>
  10. 10 10 </dependency>
  11. 11 11 <dependency>
  12. 12 12 <groupId>com.itextpdf</groupId>
  13. 13 13 <artifactId>itext-asian</artifactId>
  14. 14 14 <version>5.2.0</version>
  15. 15 15 </dependency>
  16. 16 16 <dependency>
  17. 17 17 <groupId>org.xhtmlrenderer</groupId>
  18. 18 18 <artifactId>flying-saucer-pdf</artifactId>
  19. 19 19 <version>9.0.3</version>
  20. 20 20 </dependency>

 

2、代码

  1. package pdf.kit;
  2. import com.itextpdf.text.*;
  3. import com.itextpdf.text.pdf.BaseFont;
  4. import com.itextpdf.text.pdf.PdfWriter;
  5. import com.itextpdf.tool.xml.Pipeline;
  6. import com.itextpdf.tool.xml.XMLWorker;
  7. import com.itextpdf.tool.xml.XMLWorkerFontProvider;
  8. import com.itextpdf.tool.xml.XMLWorkerHelper;
  9. import com.itextpdf.tool.xml.html.CssAppliers;
  10. import com.itextpdf.tool.xml.html.CssAppliersImpl;
  11. import com.itextpdf.tool.xml.html.Tags;
  12. import com.itextpdf.tool.xml.net.FileRetrieve;
  13. import com.itextpdf.tool.xml.net.ReadingProcessor;
  14. import com.itextpdf.tool.xml.parser.XMLParser;
  15. import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
  16. import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
  17. import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
  18. import com.itextpdf.tool.xml.pipeline.html.*;
  19. import org.apache.commons.io.FileUtils;
  20. import org.apache.commons.lang.StringUtils;
  21. import org.xhtmlrenderer.pdf.ITextFontResolver;
  22. import org.xhtmlrenderer.pdf.ITextRenderer;
  23. import java.io.*;
  24. import java.net.HttpURLConnection;
  25. import java.net.URL;
  26. import java.nio.charset.Charset;
  27. /**
  28. * html 转换成 pdf
  29. */
  30. public class ParseHtmlTable {
  31. public static final String pdfDestPath = "C:/Users/xxx-b/Desktop/pdf/";
  32. public static final String htmlPath = "D:\\3-workspace\\pdf-test\\src\\test\\resources\\templates\\test.html";
  33. public static void main(String[] args) throws IOException, DocumentException {
  34. String pdfName = "test.pdf";
  35. ParseHtmlTable parseHtmlTable = new ParseHtmlTable();
  36. String htmlStr = FileUtils.readFileToString(new File(htmlPath));
  37. parseHtmlTable.html2pdf(htmlStr,pdfName ,"C:\\Windows\\Fonts");
  38. }
  39. public void html2pdf(String html, String pdfName, String fontDir) {
  40. try {
  41. ByteArrayOutputStream os = new ByteArrayOutputStream();
  42. ITextRenderer renderer = new ITextRenderer();
  43. ITextFontResolver fontResolver = (ITextFontResolver) renderer.getSharedContext().getFontResolver();
  44. //添加字体库 begin
  45. File f = new File(fontDir);
  46. if (f.isDirectory()) {
  47. File[] files = f.listFiles(new FilenameFilter() {
  48. public boolean accept(File dir, String name) {
  49. String lower = name.toLowerCase();
  50. return lower.endsWith(".otf") || lower.endsWith(".ttf") || lower.endsWith(".ttc");
  51. }
  52. });
  53. for (int i = 0; i < files.length; i++) {
  54. fontResolver.addFont(files[i].getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  55. }
  56. }
  57. //添加字体库end
  58. renderer.setDocumentFromString(html);
  59. renderer.layout();
  60. renderer.createPDF(os);
  61. renderer.finishPDF();
  62. byte[] buff = os.toByteArray();
  63. //保存到磁盘上
  64. FileUtil.byte2File(buff,pdfDestPath,pdfName);
  65. } catch (Exception e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }


FileUtil.java

  1. package pdf.kit;
  2. import java.io.*;
  3. public class FileUtil {
  4. /**
  5. * 获得指定文件的byte数组
  6. *
  7. * @param filePath 文件绝对路径
  8. * @return
  9. */
  10. public static byte[] file2Byte(String filePath) {
  11. ByteArrayOutputStream bos = null;
  12. BufferedInputStream in = null;
  13. try {
  14. File file = new File(filePath);
  15. if (!file.exists()) {
  16. throw new FileNotFoundException("file not exists");
  17. }
  18. bos = new ByteArrayOutputStream((int) file.length());
  19. in = new BufferedInputStream(new FileInputStream(file));
  20. int buf_size = 1024;
  21. byte[] buffer = new byte[buf_size];
  22. int len = 0;
  23. while (-1 != (len = in.read(buffer, 0, buf_size))) {
  24. bos.write(buffer, 0, len);
  25. }
  26. return bos.toByteArray();
  27. } catch (Exception e) {
  28. System.out.println(e.getMessage());
  29. e.printStackTrace();
  30. return null;
  31. } finally {
  32. try {
  33. if (in != null) {
  34. in.close();
  35. }
  36. if (bos != null) {
  37. bos.close();
  38. }
  39. } catch (Exception e) {
  40. System.out.println(e.getMessage());
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. /**
  46. * 根据byte数组,生成文件
  47. *
  48. * @param bfile 文件数组
  49. * @param filePath 文件存放路径
  50. * @param fileName 文件名称
  51. */
  52. public static void byte2File(byte[] bfile, String filePath, String fileName) {
  53. BufferedOutputStream bos = null;
  54. FileOutputStream fos = null;
  55. File file = null;
  56. try {
  57. File dir = new File(filePath);
  58. if (!dir.exists() && !dir.isDirectory()) {//判断文件目录是否存在
  59. dir.mkdirs();
  60. }
  61. file = new File(filePath + fileName);
  62. fos = new FileOutputStream(file);
  63. bos = new BufferedOutputStream(fos);
  64. bos.write(bfile);
  65. } catch (Exception e) {
  66. System.out.println(e.getMessage());
  67. e.printStackTrace();
  68. } finally {
  69. try {
  70. if (bos != null) {
  71. bos.close();
  72. }
  73. if (fos != null) {
  74. fos.close();
  75. }
  76. } catch (Exception e) {
  77. System.out.println(e.getMessage());
  78. e.printStackTrace();
  79. }
  80. }
  81. }
  82. }

 

3.html

  1.  
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  5. <style type="text/css">
  6. *{
  7. padding: 0;
  8. margin: 0;
  9. color: #000;
  10. font-family:Microsoft YaHei
  11. }
  12. </style>
  13. </head>
  14. <body screen_capture_injected="true" ryt11773="1">
  15. <p>
  16. <span style="font-size:12.0pt; font-family:MS Mincho">長空</span> <span
  17. style="font-size:12.0pt; font-family:Times New Roman,serif">(Broken
  18. Sword),</span> <span style="font-size:12.0pt; font-family:MS Mincho">秦王殘劍</span>
  19. <span style="font-size:12.0pt; font-family:Times New Roman,serif">(Flying
  20. Snow),</span> <span style="font-size:12.0pt; font-family:MS Mincho">飛雪</span>
  21. <span style="font-size:12.0pt; font-family:Times New Roman,serif">(Moon),
  22. </span> <span style="font-size:12.0pt; font-family:MS Mincho">如月</span> <span
  23. style="font-size:12.0pt; font-family:Times New Roman,serif">(the
  24. King), and</span> <span style="font-size:12.0pt; font-family:MS Mincho">秦王</span>
  25. <span style="font-size:12.0pt; font-family:Times New Roman,serif">(Sky).</span>
  26. </p>
  27. <p>选中<input type="checkbox" value="1" disabled="disabled" checked="checked"/></p>
  28. <br/>
  29. <textarea rows="11" cols="10" disabled="disabled">
  30. adfadfadfadfa
  31. </textarea>
  32. </body>
  33. </html>
  1.  

 

  1.  

 

4、pdf结果

 

 

 

5、一些总结

   1、模板的要求: html的格式要求符合xml格式,必须要有闭合标签。

   2、字体的支持: font-family:Microsoft YaHei ,html中定义字体,程序中一定要导入想匹配的格式,才能有效。

 

版权声明:本文为dongjingzhiai原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/dongjingzhiai/p/9018956.html