itextpdf插件下XMLWorkerHelper工具用HTML代码实现PDF的导出功能(解决Linux服务器中文不显示的问题)

  • 效果展示

  • 开工

  1. 引入jar包
    1. 		<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>

       

  2. html代码示例

    1. <?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>

       

  3. PDF工具类 
    1. 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();
          }
      }

       

  4. 调用

    1.  

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、解决中文问题 2、附字体 3、动态html拼接转pdf public static void htmlCodeComeString(String linkcss,String htmlCode, String outputFile,String title) throws Exception { OutputStream os = new FileOutputStream(outputFile); ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(getConversionHtmlCode(linkcss,htmlCode,title)); ITextFontResolver fontResolver = renderer.getFontResolver(); URL fontPath = ItextUtil.class.getResource("simsun.ttc"); fontResolver.addFont(fontPath.toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 解决图片的相对路径问题 // renderer.getSharedContext().setBaseURL("file:/F:/teste/html/"); renderer.layout(); renderer.createPDF(os); System.out.println("======转换成功!"); os.close(); os.flush(); } public static void main(String[] args) { ItextUtil itextUtil = new ItextUtil(); String html = ""; html += ""; html += "企业信息"; html += " "; html += " "; html += " 登记日期"; html += " 2006-04-28"; html += " "; html += " "; html += " 纳税人编号"; html += " HSJIHKS002"; html += " "; html += " "; html += " 有效标志"; html += " Y"; html += " "; html += " "; html += " 社会信用代码"; html += " 916101317H"; html += " "; html += " "; html += " 评估机关代码"; html += " 盛世"; html += " "; html += " "; html += " 工商注销日期"; html += " 2006-04-28"; html += " "; html += " "; html += ""; String outputFile = "D:\\pdf\\aa.pdf"; try { itextUtil.htmlCodeComeString("",html,outputFile,""); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("生成结束!!!"); }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值