首页 > 其他分享 >SpringBoot 实现 PDF 添加水印

SpringBoot 实现 PDF 添加水印

时间:2024-10-24 22:58:32浏览次数:1  
标签:文件 SpringBoot 水印 添加 new PDF pdf

方式一:使用 Apache PDFBox 库

1. 添加 PDFBox 依赖

首先,在 pom.xml 文件中添加 PDFBox 的依赖:

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>


2. 添加水印

在添加水印之前,需要读取原始 PDF 文件:

PDDocument document = PDDocument.load(new File("original.pdf"));
然后,遍历 PDF 中的所有页面,并使用 PDPageContentStream 添加水印:
// 遍历 PDF 中的所有页面
for (int i = 0; i < document.getNumberOfPages(); i++) {
    PDPage page = document.getPage(i);
    PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);

    // 设置字体和字号
    contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36);

    // 设置透明度
    contentStream.setNonStrokingColor(200, 200, 200);

    // 添加文本水印
    contentStream.beginText();
    contentStream.newLineAtOffset(100, 100); // 设置水印位置
    contentStream.showText("Watermark"); // 设置水印内容
    contentStream.endText();

    contentStream.close();
}

最后,需要保存修改后的 PDF 文件:

document.save(new File("output.pdf"));
document.close();

方式二:使用 iText 库

1. 添加 iText 依赖

在 pom.xml 文件中添加 iText 的依赖:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

2. 添加水印

在添加水印之前,需要读取原始 PDF 文件:

PdfReader reader = new PdfReader("original.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf"));

然后,遍历 PDF 中的所有页面,并使用 PdfContentByte 添加水印:

// 获取 PDF 中的页数
int pageCount = reader.getNumberOfPages();

// 添加水印
for (int i = 1; i <= pageCount; i++) {
    PdfContentByte contentByte = stamper.getUnderContent(i); // 或者 getOverContent()
    contentByte.beginText();
    contentByte.setFontAndSize(BaseFont.createFont(), 36f);
    contentByte.setColorFill(BaseColor.LIGHT_GRAY);
    contentByte.showTextAligned(Element.ALIGN_CENTER, "Watermark", 300, 400, 45);
    contentByte.endText();
}

最后,需要保存修改后的 PDF 文件并关闭文件流:

stamper.close();
reader.close();





方式三:用 Ghostscript 命令行

1. Ghostscript

首先需要在本地安装 Ghostscript 程序。

Windows: https://www.ghostscript.com/download/gsdnld.html

macOS: https://www.ghostscript.com/download/gsdnld.html

Linux: https://www.ghostscript.com/download/gsdnld.html

2. 添加水印


可以在终端中使用 Ghostscript 的命令行工具执行以下命令来实现:


gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=output.pdf -c "newpath /Helvetica-Bold findfont 36 scalefont setfont 0.5 setgray 200 200 moveto (Watermark) show showpage" original.pdf

上述命令中,-sDEVICE=pdfwrite 表示输出为 PDF 文件;-sOutputFile=output.pdf 表示输出文件名为 output.pdf;最后一个参数 original.pdf 则表示原始 PDF 文件的路径;中间的字符串则表示添加的水印内容。


3. 注意事项


使用 Ghostscript 命令行添加水印时,会直接修改原始 PDF 文件,因此建议先备份原始文件。


方式四:Free Spire.PDF for Java


下面介绍一下使用 Free Spire.PDF for Java 实现 PDF 添加水印的方式。


1. 添加 Free Spire.PDF for Java 依赖


首先,在 pom.xml 文件中添加 Free Spire.PDF for Java 的依赖:


<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>free-spire-pdf-for-java</artifactId>
    <version>1.9.6</version>
</dependency>

2. 添加水印


2.1 添加文本水印

在添加水印之前,需要读取原始 PDF 文件:


PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("original.pdf");

然后,遍历 PDF 中的所有页面,并使用 PdfPageBase 添加水印:


// 遍历 PDF 中的所有页面
for (int i = 0; i < pdf.getPages().getCount(); i++) {
    PdfPageBase page = pdf.getPages().get(i);

    // 添加文本水印
    PdfWatermark watermark = new PdfWatermark("Watermark");
    watermark.setFont(new PdfFont(PdfFontFamily.Helvetica, 36));
    watermark.setOpacity(0.5f);
    page.getWatermarks().add(watermark);
}

最后,需要保存修改后的 PDF 文件:


pdf.saveToFile("output.pdf");
pdf.close();

2.2 添加图片水印

添加图片水印与添加文本水印类似,只需要将 PdfWatermark 的参数修改为图片路径即可。


// 添加图片水印
PdfWatermark watermark = new PdfWatermark("watermark.png");
watermark.setOpacity(0.5f);
page.getWatermarks().add(watermark);
方式五:Aspose.PDF for Java

在 pom.xml 文件中添加 Aspose.PDF for Java 的依赖:

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-pdf</artifactId>
    <version>21.4</version>
</dependency>

1. 添加文本水印

