java pdfBox给PDF添加图片水印

package com.example.test.controller;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;

import java.io.File;
import java.io.IOException;
import java.util.Random;

public class pdfTest {

    static final String DEFAULT_FILENAME = "D:\\darcy\\a\\1.pdf"; // 源PDF
    static final String DEFAULT_FILENAME_TEMP = "D:\\darcy\\a\\copy.pdf"; // 生成新的PDF
    static final String DEFAULT_IMAGE = "D:\\darcy\\a\\1.jpg";  // 水印

    /**
     * PDF添加图片水印
     * */
    public static void main(String[] args) throws IOException {
        File file = new File(DEFAULT_FILENAME);
        PDDocument doc = Loader.loadPDF(file);

        // TODO 这里的数据 计算水印个数(900 150 700 150) 首个水印位置(-200至-100)都是实验得到 没有理论依据
        for (int top = 0; top < 700; top += 150) {
            int beginLeft = new Random().ints(-200, -50).limit(1).findFirst().getAsInt();
            for (int left = beginLeft; left < 700; left += 150) {
                for(int i=0; i<doc.getNumberOfPages(); i++){
                    PDPage page = doc.getPage(i);
                    PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true,true);
                    PDImageXObject pdImage = PDImageXObject.createFromFile(DEFAULT_IMAGE, doc);

                    PDExtendedGraphicsState pdExtGfxState = new PDExtendedGraphicsState();

                    // 设置透明度
                    pdExtGfxState.setNonStrokingAlphaConstant(0.5f);
                    pdExtGfxState.setAlphaSourceFlag(true);
                    pdExtGfxState.getCOSObject().setItem(COSName.BM, COSName.MULTIPLY);
                    contentStream.setGraphicsStateParameters(pdExtGfxState);

                    float width = 100;
                    float height = 100;
                    contentStream.drawImage(pdImage, left, top, width, height);
                    contentStream.close();
                    doc.save(DEFAULT_FILENAME_TEMP);
                }
            }
        }
        doc.close();
        

    }



}

 

 

pom.xml

        <!--pdf 添加水印-->
        <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>3.0.0-RC1</version>
        </dependency>

        <!--pdf 添加水印-->    

 

效果图:

 

 

posted @ 2021-07-29 15:52  ToDarcy  阅读(2089)  评论(0编辑  收藏  举报