使用 PDFBox 给 PDF 添加水印


使用 PDFBox 给 PDF 添加水印

PDF 加水印,使用 pdfbox 架包进行处理。

引入架包

<!--pdf加水印-->
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.23</version>
</dependency>

核心代码

public static MultipartFile setPDFMark(File file, String name) throws IOException {
    // 加载文件并设置样式
    PDDocument pdDocument = PDDocument.load(file);
    PDExtendedGraphicsState state = new PDExtendedGraphicsState();
    state.setNonStrokingAlphaConstant(0.1f);
    state.setAlphaSourceFlag(true);
    state.setBlendMode(BlendMode.MULTIPLY);

    // 处理每页的水印字体,透明度,大小
    for (int i = 0; i < pdDocument.getNumberOfPages(); i++) {
        PDPageContentStream stream = new PDPageContentStream(pdDocument, pdDocument.getPage(i), PDPageContentStream.AppendMode.APPEND, true, true);
        stream.setFont(PDType1Font.HELVETICA_BOLD, 8);
        stream.setNonStrokingColor(Color.BLACK);
        stream.setGraphicsStateParameters(state);
        stream.beginText();
        float pageHeight = pdDocument.getPage(i).getMediaBox().getHeight();
        float pageWidth = pdDocument.getPage(i).getMediaBox().getWidth();

        // 根据纸张大小添加水印,30度倾斜
        for (int h = 10; h < pageHeight; h = h + 150) {
            for (int w = -10; w < pageWidth; w = w + 150) {
                stream.setTextMatrix(Matrix.getRotateInstance(0.3, w, h));
                stream.showText("KK");
            }
        }
        stream.endText();
        stream.close();
    }

    /**
      * 转换对应的格式
     */
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    pdDocument.save(byteArrayOutputStream);
    pdDocument.close();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    return new MultipartFileUtils(name, name, "application/pdf", byteArrayInputStream);
}

文章作者: L Q
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 L Q !
  目录