项目中使用itext 和模板 前台导出PDF并下载

AcroPro 

使用AcroPro创建模板 先创建doc文件 编辑你想要生成pdf的模板 另存为.pdf格式的文件

用AcroPro打开文件点击右边最下方的 准备表单 点击开始 再点击上面Tt的图标编辑你要替换的内容 保存

基本内容准备完毕

代码

package com.example.demo.Test;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wkg
 * @Date: 2018/6/22 09:32
 * @Description:
 */
@RestController
@RequestMapping("pdf")
public class PDFTemplate {
    @RequestMapping("pdfDownload")
 public void test(HttpServletResponse response) throws IOException, DocumentException {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("实际导出的PDF名称", "UTF-8") + ".pdf");
        //编码
        response.setCharacterEncoding("UTF-8");
        String fileName = "D:/1.pdf"; // pdf模板路径  可根据项目实际路径
        PdfReader reader = new PdfReader(fileName);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        /* 将要生成的目标PDF文件名称 */
        PdfStamper ps = new PdfStamper(reader, bos);
        /* 使用中文字体 */
        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
        fontList.add(bf);

        /* 取出报表模板中的所有字段 */
        AcroFields fields = ps.getAcroFields();
        fields.setSubstitutionFonts(fontList);
        fillData(fields, data());

        /* 必须要调用这个,否则文档不会生成的 */
        ps.setFormFlattening(true);
        ps.close();
        response.getOutputStream().write(bos.toByteArray());
        bos.close();
    }

 private static void fillData(AcroFields fields, Map<String, String> data)
            throws IOException, DocumentException {
        for (String key : data.keySet()) {
            String value = data.get(key);
            fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
        }
    }

    private static Map<String, String> data() {
        Map<String, String> data = new HashMap<String, String>();
        data.put("qq", "test:");//qq ww就是在PDF中编辑的替换内容
        data.put("ww", "xx第10000001号");
        return data;
    }
}

输入http://localhost:8080/pdf/pdfDownload

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值