导出文件:使用itext导出数据为PDF并添加文字与图片水印

简介: 导出文件:使用itext导出数据为PDF并添加文字与图片水印

背景


日常工作中,曾遇到过导出数据为 PDF 的需求,这里做个简单总结。当前业务共涉及到四个实体类,后台将不同实体的数据组装后导出为 PDF 文件。


  • 领域模型


  1. StdCommittee
  2. StdCommitteeBranch
  3. StdCommitteeSecretariat
  4. StdCommitteeSecretariatStaff
  • 实体关系

image.png

  • 涉及技术


SpringBootMyBatisPlusitextpdfConfigProperties 自定义配置。


  • 导出接口
/**
 * @Author Heartsuit
 * @Date 2022-01-02
 */
@RestController
@RequestMapping("committee")
public class StdCommitteeController {
    @Autowired
    private IStdCommitteeService stdCommitteeService;
    /**
     * 导出申报书
     */
    @GetMapping("/download/{id}")
    public void downloadPdf(@PathVariable Long id, HttpServletResponse response)
    {
        StdCommittee stdCommittee = stdCommitteeService.getById(id);
        OutputStream outputStream = null;
        try {
            outputStream = new BufferedOutputStream(response.getOutputStream());
            //生成pdf文件
            stdCommitteeService.generatePdf(stdCommittee, outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


导出数据为PDF


  • 配置文件
server:
  port: 8080
# spring配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/standard-core?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
    username: root
    password: root
# mybatisplus配置
mybatis-plus:
  # 搜索指定包别名
  typeAliasesPackage: com.heartsuit.domain
  # 配置mapper的扫描,找到所有的mapper.xml映射文件
  mapper-locations: classpath:mapper/**/*.xml
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  • 核心服务
/**
 * @Author Heartsuit
 * @Date 2022-01-02
 */
@Service
public class StdCommitteeServiceImpl extends ServiceImpl<StdCommitteeMapper, StdCommittee> implements IStdCommitteeService {
    @Autowired
    private IStdCommitteeSecretariatService stdCommitteeSecretariatService;
    @Autowired
    private IStdCommitteeSecretariatStaffService stdCommitteeSecretariatStaffService;
    @Autowired
    private IStdCommitteeBranchService stdCommitteeBranchService;
    private void buildCommittee(StdCommittee stdCommittee) {
        // one 2 one
        StdCommitteeSecretariat stdCommitteeSecretariat = stdCommitteeSecretariatService.getOne(new QueryWrapper<StdCommitteeSecretariat>()
                .lambda().eq(StdCommitteeSecretariat::getCommitteeId, stdCommittee.getId()));
        // one 2 many
        List<StdCommitteeSecretariatStaff> staffs = stdCommitteeSecretariatStaffService.list(new QueryWrapper<StdCommitteeSecretariatStaff>()
                .lambda().eq(StdCommitteeSecretariatStaff::getCommitteeSecretariatId, stdCommitteeSecretariat.getId()));
        stdCommitteeSecretariat.setStdCommitteeSecretariatStaffs(staffs);
        stdCommittee.setStdCommitteeSecretariat(stdCommitteeSecretariat);
        // one 2 many
        List<StdCommitteeBranch> branches = stdCommitteeBranchService.list(new QueryWrapper<StdCommitteeBranch>()
                .lambda().eq(StdCommitteeBranch::getCommitteeId, stdCommittee.getId()));
        stdCommittee.setStdCommitteeBranches(branches);
    }
    @Override
    public void generatePdf(StdCommittee stdCommittee, OutputStream outputStream) {
        buildCommittee(stdCommittee);
        Document document = new Document();
        try {
            PdfWriter.getInstance(document, outputStream);
            document.open();
            // 解决中文不显示问题
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            // 标题加粗
            Font fontChina18 = new Font(bfChinese, PDFConstant.FONT_SIZE_18, Font.BOLD);
            Font fontChina15 = new Font(bfChinese, PDFConstant.FONT_SIZE_15, Font.BOLD);
            Font fontChina10 = new Font(bfChinese, PDFConstant.FONT_SIZE_10);
            // 获取pdf头文件信息
            Map<String, String> headInfo = new HashMap<>();
            headInfo.put("firstHeadInfo", "标准化技术委员会登记表");
            // 空格
            Paragraph blank1 = new Paragraph(" ", new Font(bfChinese, PDFConstant.FONT_SIZE_5));
            Paragraph firstTitle = new Paragraph(headInfo.get("firstHeadInfo"), fontChina18);
            firstTitle.setAlignment(Element.ALIGN_CENTER);// 居中
            document.add(firstTitle);
            // 添加空格
            document.add(blank1);
            // 3 创建表格
            PdfPTable table = new PdfPTable(PDFConstant.TABLE_COLUMN_NUMBER_8);// 表格总共几列
            table.setWidthPercentage(PDFConstant.TABLE_WIDTH_PERCENTAGE);// 表格宽度为100%
            PdfUtil.addTableCell(table, "名称", fontChina10, false, false, 0, 0);
            PdfUtil.addTableCell(table, stdCommittee.getName(), fontChina10, true, false, 3, 0);//跨三列
            PdfUtil.addTableCell(table, "编号", fontChina10, false, false, 0, 0);
            PdfUtil.addTableCell(table, stdCommittee.getCode(), fontChina10, true, false, 3, 0);//跨三列
            PdfUtil.addTableCell(table, "本届是第几届", fontChina10, false, false, 0, 0);
            PdfUtil.addTableCell(table, stdCommittee.getNumberSession().toString(), fontChina10, true, false, 3, 0);//跨三列
            PdfUtil.addTableCell(table, "本届成立时间", fontChina10, false, false, 0, 0);
            PdfUtil.addTableCell(table, DateFormatUtils.format(stdCommittee.getEstablishDate(), "yyyy-MM-dd"), fontChina10, true, false, 3, 0);//跨三列
            PdfUtil.addTableCell(table, "负责制修订地方标准的专业领域", fontChina10, false, true, 0, 3); //跨三行
            PdfUtil.addTableCell(table, stdCommittee.getProfessionalField(), fontChina10, true, true, 7, 3);//跨七列
            List<StdCommitteeSecretariatStaff> staffs = stdCommittee.getStdCommitteeSecretariat().getStdCommitteeSecretariatStaffs();
            PdfUtil.addTableCell(table, "技术委员会秘书处工作人员", fontChina10, false, true, 0, staffs.size() + 1);
            PdfUtil.addTableCell(table, "姓名", fontChina10, true, false, 0, 0);
            PdfUtil.addTableCell(table, "秘书类型", fontChina10, true, false, 0, 0);
            PdfUtil.addTableCell(table, "职务/职称", fontChina10, true, false, 0, 0);
            PdfUtil.addTableCell(table, "出生年月", fontChina10, true, false, 0, 0);
            PdfUtil.addTableCell(table, "学历", fontChina10, true, false, 0, 0);
            PdfUtil.addTableCell(table, "电话", fontChina10, true, false, 2, 0);
            staffs.forEach(staff -> {
                PdfUtil.addTableCell(table, staff.getName(), fontChina10, true, false, 0, 0);
                PdfUtil.addTableCell(table, staff.getType(), fontChina10, true, false, 0, 0);
                PdfUtil.addTableCell(table, staff.getProfessionalTitle(), fontChina10, true, false, 0, 0);
                PdfUtil.addTableCell(table, DateFormatUtils.format(staff.getBirthday(), "yyyy-MM-dd"), fontChina10, true, false, 0, 0);
                PdfUtil.addTableCell(table, staff.getQualification(), fontChina10, true, false, 0, 0);
                PdfUtil.addTableCell(table, staff.getPhone(), fontChina10, true, false, 2, 0);
            });
            PdfUtil.addTableCell(table, "技术委员会下设分技术委员会或标准化技术专家组", fontChina15, true, false, 8, 0);//跨8列
            PdfUtil.addTableCell(table, "id", fontChina10, true, false, 2, 0);
            PdfUtil.addTableCell(table, "编号", fontChina10, true, false, 2, 0);
            PdfUtil.addTableCell(table, "名称", fontChina10, true, false, 2, 0);
            PdfUtil.addTableCell(table, "委员数", fontChina10, true, false, 2, 0);
            stdCommittee.getStdCommitteeBranches().forEach(branch -> {
                PdfUtil.addTableCell(table, branch.getId().toString(), fontChina10, true, false, 2, 0);
                PdfUtil.addTableCell(table, branch.getCode(), fontChina10, true, false, 2, 0);
                PdfUtil.addTableCell(table, branch.getName(), fontChina10, true, false, 2, 0);
                PdfUtil.addTableCell(table, branch.getNumberMember().toString(), fontChina10, true, false, 2, 0);
            });
            document.add(table);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}
  • 导出效果


直接浏览器访问: http://localhost:8080/committee/download/1477482360448090113

image.png

或者在 PostMan 中访问: http://localhost:8080/committee/download/1477482360448090113 ,不过需要保存为文件后再查看生成的PDF文件内容。

image.png


添加文字水印


  • 配置文件


为了方便控制是否启用文字水印,我在原配置中添加了以下自定义配置(实际生产中一般与配置中心配合使用,实现动态控制开关):

pdf:
  watermark:
    text:
      enabled: true
      content: 'Heartsuit文字水印666'
  • 配置类
/**
 * @Author Heartsuit
 * @Date 2022-01-02
 */
@Configuration
@ConfigurationProperties(prefix = "pdf.watermark")
@Data
public class PdfConfigProperties
{
    private TextProperties text = new TextProperties();
    @Data
    public static class TextProperties{
        private Boolean enabled;
        private String content;
    }
}
  • 核心服务类
public class TextWaterMark extends PdfPageEventHelper {
    private String waterMarkText;
    public TextWaterMark(String waterMarkText) {
        this.waterMarkText = waterMarkText;
    }
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            float pageWidth = document.right() + document.left();//获取pdf内容正文页面宽度
            float pageHeight = document.top() + document.bottom();//获取pdf内容正文页面高度
            //设置水印字体格式
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font waterMarkFont = new Font(base, 20, Font.BOLD, BaseColor.LIGHT_GRAY);
            PdfContentByte waterMarkPdfContent = writer.getDirectContentUnder();
            Phrase phrase = new Phrase(waterMarkText, waterMarkFont);
            //两行三列
            ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
                    pageWidth * 0.25f, pageHeight * 0.2f, 45);
            ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
                    pageWidth * 0.25f, pageHeight * 0.5f, 45);
            ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
                    pageWidth * 0.25f, pageHeight * 0.8f, 45);
            ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
                    pageWidth * 0.65f, pageHeight * 0.2f, 45);
            ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
                    pageWidth * 0.65f, pageHeight * 0.5f, 45);
            ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
                    pageWidth * 0.65f, pageHeight * 0.8f, 45);
        } catch (DocumentException | IOException de) {
            de.printStackTrace();
        }
    }
}
  • 导出PDF代码需修改的部分

