SpringBoot实现 PDF 添加水印

方案一:使用 Apache PDFBox 库

①、依赖

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

②、添加水印

public class PdfoxWatermark{
	
	public static void main(String[] args)throws IOException{
		
		// 读取原始 PDF 文件
        PDDocument document = PDDocument.load(new File("original.pdf"));

        // 遍历 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 库

①、添加依赖

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

②、添加水印

public class ItextWatermark {
    public static void main(String[] args) throws IOException, DocumentException {
        // 读取原始 PDF 文件
        PdfReader reader = new PdfReader("original.pdf");
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf"));

        // 获取 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 命令行

用来创建、读取、修改和提取 PDF 内容。Ghostscript 中提供了命令行参数来添加水印。

①、需要在本地安装 Ghostscript 程序。

不同的系统,安装对应的安装包

②、添加水印

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

  • -sDEVICE=pdfwrite 表示输出为 PDF 文件;
  • -sOutputFile=output.pdf 表示输出文件名为 output.pdf;
  • 最后一个参数 original.pdf 则表示原始 PDF 文件的路径;中间的字符串则表示添加的水印内容。
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

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

方案四:Free Spire.PDF for Java

①、添加依赖

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

②、添加水印

public class FreeSpirePdfWatermark {
    public static void main(String[] args) {
        // 读取原始 PDF 文件
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("original.pdf");

        // 遍历 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);

            // 添加图片水印
            // PdfWatermark watermark = new PdfWatermark("watermark.png");
            // watermark.setOpacity(0.5f);
            // page.getWatermarks().add(watermark);
        }

        // 保存修改后的 PDF 文件
        pdf.saveToFile("output.pdf");
        pdf.close();
    }
}

方案五:Aspose.PDF for Java

①、依赖

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

②、添加水印

@RestController
@RequestMapping("/api/pdf")
public class PdfController {

    @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());
    }

    @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());
    }
}

两个 RESTful API:/addTextWatermark 和 /addImageWatermark,分别用于添加文本水印和图片水印。在请求中通过 file 参数传递 PDF 文件

  • 在 URL 地址栏中输入 http://localhost:8080/api/pdf/addTextWatermark
  • 在 Headers 标签页中设置 Content-Type 为 multipart/form-data
  • 在 Body 标签页中选择 form-data 类型,然后设置 key 为 file,value 选择本地的 PDF 文件。
  • 点击 Send 按钮发送请求,等待应答结果

处理结果将会在响应的 Body 中返回,也可以选择浏览器下载或保存到本地磁盘。

相关推荐

  1. SpringBoot实现PDF添加水印

    2024-03-11 07:16:02       48 阅读
  2. SpringBoot 实现 PDF 添加水印

    2024-03-11 07:16:02       56 阅读
  3. SpringBoot实现 PDF 添加水印

    2024-03-11 07:16:02       42 阅读
  4. Flying HTML生成PDF添加水印

    2024-03-11 07:16:02       66 阅读
  5. PDF下载添加水印和访问密码

    2024-03-11 07:16:02       49 阅读
  6. SpringBoot 实现 PDF 添加水印有哪些方案

    2024-03-11 07:16:02       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-11 07:16:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-11 07:16:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-11 07:16:02       87 阅读
  4. Python语言-面向对象

    2024-03-11 07:16:02       96 阅读

热门阅读

  1. N32L40x基于串口IAP实现(含升级工具)

    2024-03-11 07:16:02       47 阅读
  2. Go微服务: 基于Go Micro框架实现微服务调用

    2024-03-11 07:16:02       41 阅读
  3. ChatGPT 基本用法!ChatGPT4的prompt的使用例子!

    2024-03-11 07:16:02       65 阅读
  4. 四大组件的工作过程

    2024-03-11 07:16:02       35 阅读
  5. vim搜索和替换

    2024-03-11 07:16:02       49 阅读
  6. Haproxy

    Haproxy

    2024-03-11 07:16:02      31 阅读