PDF操作

//根据坐标位置写入操作

    public static void main(String[] args) throws Exception {
        String input = "pdf";//放入pdf文件
        PdfReader pr = new PdfReader(input);//创建pdf读取
        PdfDocument pd = new PdfDocument(pr, new PdfWriter("pdf"));//创建另存为pdf
        Document document = new Document(pd);
        List<PdfWords> words = new ArrayList<>();
        words.add(new PdfWords(40l, 450l, "123555555555555555555555555555555555"));
        words.add(new PdfWords(50l, 436l, "fffmmmmmmmmmmmmmmmmmmm"));
        words.add(new PdfWords(30l, 420l, "√"));
        addLocationWords(document, words, 1);
        document.close();
        pr.close();
        pd.close();
    }

    //在对应位置写入文字
    public static void addLocationWords(Document document, List<PdfWords> words, int pageNum) throws IOException {
        PdfFont font = PdfFontFactory.createFont("Font/simhei.ttf", PdfEncodings.IDENTITY_H);
        for (PdfWords word : words) {
            Text text = new Text(word.getText());
            document.add(new Paragraph(text).setFixedPosition(pageNum, word.getX(), word.getY(), word.getWidth()).setFont(font).setFontSize(word.getFontSize()));
        }
    }

//创建字实体类
package com.ruoyi.icfms.domain.vo;
import lombok.Data;
@Data
public class PdfWords {
    private String text;  // 文本
    private float x; //x 坐标
    private float y; //y 坐标
    private float width; //宽
    private float fontSize; //字号

    public PdfWords(float x, float y, String text) {
        this.text = text;
        this.x = x;
        this.y = y;
        this.width = 100;
        this.fontSize = 11;
    }
    public PdfWords(float x, float y, String text, float width) {
        this.text = text;
        this.x = x;
        this.y = y;
        this.width = width;
        this.fontSize = 11;
    }
    public PdfWords(float x, float y, String text, float width, float fontSize) {
        this.text = text;
        this.x = x;
        this.y = y;
        this.width = width;
        this.fontSize = fontSize;
    }
}

posted @ 2024-09-13 09:14  IxXi  阅读(34)  评论(0)    收藏  举报