使用itextpdf生成pdf

        因为工作需要,最近项目中有一个需求需要生成带有项目信息的pdf,并且pdf中还需要有附带项目信息的二维码方便用户扫码.
        做这个功能中踩了不少坑,写个博客提醒一下

springboot版本:2.6.7

1.引入itextpdf的pom文件

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.4.3</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>

2.引入pdfbox的pom文件

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>fontbox</artifactId>
    <version>2.0.1</version>
</dependency>
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.1</version>
</dependency>

3.生成二维码的pom文件

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.3</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.3</version>
</dependency>

        


具体代码实现:
1.准备两个实体类,写入文字的类和写入图片的类

图片类:ImagePro.java

@Data
public class ImagePro {
    //x 坐标
    private float x; 
    //y 坐标
    private float y; 
    //缩放百分比
    private float scalePercent;  
    //路径
    private String imgPath; 
}

文字类:PdfPro.java
 

@Data
public class PdfPro {
    private String text;  // 文本
    private float x; //x 坐标
    private float y; //y 坐标
}

工具类:PdfUtil.java

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Admin
 */
@Component
public class PdfUtil {

    @Value("${uploadFile.pdfLocation}")
    private String pdfLocation;

    @Value("${scheme.serverName}")
    private String serverName;

    @Value("${scheme.serverPort}")
    private String serverPort;

    //引入生成二维码工具类
    @Autowired
    private QrCodeUtil qrCodeUtil;

    /**
     * @param inputPDFFilePath  要写入的pdf文件路径
     * @param outPutPDFFilePath 输出的pdf文件路径
     * @param imagePros         要写入的图片的list,包含图片坐标等
     * @param pdfList           要写入的文字的list,包含坐标等
     * @throws Exception
     */
    public static void writeToPdf(String inputPDFFilePath, String outPutPDFFilePath, List<ImagePro> imagePros, List<PdfPro> pdfList)
            throws Exception {
        System.out.println(inputPDFFilePath);
        //append 追加
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(outPutPDFFilePath), false));
        PdfReader reader = new PdfReader(inputPDFFilePath);
        PdfStamper stamper = new PdfStamper(reader, bos);
        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        // BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        // "c:\\windows\\fonts\\SIMHEI.TTF" 使用windows系统的黑体
        //使用jar包自带的字体
        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        PdfGState gs = new PdfGState();
        for (int i = 1; i < total; i++) {
            //在内容下方加水印
            content = stamper.getUnderContent(i);
            gs.setFillOpacity(0.2f);
            content.beginText();
            //字体大小
            content.setFontAndSize(base, 12.5F);
            //内容居中,横纵坐标,偏移量
            for (PdfPro pdfPro : pdfList) {
                content.showTextAligned(Element.ALIGN_CENTER, pdfPro.getText(), pdfPro.getX(), pdfPro.getY(), 0);
            }
            for (ImagePro imagePro : imagePros) {
                //添加图片
                Image image = Image.getInstance(imagePro.getImgPath());
                //图片的位置(坐标)
                image.setAbsolutePosition(imagePro.getX(), imagePro.getY());
                // image of the absolute
                image.scaleToFit(200, 200);
                //依照比例缩放. 调整缩放,控制图片大小
                image.scalePercent(imagePro.getScalePercent());
                content.addImage(image);
            }
            content.setFontAndSize(base, 8);
            content.endText();
        }
        stamper.close();
        //关闭打开的原来PDF文件,不执行reader.close()删除不了(必须先执行stamper.close(),否则会报错)
        reader.close();
        //删除原来的PDF文件
        /*File targetTemplePDF = new File(inputPDFFilePath);
        targetTemplePDF.delete();*/
    }
  
}

生成二维码的工具类 QrCodeUtil.java
 

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Admin
 */
@Component
public class QrCodeUtil {

    @Value("${uploadFile.qrCodeLocation}")
    private String qrCodeLocation;

    @Value("${scheme.serverName}")
    private String serverName;


    public static void createQrCode(String url,String path,String fileName) {
        try {
            Map<EncodeHintType, String> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);
            File file = new File(path, fileName);
            if (file.exists() || ((file.getParentFile().exists() || file.getParentFile().mkdirs()) && file.createNewFile())) {
                writeToFile(bitMatrix, "jpg", file);
                System.out.println("二维码图片:" + file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
}

 注:在windows环境下测试不会产生中文字体不显示的问题,但是在linux环境下,如果系统没有安装中文字体则会出现写入pdf中中文内容丢失的问题.
解决该问题方案:
        1.使用jar包自带的中文字体,"STSong-Light"
        2.在linux下安装中文字体

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值