Java操作PDF

java 使用 itextpdf 操作pdf,往 pdf 填入内容

准备
  1. pdf 模板
  2. 下载 Adobe Acrobat DC 软件
使用 Adobe 软件编辑 pdf模板
  1. 使用Adobe打开pdf

  2. 添加准备表单工具
    在这里插入图片描述

  3. 点击准备表单,设置表单属性在这里插入图片描述

  4. 保存pdf文档

使用 Springboot 操作PDF
1. 创建 springboot 项目,修改 pom.xml 文件

引入 pdf 工具类jar包

 <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.1</version>
        </dependency>
        <!-- itextpdf的亚洲字体支持 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

引入其他 jar 包

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
2.pdf 表单 对应实体类 合同信息 ContractInfo
/**
 * @author jxbai
 * @desc 合同信息
 * @date 2020/7/7
 */
@Data
public class ContractInfo {

    /**
     * 旅游者
     */
    private String travelName;

    /**
     * 旅行社
     */
    private String host;

    /**
     * 住所
     */
    private String address;

    /**
     * 旅行社经营许可证号
     */
    private String hostNo;

    /**
     * 联系电话
     */
    private String hostPhone;

    /**
     * 产品名称
     */
    private String productName;

    /**
     * 订单号
     */
    private String orderNo;

    /**
     * 出发日期-年
     */
    private String startYear;

    /**
     * 出发日期-月
     */
    private String startMonth;

    /**
     * 出发日期-日
     */
    private String startDay;

    /**
     * 结束时间-年
     */
    private String endYear;

    /**
     * 结束时间-月
     */
    private String endMonth;

    /**
     * 结束时间-天
     */
    private String endDay;

    /**
     * 晚
     */
    private String night;

    /**
     * 天
     */
    private String day;

    /**
     * 总天数
     */
    private String totalDay;

    /**
     * 成人费用/人
     */
    private String adultFee;

    /**
     * 儿童费用/人
     */
    private String childrenFee;

    /**
     * 总费用
     */
    private String totalFee;

    /**
     * 是否旅行社购买
     */
    private Boolean agencyBuy;

    /**
     * 保险产品名称
     */
    private String insuranceName;

    /**
     * 是否自行购买
     */
    private Boolean selfBuy;

    /**
     * 是否放弃购买
     */
    private Boolean abandonBuy;

    /**
     * 旅游者名单
     */
    private String travelerList;

    /**
     * 旅游者签字
     */
    private String travelerSign;

    /**
     * 旅行社盖章图片路径
     */
    private String stampImage;

    /**
     * 旅游者签约日期
     */
    private String travelerSignDate;

    /**
     * 旅行社签约日期
     */
    private String hostSignDate;

    /**
     * 签约地点
     */
    private String signLocation;

    /**
     * 监督所电话
     */
    private String supervisionOfficePhone;
}
3.合同相关服务接口 IContractService
/**
 * @author jxbai
 * @desc 合同相关服务
 * @date 2020/7/8
 */
public interface IContractService {
    String buildPdfContractByTemplate(HttpServletResponse response, ContractInfo info, String templatePdfPath);
}
4.合同服务功能实现类 ContractServiceImpl
/**
 * @author jxbai
 * @desc 合同服务功能实现类
 * @date 2020/7/8 0008
 */
@Service
@Slf4j
public class ContractServiceImpl implements IContractService {

