Java使用itextpdf向PDF上添加图片

mtain 2021年08月09日 1,657次浏览

添加依赖

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.10</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.54</version>
        </dependency>

示例代码

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;

import java.io.*;


public class PdfAddImage {

    public void pageAddImage(){

        String pdfPath = "/tmp/test.pdf";
        String imagePath = "/tmp/qrcode.png";

        InputStream input = null;
        try {
            input = new FileInputStream(pdfPath);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {
            // 读取模板文件
            PdfReader reader = new PdfReader(input);
            System.out.println("总页数:" + reader.getNumberOfPages());
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdfPath));
            Document document = new Document();

            System.out.println("文档高度:" + document.getPageSize().getHeight());
            System.out.println("文档宽度:" + document.getPageSize().getWidth());

            float absolutePositionNewY =  document.getPageSize().getHeight() - 825;
            // X轴位置的值
            float absolutePositionNewX = 450;
            // 图片缩放的比例值
            float scalePercent = 15;

            // 提取pdf中的表单
            AcroFields form = stamper.getAcroFields();
            form.addSubstitutionFont(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED));

            // 根据地址读图片
            Image image = Image.getInstance(imagePath); // 读取图片地址
            image.setAbsolutePosition(absolutePositionNewX, absolutePositionNewY);// 图片位置
            image.scalePercent(scalePercent); // 图片缩放的比例

            // 获取pdf页码数
            int total = reader.getNumberOfPages();
            PdfContentByte content;

            //为每页 添加图片
            for(int i=1;i<=total;i++){
                content = stamper.getOverContent(i);
                content.addImage(image);
            }

            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        PdfAddImage pdfAddImage = new PdfAddImage();
        pdfAddImage.pageAddImage();
    }
}