JAVA使用itextPdf将数据填入PDF模版文件的方式打印PDF文件

本文介绍了如何使用Java库itexPdf处理Word模版,将数据动态填充到PDF中,通过PdfPrintHelper类实现PDF打印功能,包括字段类型判断和数据插入,适用于前端快速生成PDF的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、背景

客户提供了一个Word格式的打印模版,需要把数据填入

对于前端来讲,再重新排版布局,可就太折磨人了,而且像这种需求,我们还会经常接到,所以就考虑,有没有一种方式,在已经有打印模版的情况下,如何能快速地实现这个需求,经过查找,发现使用itexPdf可以往PDF模版中放入数据,word文件可以很轻易地转换为pdf文件,所以经过一番探索,自己写了一个PDF打印工具类

二、类源码:

PdfPrintHelper类

package com.ll.hiws.common.utils.pdf;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class PdfPrintHelper {

    public static byte[] getPdfDataFromTemplate(Object bean, String templateFullPath) throws Exception {

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfReader reader = new PdfReader(templateFullPath);
        PdfStamper ps = new PdfStamper(reader, os);
        AcroFields form = ps.getAcroFields();
        BaseFont bf = BaseFont.createFont("SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        form.addSubstitutionFont(bf);

        putDataToForm(bean, form,ps);
        ps.setFormFlattening(true);
        ps.close();
        reader.close();
        return os.toByteArray();
    }

    private static void putDataToForm(Object bean, AcroFields form,PdfStamper ps) throws Exception {
        Field[] fields = bean.getClass().getDeclaredFields();
        for(Field field:fields){
            field.setAccessible(true);
            PdfPrintAnnotation printAnnotation = field.getAnnotation(PdfPrintAnnotation.class);
            if ( null == printAnnotation){
                continue;
            }
            Object fieldObject = field.get(bean);
            String fieldStringValue;
            PdfPrintAnnotation.PdfFieldType fieldType = printAnnotation.pdfFieldType();
            String fieldName = printAnnotation.pdfFieldName();
            if(null == fieldObject || null == fieldName || "".equals(fieldName.trim())){
                continue;
            }

            switch (fieldType){
                case TEXT:
                    fieldStringValue = getBeanFieldStringValue(fieldObject);
                    if( null != form.getFi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值