    /**
     * @desc 通过合同模板创建合同pdf
     * @author jxbai
     * @date 2020/7/8
     */
    @Override
    public String buildPdfContractByTemplate(HttpServletResponse response, ContractInfo info, String templatePdfPath) {
        log.info("build pdf contract by template. contract info: {}, template path: {}", info, templatePdfPath);
        PdfReader reader = null;
        ByteArrayOutputStream bos = null;
        OutputStream os = null;
        try {
            //创建书写器,用于往document中书写信息
            reader = new PdfReader(templatePdfPath);
            bos = new ByteArrayOutputStream();
            PdfStamper stamper = new PdfStamper(reader, bos);

            //使用中文字体
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<>();
            fontList.add(baseFont);


            AcroFields form = stamper.getAcroFields();
            form.setSubstitutionFonts(fontList);

            Class<? extends ContractInfo> infoClass = info.getClass();
            Field[] infoFields = infoClass.getDeclaredFields();
            for (Field field : infoFields) {
                field.setAccessible(true);
                String fieldName = field.getName();
                if (field.get(info)  == null) {
                    continue;
                }

                if (fieldName.indexOf("Image") > 0) {
                    String imgPath = field.get(info).toString();
                    int pageNo = form.getFieldPositions(fieldName).get(0).page;
                    Rectangle rectangle = form.getFieldPositions(fieldName).get(0).position;
                    float x = rectangle.getLeft();
                    float y = rectangle.getTop();
                    //根据路径读取图片
                    Image image = Image.getInstance(imgPath);
                    //获取图片页面
                    PdfContentByte under = stamper.getOverContent(pageNo);
                    //图片大小自适应
                    image.scaleToFit(rectangle.getWidth(), rectangle.getHeight());
                    //添加图片
                    image.setAbsolutePosition(x, y - rectangle.getHeight());
                    under.addImage(image);
                } else {
                    form.setField(fieldName, field.get(info).toString());
                }
            }


            stamper.setFormFlattening(false);
            stamper.close();

            os = response.getOutputStream();
            os.write(bos.toByteArray());
        } catch (Exception e) {
            log.error("build pdf contract by template error", e.getMessage());
            return "false";
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                }
                if (null != bos) {
                    bos.close();
                }
                if (null != os){
                    os.close();
                }
            } catch (IOException e) {
                log.error("close resource error", e.getMessage());
            }
        }
        return "success";
    }
}
6.合同相关控制器 ContractController
@RestController
public class ContractController {

    @Autowired
    private IContractService contractService;

    @RequestMapping("contract/pdf/down")
    public String down(HttpServletResponse response, @RequestParam("name") String name) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        // 设置相应头,控制浏览器下载该文件,这里就是会出现当你点击下载后,出现的下载地址框
        response.setHeader("content-disposition",
                "attachment;filename=" + URLEncoder.encode("contract.pdf", "utf-8"));

        ContractInfo info = buildContractInfo(name);
        contractService.buildPdfContractByTemplate(response, info, "D:\\contract\\contractTemplate.pdf");
        return "success";
    }

    private ContractInfo buildContractInfo(String name) throws FileNotFoundException {
        ContractInfo info = new ContractInfo();
        info.setTravelName(name);
        info.setHost("XXX公司");
        info.setAddress("浙江杭州");
        info.setHostNo("1234567890");
        info.setHostPhone("15207420000");

        info.setProductName("产品名称");
        info.setOrderNo("123456789");
        String data = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String[] dates = data.split("-");
        info.setStartYear(dates[0]);
        info.setStartMonth(dates[1]);
        info.setStartDay(dates[2]);

        info.setEndYear(dates[0]);
        info.setEndMonth(dates[1]);
        info.setEndDay(dates[2]);

        info.setNight("1");
        info.setDay("1");
        info.setTotalDay("1");

        info.setAdultFee("100");
        info.setChildrenFee("100");
        info.setTotalFee("200");

        info.setAgencyBuy(true);
        info.setInsuranceName("XX保险");

        info.setStampImage("D:\\contract\\stamp.jpg" );
        info.setSupervisionOfficePhone("110");
        return info;
    }
}
6.创建 springboot 启动类
@SpringBootApplication
public class PdfDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(PdfDemoApplication.class, args);
    }
}
7.启动项目 访问地址 http://localhost:8000/contract/pdf/down?name=java操作PDF 下载pdf文件并打开,内容写入成功

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值