java 生成 PDF

1,创建fonts文件夹下两个文件 simsun.ttf  (字体下载地址 simsun.ttf下载-simsun.ttf字体下载-当易网)   和static下的ftl模板,在线转html地址(Word转HTML——免费在线Word转网页

properties配置

2 pom文件

<!-- pdf:start -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.11</version>
        </dependency>
        <!-- 支持中文 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- 支持css样式渲染 -->
        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf-itext5</artifactId>
            <version>9.1.16</version>
        </dependency>
        <!-- 转换html为标准xhtml包 -->
        <dependency>
            <groupId>net.sf.jtidy</groupId>
            <artifactId>jtidy</artifactId>
            <version>r938</version>
        </dependency>
        <!-- 以下两个依赖可能会下载不了 q: 2826324267  -->
<!-- https://mvnrepository.com/artifact/css2parser/ss_css2 -->
		<dependency>
			<groupId>css2parser</groupId>
			<artifactId>ss_css2</artifactId>
			<version>0.9.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.zefer/pd4ml -->
		<dependency>
			<groupId>org.zefer</groupId>
			<artifactId>pd4ml</artifactId>
			<version>1.0.0</version>
		</dependency>
<!-- pdf:end -->

3、工具类3

package io.renren.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.MalformedURLException;
import java.security.InvalidParameterException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Calendar;

import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;

/**
 * @Description: 生成PDF合同工具类
 * @author liguodong
 * @date 2022年3月6日 下午5:19:32
 */
public class GeneratePdfUtil {

    //private static final String TEMPORARY_CONTRACT_HTML = "E:\\workspace\\dytc\\dytc\\seezoon-admin-server\\src\\main\\resources\\contract\\temporary.html";// 临时HTML合同,用于转PDF格式
    private static final String TEMPORARY_CONTRACT_HTML = "vast_service/vast_service_backstages/src/main/resources/static/temporary.html";
    //private static final String SIMSUM_FILE = "E:\\workspace\\dytc\\dytc\\seezoon-admin-server\\src\\main\\resources\\common\\simsun.ttc";// 添加字体,解决中文支持问题


    public static String GenerateContract(ContractDynamicParam param) throws Exception {
        // 生成html合同
        generateHTML(param.getTemplatePath(), param.getTemplateName(), param.getContractParam());
        // 根据html合同生成pdf合同
        generatePDF(param.getContractPath() + param.getContractName());
        // 删除临时html格式合同
        removeFile(TEMPORARY_CONTRACT_HTML);
        return param.getContractPath() + param.getContractName();
    }

    /**
     * @Description 生成html格式合同
     */
    private static void generateHTML(String templatePath, String templateName, Map<String, Object> paramMap) throws Exception {


        Configuration cfg = new Configuration();
        cfg.setDefaultEncoding("UTF-8");
        /**
         * 1.setClassForTemplateLoading(this.getClass(), "/HttpWeb");
         * 基于类路径,HttpWeb包下的framemaker.ftl文件
         * 2.setDirectoryForTemplateLoading(new File("/template"));
         * 基于文件系统,template目录下的文件
         * 3.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");
         * 基于Servlet Context,指的是基于WebRoot下的template下的framemaker.ftl文件
         */
        cfg.setDirectoryForTemplateLoading(new File(templatePath));

        // templateName.ftl为要装载的模板
        Template template = cfg.getTemplate(templateName);

        File outHtmFile = new File(TEMPORARY_CONTRACT_HTML);

        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outHtmFile)));
        // 将参数输出到模版,并操作到HTML上
        template.process(paramMap, out);
        out.close();
    }


    private static int topValue = 10;
    private static int leftValue = 20;
    private static int rightValue = 10;
    private static int bottomValue = 10;
    private static int userSpaceWidth = 650;
    /**
     * @Description 根据html生成pdf格式合同
     */
    private static void generatePDF(String pdfUrl) throws Exception {

        try {
//            Test jt = new Test();
            //此处填写你的html文件
            String html = readFile("vast_service/vast_service_backstages/src/main/resources/static/temporary.html", "UTF-8");
            //此处填写你下载的地方
            doConversion2(html, "C:/Users/LENOVO/Desktop/贷款合同.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void doConversion2(String htmlDocument, String outputPath)
            throws InvalidParameterException, MalformedURLException,
            IOException {
        PD4ML pd4ml = new PD4ML();
        pd4ml.enableDebugInfo();
        pd4ml.setHtmlWidth(userSpaceWidth);
        pd4ml.setPageSize(PD4Constants.A4);
        pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue,
                rightValue));
//此处的classPath注意一定要获取到你放fonts的文件夹。他需要获取到你下载的字体
        String classPath = Test.class.getResource("/")+"fonts/";
        pd4ml.useTTF(classPath, true);
        pd4ml.setDefaultTTFs("SimSun", "SimSun", "SimSun");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pd4ml.render(new StringReader(htmlDocument), baos);
        baos.close();
        File output = new File(outputPath);
        java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
        fos.write(baos.toByteArray());
        fos.close();
    }

    private final static String readFile(String path, String encoding)
            throws IOException {
        File f = new File(path);
        FileInputStream is = new FileInputStream(f);
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        byte buffer[] = new byte[2048];
        int read;
        do {
            read = is.read(buffer, 0, buffer.length);
            if (read > 0) {
                fos.write(buffer, 0, read);
            }
        } while (read > -1);
        fos.close();
        bis.close();
        is.close();
        return fos.toString(encoding);
    }

    /**
     * @Description 移除文件
     */
    private static void removeFile(String fileUrl) {
        File file = new File(fileUrl);
        file.delete();
    }

    public static void returnPdfStream(HttpServletResponse response, String pathName) throws Exception {
        response.setContentType("application/pdf");

        File file = new File(pathName);
        if (file.exists()) {
            FileInputStream in = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[1024 * 5];
            int n;
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n);
            }
            out.flush();
            in.close();
            out.close();
        }
    }
}

4.测试类 

package io.renren.common.utils;

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: syh
 * @CreateTime: 2022/5/20 09:47
 */
public class Test {


    public static void main(String[] args) throws Exception {

        String TEMPLATES_PATH = "模板地址(**.ftl)";
        String CONTRACT_PATH = "输出路径";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("borrower", "張三冯");
        paramMap.put("lender", "**产品");
        paramMap.put("guarantor", "lisa");
        paramMap.put("create_date", format);
        paramMap.put("real_name", "张三");
        paramMap.put("card_id", "1654654654564654654654");
        paramMap.put("address", "fdsafasdfasdfsd");
        paramMap.put("repayment_date", format);
        paramMap.put("repayment_amount", "132123");
        paramMap.put("interest_rate", "1");
        paramMap.put("Interest", "1");
        ContractDynamicParam param = new ContractDynamicParam(TEMPLATES_PATH, "052012085952.ftl", CONTRACT_PATH, "贷款合同.pdf", paramMap);
        GeneratePdfUtil.GenerateContract(param);
        System.out.println("====test生成PDF合同成功====");
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值