根据pdf模板导出pdf文件

根据pdf模板导出pdf文件

你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。

为帮助您在CSDN创作的文章获得更多曝光和关注,我们为您提供了专属福利:
已注册且未在CSDN平台发布过文章的用户,9月1日—9月30日期间发布首篇文章可享大额首篇流量券扶持,且发布首篇文章后30日内,享连续每日流量券扶持;
已注册且未在CSDN平台发布过文章的用户,在8月1日—8月30日期间发布过首篇,可自9月1日起,享连续30天每日流量券扶持;

更多福利介绍详见https://mp.csdn.net/mp_blog/manage/traffic

如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。

制作pdf模板

使用Adobe Acrobat pro软件,制作模板可参考:https://blog.csdn.net/TOP__ONE/article/details/65442390

在pom.xml中添加包itextpdf:

    <!--PDF-->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.4.3</version>
    </dependency>

根据模板下载(serviceimpl文件)

    public String createPDF(CasesEntity casesEntity) throws DocumentException, IOException {
        Map<String, Object> paramsa = Maps.newHashMap();
        Map<String, Object> params = Maps.newHashMap();
        String category = casesEntity.getCategory();
        if (Objects.equals(category, "推进")) {
            //   推进
            paramsa.put("series1", casesEntity.getSeries() + "案例");
            paramsa.put("power", "机组:" + casesEntity.getPower() + "kW");
            paramsa.put("rotateSpeed", "转速:" + casesEntity.getRotateSpeed() + "r/min");
            params = getSame(casesEntity, paramsa);
        } else if (Objects.equals(category, "发电")) {
            //    发电
            paramsa.put("series1", casesEntity.getSeries() + "案例");
            paramsa.put("power", "功率:" + casesEntity.getPower() + "kW");
            paramsa.put("rotateSpeed", "转速:" + casesEntity.getRotateSpeed() + "r/min");
            params = getSame(casesEntity, paramsa);
        }

//        // 字体样式
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        ArrayList<BaseFont> fontList = new ArrayList<>();
        fontList.add(bf);

        // 利用模板生成pdf
        String templatePath = "C:/Users/Desktop/cases.pdf";

        // 生成的新文件路径
        String caseId = casesEntity.getId();
        String newPDFPath = "C:/Users/Desktop/" + caseId + "ceshi.pdf";

        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            form.setSubstitutionFonts(fontList);
            for (String key : params.keySet()) {
                form.setField(key, (String) params.get(key));
            }
            //添加图片
            String hostImage = "C:/Users/Desktop/3.png";
            addImage(stamper, form, "hostImage_af_image", hostImage);

            String shipImage = "C:/Users/Desktop/5.jpg";
            addImage(stamper, form, "shipImage_af_image", shipImage);

            String white = "C:/Users/Desktop/white.png";
            addImage(stamper, form, "background_af_image", white);
            //  字体大小
            if (MapUtils.isNotEmpty(params)) {
                for (Map.Entry<String, Object> next : params.entrySet()) {
                    String key = next.getKey();
                    String value = StringUtils.defaultString((String) next.getValue());
                    // 默认12号字体
                    float fontSize = 20f;
                    form.setFieldProperty(key, "textsize", fontSize, null);
                    form.setField(key, value);
                }
                float fontSize = 30f;
                form.setFieldProperty("series1", "textsize", fontSize, null);
                form.setField("series1", StringUtils.defaultString((String) params.get("series1")));
                float fontSize1 = 25f;
                form.setFieldProperty("shipType", "textsize", fontSize1, null);
                form.setField("shipType", StringUtils.defaultString((String) params.get("shipType")));
            }
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为true
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            copy.open();
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            copy.close();
            return newPDFPath;
        } catch (IOException | DocumentException e) {
            throw new RuntimeException(e);
        }
    }

导入照片代码(serviceimpl文件)

    public static void addImage(PdfStamper stamper,AcroFields form,String field,String fieldValue){
        try{
            java.util.List<AcroFields.FieldPosition> photograph = form.getFieldPositions(field);
            if(photograph!=null && photograph.size()>0){
                Rectangle rect= photograph.get(0).position;
                Image img = Image.getInstance(fieldValue);
                img.scaleToFit(rect.getWidth() ,rect.getHeight());
                img.setAbsolutePosition(rect.getLeft() ,rect.getBottom());
                PdfContentByte cb = stamper.getOverContent(photograph.get(0).page);
                cb.addImage(img);
            }
            else{
                String field1 = "C:/Users/Desktop/white.png";
                addImage(stamper,form,field,field1);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

附getSame函数(serviceimpl文件)

    private Map<String, Object> getSame(CasesEntity casesEntity, Map<String, Object> params) {
        params.put("series2", "系列:"+ casesEntity.getSeries());
        params.put("shipType", casesEntity.getShipName());
        params.put("buildTime","建造时间:" + casesEntity.getBuildTime());
        params.put("tonnage","吨位:" + casesEntity.getTonnage() + " " + casesEntity.getUnit());
        return params;
    }

Map字典params中关键字为创建pdf模板时的id。

Controller层

/**
 * 导出案例
 *
 * @param CasesEntity
 * @return RestResponse
 */
@ApiOperation(value = "导出案例", notes = "导出案例")
@RequestMapping(value = "/export", method = RequestMethod.POST)
public RestResponse export(@RequestBody CasesEntity casesEntity, HttpServletResponse response) throws Exception {
    casesService.exportToPdf(casesEntity, response);
    return RestResponse.success();

}

entity层

@Data
@TableName("CASES")
public class CasesEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 
     */
    @TableId
    @ApiModelProperty(value = "编号", name = "id", example = "TP20230810001")
    private String id;
    /**
     * 类别
     */
    @ApiModelProperty(value = "类别", name = "category", example = "1")
    private String category;
    /**
     * 照片
     */
    @ApiModelProperty(value = "照片路径", name = "hostImage", example = "1")
    private String hostImage;
    /**
     * 建造时间
     */
    @ApiModelProperty(value = "建造时间", name = "buildTime", example = "1")
    private String buildTime;
    /**
     * 照片
     */
    @ApiModelProperty(value = "照片路径", name = "shipImage", example = "1")
    private String shipImage;
    /**
     * 吨位
     */
    @ApiModelProperty(value = "吨位", name = "tonnage", example = "1")
    private String tonnage;
    /**
     * 单位
     */
    @ApiModelProperty(value = "单位", name = "unit", example = "t/人")
    private String unit;
    /**
     * 删除标志,1表示删除
     */
    @TableLogic
    private String delFlag;
    /**
     *   创建人
     */
    @ApiModelProperty(value = "创建人", name = "createBy", example = "1")
    private String createBy;
    /**
     *   创建时间
     */
    @ApiModelProperty(value = "创建时间", name = "createDate", example = "1")
    private String createDate;
    /**
     *
     */
    @ApiModelProperty(value = "更新人", name = "updateBy", example = "1")
    private String updateBy;
    /**
     *
     */
    @ApiModelProperty(value = "更新时间", name = "updateDate", example = "1")
    private String updateDate;
}

service层

    void exportToPdf(CasesEntity casesEntity, HttpServletResponse response) throws IOException, DocumentException;

总结

效果不展示了,公司涉密内容
1、 字体记得修改,使用中文字体,否则中文乱码;
2、实体可能不匹配,我删了部分字段,没有去详细比对;
3、敲代码路漫漫,有点耐心就能成功。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值