image.png

  • 导出效果

只有一页时,导出的PDF文件效果:

image.png

当有多页时,导出的PDF文件效果:

image.png


添加图片水印


  • 配置文件


为了方便控制是否启用图片水印,我在原配置中添加了以下自定义配置(实际生产中一般与配置中心配合使用,实现动态控制开关): 另外,图片文件我直接放到了 resources 根目录下,然后代码中通过 Resource 类读取到路径,传递给生产带图片水印的核心服务层方法。

pdf:
  watermark:
    text:
      enabled: false
      content: 'Heartsuit文字水印666'
    image:
      enabled: true
      file: 'avatar.jpg'
  • 核心服务类
public class ImageWaterMark extends PdfPageEventHelper {
    private String waterMarkFullFilePath;
    private Image waterMarkImage;
    public ImageWaterMark(String waterMarkFullFilePath) {
        this.waterMarkFullFilePath = waterMarkFullFilePath;
    }
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            float pageWidth = document.right() + document.left();//获取pdf内容正文页面宽度
            float pageHeight = document.top() + document.bottom();//获取pdf内容正文页面高度
            PdfContentByte waterMarkPdfContent = writer.getDirectContentUnder();
            //仅设置一个图片实例对象,整个PDF文档只应用一个图片对象,极大减少因为增加图片水印导致PDF文档大小增加
            if (waterMarkImage == null) {
                waterMarkImage = Image.getInstance(waterMarkFullFilePath);
            }
            //添加水印图片,三行两列
            waterMarkPdfContent.addImage(getSingletonWaterMarkImage(waterMarkImage, pageWidth * 0.2f, pageHeight * 0.1f));
            waterMarkPdfContent.addImage(getSingletonWaterMarkImage(waterMarkImage, pageWidth * 0.2f, pageHeight * 0.4f));
            waterMarkPdfContent.addImage(getSingletonWaterMarkImage(waterMarkImage, pageWidth * 0.2f, pageHeight * 0.7f));
            waterMarkPdfContent.addImage(getSingletonWaterMarkImage(waterMarkImage, pageWidth * 0.6f, pageHeight * 0.2f));
            waterMarkPdfContent.addImage(getSingletonWaterMarkImage(waterMarkImage, pageWidth * 0.6f, pageHeight * 0.5f));
            waterMarkPdfContent.addImage(getSingletonWaterMarkImage(waterMarkImage, pageWidth * 0.6f, pageHeight * 0.8f));
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);//设置透明度
            waterMarkPdfContent.setGState(gs);
        } catch (DocumentException | IOException de) {
            de.printStackTrace();
        }
    }
    /**
     * 对一个图片对象设置展示位置等信息,该对象重复利用,减少PDF文件大小
     *
     * @param waterMarkImage
     * @param xPosition
     * @param yPosition
     * @return
     */
    private Image getSingletonWaterMarkImage(Image waterMarkImage, float xPosition, float yPosition) {
        waterMarkImage.setAbsolutePosition(xPosition, yPosition);//坐标
        waterMarkImage.setRotation(-20);//旋转 弧度
        waterMarkImage.setRotationDegrees(-45);//旋转 角度
        waterMarkImage.scalePercent(100);//依照比例缩放
        return waterMarkImage;
    }
}
  • 导出PDF代码需修改的部分

