Java PDF操作总结

最近公司有个需求,要求根据数据动态生成PDF文件,然后再送往无纸化系统进行签章。现在公司的无纸化系统,只支持传递固定的pdf表单,当数据是一个长度不固定的列表时。PDF的表单就没发满足现有的需求。

通过模板引擎生成html,并将html转换为pdf文件

相关依赖:

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>
<!--html转换pdf,会自动引入itext2-->
<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>core-renderer</artifactId>
    <version>R8</version>
</dependency>
<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.0.8</version>
</dependency>

PDF工具类:

import com.csii.pe.core.PeException;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VelocityPdfUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(VelocityPdfUtils.class);

    private static final String FONT_FILE_PATH = "c:/Windows/Fonts/simsun.ttc"; // 字体文件可以拷贝出来放到相对路径下
    private static final VelocityEngine VELOCITY_ENGINE;

    static {
        VELOCITY_ENGINE = new VelocityEngine();
        VELOCITY_ENGINE.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        VELOCITY_ENGINE.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        VELOCITY_ENGINE.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        VELOCITY_ENGINE.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        VELOCITY_ENGINE.init();
    }

    /**
     * 使用Velocity模板引擎渲染模板文件
     *
     * @param templateFileName 模板文件
     * @param data             渲染数据模型
     * @return 渲染后的字符串结果
     */
    public static String renderTemplateToString(String templateFileName, Map<String, Object> data) {
        Template t = VELOCITY_ENGINE.getTemplate(templateFileName);
        VelocityContext ctx = new VelocityContext();
        ctx.put("data", data);
        StringWriter sw = new StringWriter();
        t.merge(ctx, sw);
        return sw.toString();
    }

    /**
     * 根据文档内容生成pdf文件
     *
     * @param documentContent 文档内容
     * @param pdfPath         生成的pdf路径
     * @param pdfName         生成的pdf文件名称
     */
    public static void generatePDFFileFromDocumentToFileSystem(String documentContent, String pdfPath, String pdfName) throws PeException {
        ITextRenderer renderer = new ITextRenderer();
        // renderer.setDocument(new File(htmlFile).toURI().toString());
        renderer.setDocumentFromString(documentContent);
        ITextFontResolver fontResolver = renderer.getFontResolver();
        try {
            fontResolver.addFont(FONT_FILE_PATH, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            LOGGER.error("文档处理失败", e);
            throw new PeException(e);
        } catch (IOException e) {
            LOGGER.error("字体文件读取失败", e);
            throw new PeException(e);
        }
        renderer.layout();
        String pdfFile = pdfPath + pdfName;
        LOGGER.info("准备创建PDF文件至{}", pdfPath);
        try (OutputStream os = new FileOutputStream(new File(pdfFile));) {
            renderer.createPDF(os);
            renderer.finishPDF();
            os.flush();
        } catch (DocumentException | IOException e) {
            LOGGER.error("PDF生成失败", e);
            throw new PeException(e);
        }
    }

    public static void main(String[] args) throws Exception {
        String content = renderTemplateToString("/pdf/template/test.vm", new HashMap<String, Object>() {{
            List list = new ArrayList();
            for (int i = 0; i < 100; i++) {
                list.add(new HashMap<String, Object>() {{
                    put("stdbillnum", "C101111111\n111111111");
                    put("stdpmmoney", "400,000.00");
                    put("acceptmoney", "204,000.00");
                    put("stdissdate", "2020-08-02");
                    put("stdduedate", "2020-08-02");
                    put("stdpyeenam", "啦啦啦德玛西亚公司");
                    put("stdpyeeacc", "79999999999999");
                    put("stdpyeebnm", "苏中农村商业\n银行同理支行");
                }});
            }
            put("List", list);
        }});
        System.out.println(content);
        generatePDFFileFromDocumentToFileSystem(content, "E:\\", "test1.pdf");
    }
}

模板文件:

<!DOCTYPE html>
<html>
<head>
    <!-- @page 用于指定pdf的长和宽 -->
    <style>
        @page {
            size: 500mm 200mm;
        }
        body {
            font-family: SimSun;
            text-align: center;
            font-size: 10px;
        }

        table.gridtable {
            font-size: 11px;
            color: #333333;
            border-width: 1px;
            border-color: #666666;
            border-collapse: collapse;
            width: 96%;
            table-layout: fixed;
        }

        table.gridtable th {
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #666666;
            text-align: center;
            font-weight: bold;
            word-break: break-all;
            word-wrap: break-word;
            overflow:hidden;
            width: 20px;
        }

        table.gridtable td {
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #666666;
            background-color: #ffffff;
            text-align: center;
            word-break: break-all;
            word-wrap: break-word;
            overflow:hidden;
            width: 20px;
        }

    </style>
    <title></title>
</head>
<body>
<h1>承兑汇票清单</h1>
<table class="gridtable">
    <tr>
        <th>合同汇票号</th>
        <th>金额</th>
        <th>应交保证金额</th>
        <th>出票日</th>
        <th>承兑到期日</th>
        <th>收款人名称</th>
        <th>收款人账号</th>
        <th>开户银行</th>
    </tr>
    #foreach($i in $data.List)
        <tr>
            <td>$data.List[0].stdbillnum</td>
            <td>$data.List[0].stdpmmoney</td>
            <td>$data.List[0].acceptmoney</td>
            <td>$data.List[0].stdissdate</td>
            <td>$data.List[0].stdduedate</td>
            <td>$data.List[0].stdpyeenam</td>
            <td>$data.List[0].stdpyeeacc</td>
            <td>$data.List[0].stdpyeebnm</td>
        </tr>
    #end
</table>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值