@PostMapping("/addTextWatermark")
public ResponseEntity<byte[]> addTextWatermark(@RequestParam("file") MultipartFile file) throws IOException {
    // 加载 PDF 文件
    Document pdfDocument = new Document(file.getInputStream());
    TextStamp textStamp = new TextStamp("Watermark");
    textStamp.setWordWrap(true);
    textStamp.setVerticalAlignment(VerticalAlignment.Center);
    textStamp.setHorizontalAlignment(HorizontalAlignment.Center);
    pdfDocument.getPages().get_Item(1).addStamp(textStamp);

    // 保存 PDF 文件
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    pdfDocument.save(outputStream);
    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"watermarked.pdf\"")
            .contentType(MediaType.APPLICATION_PDF)
            .body(outputStream.toByteArray());
}

2. 添加图片水印

@PostMapping("/addImageWatermark")
public ResponseEntity<byte[]> addImageWatermark(@RequestParam("file") MultipartFile file) throws IOException {
    // 加载 PDF 文件
    Document pdfDocument = new Document(file.getInputStream());
    ImageStamp imageStamp = new ImageStamp("watermark.png");
    imageStamp.setWidth(100);
    imageStamp.setHeight(100);
    imageStamp.setVerticalAlignment(VerticalAlignment.Center);
    imageStamp.setHorizontalAlignment(HorizontalAlignment.Center);
    pdfDocument.getPages().get_Item(1).addStamp(imageStamp);

    // 保存 PDF 文件
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    pdfDocument.save(outputStream);
    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"watermarked.pdf\"")
            .contentType(MediaType.APPLICATION_PDF)
            .body(outputStream.toByteArray());
}
 

标签:文件,SpringBoot,水印,添加,new,PDF,pdf
From: https://www.cnblogs.com/KL2016/p/18501541

相关文章

  • 基于SpringBoot+Vue+uniapp的乡村政务办公系统的详细设计和实现(源码+lw+部署文档+讲
    文章目录前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus系统测试系统测试目的系统功能测试系统测试结论为什么选择我代码参考数据库参考源码获取前言......
  • SpringBootStart 组件
    如何实现一个springboot-start组件Person:如何实现一个springbootstart组件ChatGPT:SpringBootStarter是SpringBoot提供的一种机制,用于简化依赖的配置和集成。一个SpringBootStarter通常包含了一组相关的依赖、配置、自动配置和其他需要的资源。通过创建自定......
  • 基于SpringBoot+Vue的校园助学金与三评申报审核系统的设计与实现
    作者简介:Java领域优质创作者、CSDN博客专家、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、多年校企合作经验,被多个学校常年聘为校外企业导师,指导学生毕业设计并参与学生毕业答辩指导,有较为丰富的相关经验。期待与各位高校教师、企业......
  • 日语学习《红宝书新日本语能力考试N1·N2·N3·N4·N5文字词汇(详解+练习)》PDF分享
    ​​《红宝书:新日本语能力考试文字词汇(详解+练习)》系列丛书自出版以来,广受好评,成为很多参加能力考试的学习者的必备用书。《红宝书:新日本语能力考试文字词汇(详解+练习)》按新日语能力考试指南和新真题编写,收录词汇量达6300多个:涵盖必须掌握的重点词汇3324个,涵盖重要补充词汇300......
  • node根据模板生成pdf,并在pdf中插入文本信息,水印,签章。
    要求通过node生成司机小程序需要的pdf,并在pdf插入信息,用户签章,公司签章,水印等。第三方插件#pdf-lib版本1.17.1。读取pdf模板,插入信息,签章,水印。#@pdf-lib/fontkit版本1.1.1。加载pdf插入信息时所需的字体文件ttf。#canvas版本2.11.2。根据用户名形成用户签章(文字......
  • SpringBoot学习笔记(3)
    一.ORM基本介绍         1.  ORM(ObjectRelationalMapping,对象关系映射)是为了解决面向对象与关系数据库存在的互不匹配现象的一种技术。ORM通过使用描述对象和数据库之间映射的元数据讲程序中的对象自动持久化到关系数据库中,即ORM能帮助我们完成对象到数据库表......
  • save download pdf
    packagecn.didisos.sos.fams.controller;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.impl.client.CloseableHttpClient;importorg......
  • SpringBoot集成Jedis
    SpringBoot集成JedisJedis/Redis/JDK版本关系JedisversionSupportedRedisversionsJDKCompatibility3.9+5.0to6.2Familyofreleases8,11>=4.0Version5.0to7.2Familyofreleases8,11,17>=5.0Version6.0tocurrent8,11,17,21&......
  • springboot-实现excle文件导出的单元格相同内容合并
    导出excle文件中的单元格有些需要合并如何操作例如:左边的表格想合并单元格成右边的表格更加便于观看        一、依赖文件<!--excle操作--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId>......
  • SpringBoot入门到精通(十三)日志:别小看它,否则吃亏的是自己!学会你也可以设计架构
    别小看他,当你面对的时候,就会知道,多么痛的领悟!如何在SpringBoot中使用Logback记录详细的日志?整合LogBack,Log4J...等,是不是很多方法!但需要注意,我讲的可能和你是一样的,但也是不一样的。常见日志级别:高---低排列TRACE:描述:最详细的日志级别,通常用于开发和调试阶段......