欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

合同模板html转pdf

程序员文章站 2024-01-18 23:02:46
...

html转pdf

maven jar包
<!-- https://mvnrepository.com/artifact/org.xhtmlrenderer/flying-saucer-pdf -->
        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf</artifactId>
            <version>9.1.20</version>
        </dependency>
代码
package xxx;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.text.SimpleDateFormat;

public class Pdf {

    private static final String FILE_HOME = "C:\\Users\\admin\\Desktop\\protocol_test";

    public String getTemplate() {
        return "<div class=\"contract_text\">" +
                "<p>合同编号:HT001</p>" +
                "  <h2 style=\"text-align:center\">xxx合同</h2> " +
                "  <p style=\"text-indent:2em\">>在您点击同意本合同之前,请您务必审慎阅读、充分理解各条款内容,特别是免除或者限制贷款人责任、增加借款人责任或限制借款*利的条款、法律适用和争议解决条款。" +
                "一旦您勾选\"我已阅读并同意\"等确认按钮(按钮名称以平台显示为准,下同)确认后即视为对本合同全部条款及相关业务规则已充分理解并完全接受。</p>" +
                "  <table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\">" +
                "    <tr>" +
                "      <td width=\"20%\"><strong>贷款人 </strong></td>" +
                "      <td width=\"30%\">xx有限公司xx有限公司xx有限公司xx有限公司xx有限公司xx有限公司 <br />" +
                "        (以下简称&ldquo;贷款人&rdquo;或者&ldquo;xxx&rdquo;) </td>" +
                "      <td width=\"20%\"><strong>借款人 </strong></td>" +
                "      <td width=\"30%\">【&nbsp;xx借款人xx借款人xx借款人xx借款人&nbsp;】&nbsp;(以下简称&ldquo;借款人&rdquo;) </td>" +
                "    </tr>" +
                "  </table>" +
                "</div>";
    }

    public String parseHtml() {
        String template = getTemplate();
        template=template.replaceAll("<table ", "<table style=\"table-layout:fixed; word-break:break-strict;font-size:13px;\" ");

        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        html.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        html.append("<head>");
        html.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");

        html.append("<style>");
        html.append(" body {");
        html.append("   margin: 0;");
        html.append("   padding: 0;");
        html.append("   color: #000;");
        html.append("   font-size: 16px;");
        html.append("   font-family: SimSun;");
        html.append("   background: #fff;");
        html.append(" }");
        html.append("</style>");
        html.append("</head>").append("<body>");
        html.append(template);
        html.append("</body></html>");
        return html.toString();
    }

    public boolean generatePdf() {
        // file name
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = format.format(System.currentTimeMillis());
        String fileName = "test_" + date + ".pdf";

        // file path
        String filePath = FILE_HOME + File.separator + fileName;
        // html content
        String html = parseHtml();


        File file = new File(filePath);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdir();
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
            ITextRenderer renderer = new ITextRenderer();

            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont("mytff/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            renderer.setDocumentFromString(html);
            renderer.layout();
            renderer.createPDF(os);
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (DocumentException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        System.out.println("已生成:" + filePath);
        return true;
    }

}

测试
package xxx;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class PdfTest {

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void generatePdf() {
        Pdf pdf = new Pdf();
        boolean suc = pdf.generatePdf();
        if (suc) {
            System.out.println("生成成功!");
        } else {
            System.out.println("生成失败!");
        }
    }
}
效果展示

合同模板html转pdf

总结
  1. 中文不显示

    body标签未加font-family;