-
效果展示
-
开工
- 引入jar包
-
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.2</version> </dependency> <dependency> <groupId>com.itextpdf.tool</groupId> <artifactId>xmlworker</artifactId> <version>5.4.1</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
-
-
html代码示例
-
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> body { font-family: SimSun; font-size: 14px; } table { width: 700px;text-align: center;border-collapse:collapse; } .detailTable { border-collapse: collapse; border-spacing: 0; border-left: 1px solid #333; border-top: 1px solid #333; text-align: center; } .detailTable th td { border-right: 1px solid #333; border-bottom: 1px solid #333; } .detailWidth { width: 20% } span { font-weight: bold; font-size: x-large; } </style> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> </head> <body> <div align="center"> <table> <tr> <td style="width: 35%;text-align: left">业务流水: YYYYYYYYYYYYYYYYY</td> <td style="width: 55%;"><span>租赁资产租金支付</span></td> <td style="width: 10%">交易流水: </td> </tr> </table> </div> <div style="white-space: pre"><br/></div> <div align="center"> <table> <tr> <td style="width: 30%; text-align: left">交易日期: 20200831</td> <td style="width: 40%">交易部门: 010003</td> <td style="width: 30%">币种: 人民币</td> </tr> </table> </div> <div align="center"> <table border="1" class="detailTable"> <tr> <th>账务机构</th> <th>科目</th> <th>借方金额</th> <th>贷方金额</th> <th>摘要</th> </tr> <tr> <td class="detailWidth">财务管理部财</td> <td class="detailWidth">科密啊</td> <td class="detailWidth">200,000.00</td> <td class="detailWidth"></td> <td class="detailWidth">内容</td> </tr> <tr> <td class="detailWidth">财务管理部2</td> <td class="detailWidth">科密啊2</td> <td class="detailWidth"></td> <td class="detailWidth">200,000.00</td> <td class="detailWidth">内容2</td> </tr> <tr> <td class="detailWidth">合计</td> <td class="detailWidth"></td> <td class="detailWidth">200,000.00</td> <td class="detailWidth">200,000.00</td> <td class="detailWidth"></td> </tr> </table> </div> <div style="white-space: pre"><br/></div> <div align="center"> <table> <tr> <td style="width: 20%"></td> <td style="width: 30%;text-align: left">19003(某某人)</td> <td style="width: 30%;text-align: left">19003(某某人)</td> <td style="width: 20%"></td> </tr> </table> </div> </body> </html>
-
- PDF工具类
-
package com.cloud.util; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.tool.xml.XMLWorkerFontProvider; import com.itextpdf.tool.xml.XMLWorkerHelper; import com.itextpdf.tool.xml.html.CssAppliers; import com.itextpdf.tool.xml.html.CssAppliersImpl; import com.itextpdf.tool.xml.html.Tags; import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.charset.Charset; public class PdfUtil { private static final Logger LOG = LoggerFactory.getLogger(PdfUtil.class.getName()); /** * 重写 字符设置方法,解决中文乱码问题 */ public static class MyFontsProvider extends XMLWorkerFontProvider { @Override public Font getFont(final String fontname, final String encoding, final boolean embedded, final float size, final int style, final BaseColor color) { BaseFont bf = null; try { bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); } catch (Exception e) { LOG.error(e.getMessage()); } Font font = new Font(bf, size, style, color); font.setColor(color); return font; } } /** * PDF生成路径 */ public static final String PDF_DOWNLOAD_PATH = File.separator +"tempDir"+File.separator; /** * 导出PDF文件 * * @param content * @param response */ public static void exportPdf(String fileName, String content, HttpServletResponse response) { FileOutputStream fos = null; FileInputStream in = null; OutputStream out = null; Document document = new Document(); File newPath = null; try { if (StringUtils.isEmpty(fileName)) { fileName = "123"; } fileName+=".pdf"; fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); String dicPath = new File(".").getCanonicalPath(); String srcPath = dicPath + PDF_DOWNLOAD_PATH + fileName; newPath = new File(dicPath + PDF_DOWNLOAD_PATH); newPath.mkdirs(); // 删除临时文件 boolean success = fileDelete(newPath); if (success) { newPath.mkdirs(); File file = new File(srcPath); fos = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, fos); document.open(); InputStream htmlInput = new ByteArrayInputStream(content.getBytes("UTF-8")); // 使用我们的字体提供器,并将其设置为unicode字体样式 MyFontsProvider fontProvider = new MyFontsProvider(); fontProvider.addFontSubstitute("lowagie", "garamond"); fontProvider.setUseUnicode(true); CssAppliers cssAppliers = new CssAppliersImpl(fontProvider); HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory()); XMLWorkerHelper.getInstance().getDefaultCssResolver(true); XMLWorkerHelper.getInstance().parseXHtml(writer, document, htmlInput, null, Charset.forName("UTF-8"), fontProvider); document.close(); writer.close(); // 设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("multipart/form-data"); // 设置响应头,控制浏览器下载该文件 response.setHeader("content-disposition", "attachment;filename=" + fileName); // 读取要下载的文件,保存到文件输入流 in = new FileInputStream(srcPath); // 创建输出流 out = response.getOutputStream(); // 创建缓冲区 byte buffer[] = new byte[1024]; int len = 0; // 循环将输入流中的内容读取到缓冲区当中 while ((len = in.read(buffer)) > 0) { // 输出缓冲区的内容到浏览器,实现文件下载 out.write(buffer, 0, len); } } } catch (DocumentException e) { throw new RuntimeException("Export PDF error : ", e); } catch (IOException e) { throw new RuntimeException("Export PDF error : ", e); } catch (Exception e) { throw new RuntimeException("Export PDF error : ", e); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); if (newPath != null) { fileDelete(newPath); } } } /** * 删除文件 * * @param file * @return */ private static boolean fileDelete(File file) { if (file.isDirectory()) { String[] children = file.list(); // 递归删除目录中的子目录下 for (int i = 0; i < children.length; i++) { boolean success = fileDelete(new File(file, children[i])); if (!success) { return false; } } } // 目录此时为空,可以删除 return file.delete(); } }
-
-
调用
-