Java利用模板生成pdf并导出

1.准备工作

(1)Adobe Acrobat pro软件:用来制作导出模板
(2)itext的jar包

2.开始制作pdf模板

(1)先用word做出模板界面
在这里插入图片描述
(2)文件另存为pdf格式文件
在这里插入图片描述
(3)通过Adobe Acrobat pro软件打开刚刚用word转换成的pdf文件
在这里插入图片描述
(4)点击右边的"准备表单"按钮,选择"测试.pdf"选择开始(选择工具栏里面添加文本域,可以选择在任意位置添加你想要的文本域。在文本域属性框可以设置文本的属性,例如文本的名称、字体大小、位置等)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
(5)做完上面的工作后,直接"另存为"将pdf存储就可以
在这里插入图片描述
到此模板就制作完成啦!接下来就开始写代码啦

3.开始导出pdf

(1)pdf工具类PdfUtil.java

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
public class PdfUtil {
	/**
	 * 
	 * @param o 写入的数据
	 * @param out 自定义保存pdf的文件流
	 * @param templatePath pdf模板路径
	 */
	// 利用模板生成pdf
    public  void fillTemplate(Map<String,Object> o,ServletOutputStream out,String templatePath) {
        PdfReader reader;
        ByteArrayOutputStream bos;	
        PdfStamper stamper;
        try {
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            java.util.Iterator<String> it = form.getFields().keySet().iterator();
            while (it.hasNext()) {
                String name = it.next().toString();
                System.out.println(name);
                String value = o.get(name)!=null?o.get(name).toString():null;
                form.setField(name,value);
            }
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为true
            stamper.close();

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();

        } catch (IOException e) {
            System.out.println(e);
        } catch (DocumentException e) {
            System.out.println(e);
        }
}
  
    }

(2)action文件里的方法调用PdfUtil生成pdf并导出

public String  downloadFile(){
	String json = ServletActionContext.getRequest().getParameter("json");
        try {
			json = java.net.URLDecoder.decode(json,"UTF-8");  //解码
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        JSONObject jsonObject = JSONObject.fromObject(json);
        Map<String, Object> mapJson = JSONObject.fromObject(jsonObject);
    	HttpServletResponse response = ServletActionContext.getResponse();
    	// 设置response参数,可以打开下载页面
        response.reset();
        response.setCharacterEncoding("UTF-8");
        // 定义输出类型
        response.setContentType("application/PDF;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + "assessment.pdf");
        try {
			ServletOutputStream out = response.getOutputStream();
			PdfUtil pdf = new PdfUtil();
		    pdf.fillTemplate(mapJson ,out,"模板pdf存放的路径");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
    }

(3)js发起调用(如果用Ajax发起的调用就无法打开下载页面)

var json = {};
json.studyNum = "123456789";
json.name = "TOP__ONE";
json.sex = "男";
json.birthday = "1991-01-01";
json.id = "130222111133338888";
json.addr = "河北省保定市";
var strJson = encodeURIComponent(encodeURIComponent(JSON.stringify(json)));  //编码
window.open( "../test/downloadFile.action?json="+strJson);  

(4)运行结果如下
在这里插入图片描述
⭐️欢迎关注公众号 【编程之旅】,点击干货 📚 可领取学习资料。
在这里插入图片描述
参考博客地址:https://blog.csdn.net/top__one/article/details/65442390

  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值