image.png

  • 导出效果

image.png



目录
相关文章
|
2月前
|
人工智能 搜索推荐 算法
PDF 转 JPG 图片小工具:CodeBuddy 助力解决转换痛点
在 PDF 转 JPG 的实际应用中,用户普遍面临转换质量差、批量处理效率低、格式兼容性不足以及编程实现困难等痛点。而 CodeBuddy 凭借智能代码生成与优化、实时错误诊断修复、助力代码学习拓展,以及支持多场景适配与个性化定制等强大的 AI 编程能力,精准直击这些难题。使用 CodeBuddy 开发 Python PDF 转 JPG 小工具,能够有效提升转换效率与质量,降低开发门槛和成本,为用户带来高效、优质的文件格式转换体验。
88 16
|
3月前
|
文字识别 BI
【工具教程】批量PDF和图片OCR识别指定区域文字自动改图片名字,多个区域一次性批量识别改名批量重命名
本内容介绍了一款用于企业档案、医院病历及办公文件管理的图片和PDF文字识别工具。通过框选识别区域,软件可批量提取关键信息,实现文件重命名或导出为表格,极大提升管理效率。支持图片与PDF两种模式,操作简单,适用于合同、病历、报告等场景。提供详细步骤指导,包含区域设置、文件导入、批量处理及结果校验等功能。
309 8
|
4月前
|
人工智能 文字识别 自然语言处理
1.6K star!这个开源文本提取神器,5分钟搞定PDF/图片/Office文档!
Kreuzberg 是一个基于 Python 的文本提取库,支持从 PDF、图像、Office 文档等 20+ 格式中提取文本内容。采用 MIT 开源协议,具备本地处理、异步架构、智能 OCR 等特性,特别适合需要隐私保护的文档处理场景。
189 1
|
4月前
|
文字识别 UED Python
对双栏 | 单双栏混合 | 图表文字混合的复杂布局的图片OCR识别(对布局复杂的整个pdf进行OCR识别)
这个故事告诉我们要多尝试不同的库和引擎,尤其是需求比较偏门或者少见的时候。同一个方向不同的库所擅长的领域是不一样的。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
3月前
|
存储 JSON API
如何将 Swagger 文档导出为 PDF 文件
你会发现自己可能需要将 Swagger 文档导出为 PDF 或文件,以便于共享和存档。在这篇博文中,我们将指导你完成将 Swagger 文档导出为 PDF 格式的过程。
|
2月前
|
人工智能 算法 安全
使用CodeBuddy实现批量转换PPT、Excel、Word为PDF文件工具
通过 CodeBuddy 实现本地批量转换工具,让复杂的文档处理需求转化为 “需求描述→代码生成→一键运行” 的极简流程,真正实现 “技术为效率服务” 的目标。感兴趣的快来体验下把
93 10
|
5月前
|
人工智能 编解码 文字识别
OCRmyPDF:16.5K Star!快速将 PDF 文件转换为可搜索、可复制的文档的命令行工具
OCRmyPDF 是一款开源命令行工具,专为将扫描的 PDF 文件转换为可搜索、可复制的文档。支持多语言、图像优化和多核处理。
675 17
OCRmyPDF:16.5K Star!快速将 PDF 文件转换为可搜索、可复制的文档的命令行工具
|
5月前
|
文字识别 Serverless 开发工具
【全自动改PDF名】批量OCR识别提取PDF自定义指定区域内容保存到 Excel 以及根据PDF文件内容的标题来批量重命名
学校和教育机构常需处理成绩单、报名表等PDF文件。通过OCR技术,可自动提取学生信息并录入Excel,便于统计分析和存档管理。本文介绍使用阿里云服务实现批量OCR识别、内容提取、重命名及导出表格的完整步骤,包括开通相关服务、编写代码、部署函数计算和设置自动化触发器等。提供Python示例代码和详细操作指南,帮助用户高效处理PDF文件。 链接: - 百度网盘:[链接](https://pan.baidu.com/s/1mWsg7mDZq2pZ8xdKzdn5Hg?pwd=8866) - 腾讯网盘:[链接](https://share.weiyun.com/a77jklXK)
472 5
|
6月前
|
机器学习/深度学习 人工智能 文字识别
Zerox:AI驱动的万能OCR工具,精准识别复杂布局并输出Markdown格式,支持PDF、DOCX、图片等多种文件格式
Zerox 是一款开源的本地化高精度OCR工具,基于GPT-4o-mini模型,支持PDF、DOCX、图片等多种格式文件,能够零样本识别复杂布局文档,输出Markdown格式结果。
509 4
Zerox:AI驱动的万能OCR工具,精准识别复杂布局并输出Markdown格式,支持PDF、DOCX、图片等多种文件格式
|
5月前
|
文字识别 BI
【图片型PDF】批量识别扫描件PDF指定区域局部位置内容,将识别内容导出Excel表格或批量改名文件,基于阿里云OCR对图片型PDF识别改名案例实现
在医疗和政务等领域,图片型PDF文件(如病历、报告、公文扫描件)的处理需求广泛。通过OCR技术识别这些文件中的文字信息,提取关键内容并保存为表格,极大提高了信息管理和利用效率。本文介绍一款工具——咕嘎批量OCR系统,帮助用户快速处理图片型PDF文件,支持区域识别、内容提取、导出表格及批量改名等功能。下载工具后,按步骤选择处理模式、进行区域采样、批量处理文件,几分钟内即可高效完成数百个文件的处理。
534 8