zl程序教程

您现在的位置是:首页 >  其它

当前栏目

ITextPDF7

2023-06-13 09:12:08 时间

大家好,又见面了,我是你们的朋友全栈君。

ITextPDF

前言

版本说明

itext7-core=7.1.13

相关链接:

核心pom依赖

<!-- https://mvnrepository.com/artifact/com.itextpdf/itext7-core -->
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>itext7-core</artifactId>
  <version>7.1.13</version>
  <type>pom</type>
</dependency>

入门示例

package top.simba1949;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;

import java.io.File;
import java.io.FileNotFoundException;

/** * @author Anthony * @date 2020/12/8 10:03 */
public class Application { 
   

    public static final String FILE_PATH = "D:\\IDE\\IDEA\\workspace\\learn\\test-spring-boot\\itextpdf-learn\\PDF.pdf";

    public static void main(String[] args) throws FileNotFoundException { 
   
        // 创建一个要生成的PDF文件对象File
        File file = new File(FILE_PATH);
        // 创建PDF输出流
        PdfWriter pdfWriter = new PdfWriter(file);
        // 创建文档对象
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);

        // 8 表示一行多少列
        Table table = new Table(UnitValue.createPercentArray(8)).useAllAvailableWidth();

        for (int i = 0; i < 16; i++) { 
   
            table.addCell("hi" + i);

        }
        document.add(table);

        // 关闭文档
        document.close();
    }
}

添加表格

package top.simba1949;

import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.xobject.PdfImageXObject;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.BackgroundImage;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;

import java.io.File;
import java.io.IOException;

/** * @author Anthony * @date 2020/12/9 19:10 */
public class ColoredBackground { 
   

    public static final String FILE_PATH = "D:\\IDE\\IDEA\\workspace\\learn\\test-spring-boot\\itextpdf-learn\\PDF.pdf";
    public static final String IMG_PATH = "itextpdf-learn/src/main/resources/static/image-0.jpg";

    public static void main(String[] args) throws IOException { 
   
        // 创建一个要生成的PDF文件对象File
        File file = new File(FILE_PATH);
        // 创建PDF输出流
        PdfWriter pdfWriter = new PdfWriter(file);
        // 创建文档对象
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);

        // 创建字体
        PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
        // 创建背景图片
        ImageData imageData = ImageDataFactory.create(IMG_PATH);
        PdfImageXObject pdfImageXObject = new PdfImageXObject(imageData);
        BackgroundImage.Builder backgroundImageBuilder = new BackgroundImage.Builder();
        backgroundImageBuilder.setImage(pdfImageXObject);
        BackgroundImage backgroundImage = backgroundImageBuilder.build();
        // 创建table
        Table table = new Table(UnitValue.createPercentArray(8)).useAllAvailableWidth();

        for (int i = 0; i < 16; i++) { 
   
            Cell cell = new Cell();
            // 设置段落,设置段落的字体和字体颜色
            Paragraph paragraph = new Paragraph("hi" + i).setFont(font).setFontColor(ColorConstants.WHITE);
            cell.add(paragraph);
            // 设置背景颜色
            // cell.setBackgroundColor(ColorConstants.RED);
            // 设置边框样式
            SolidBorder solidBorder = new SolidBorder(ColorConstants.BLACK, 1);
            cell.setBorder(solidBorder);
            // 设置文本对齐方式
            cell.setTextAlignment(TextAlignment.CENTER);
            table.addCell(cell);
        }
        // 设置表格背景图片
        table.setBackgroundImage(backgroundImage);
        // 添加表格
        document.add(table);
        document.close();
    }
}

document对象

document 元素只能添加 AreaBreakImage 对象和 IBlockElement 接口的实现类对象 IBlockElement 的实现类如下图:

进阶PDF

package top.simba1949;

import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;

import java.io.File;
import java.io.IOException;

/** * @author anthony * @date 2021/1/26 23:12 */
public class Application { 
   
    public static void main(String[] args) throws IOException { 
   
        // 文件名
        String fileName = getPdfFileName();
        // 文件对象
        File file = new File(fileName);

        // pdf 输出流
        PdfWriter pdfWriter = new PdfWriter(file);
        // 处理 pdf 的主入口点
        PdfDocument pdfDoc = new PdfDocument(pdfWriter);
        // 设置pdf的页面大小
        PageSize pageSize = new PageSize(PageSize.A4);
        // 文档对象,用于添加文档中的各种元素
        Document document = new Document(pdfDoc, pageSize);

        // document 元素只能添加 AreaBreak、Image对象和IBlockElement接口的实现类对象
        // document.add(createParagraph());
        // 对比是否存在首行缩进
        // document.add(new Paragraph("君不见黄河之水天上来,奔流到海不复回").setFont(createPdfFont()));
        document.add(createTable());

        // 文档的最后处理
        document.close();
    }

    /** * 创建字体对象 * @return * @throws IOException */
    public static PdfFont createPdfFont() throws IOException { 
   
        // 使用 PdfFontFactory 创建字体
        // 使用下面字体可以处理中文不显示的问题
        return PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
    }

    /** * 创建 Table 对象 * @return */
    public static Table createTable() throws IOException { 
   
        // 创建几列的表格对象
        Table table = new Table(4);
        // 设置table表格宽度
        table.setWidth(UnitValue.POINT).setWidth(520);
        for (int i = 0; i < 2; i++) { 
   
            if (i == 0){ 
   
                // 第一行数据,创建 Cell 对象,默认一行一列
                Cell cell00 = new Cell();
                cell00.add(new Paragraph("姓名").setFont(createPdfFont()));
                table.addCell(cell00);

                table.addCell(new Cell().add(new Paragraph("李白").setFont(createPdfFont()).setFontColor(ColorConstants.BLACK)));

                table.addCell(new Cell().add(new Paragraph("性别").setFont(createPdfFont())).setFontSize(24));
                table.addCell(new Cell().add(new Paragraph("男").setFont(createPdfFont())));
            }else if (i == 1){ 
   
                // 第二行数据
                table.addCell(new Cell().add(new Paragraph("代表作").setFont(createPdfFont())));
                // 第二行数据,创建 Cell 对象,默认一行三列
                table.addCell(new Cell(1, 3).add(new Paragraph("《将进酒》《蜀道难》").setFont(createPdfFont())));
            }
        }

        return table;
    }

    /** * 创建段落 * Paragraph 和 Text 关系, * 同一个设置如果 Text 存在,则以 Text 设置为显示方式 * 如果 Text 没有设置,以 Paragraph 设置为显示方式 * 对齐模式以 Paragraph 对齐模式设置为显示方式 * @return * @throws IOException */
    public static Paragraph createParagraph() throws IOException { 
   
        // 可以通过构造方法添加问题
        Paragraph paragraph = new Paragraph("段落内容");
        // 也可以通过添加 Text 对象添加文字
        paragraph.add(createText());
        // 段落设置字体
        paragraph.setFont(createPdfFont());
        // 段落加粗
        paragraph.setBold();
        // 段落设置字体大佬
        paragraph.setFontSize(24);
        // 段落设置颜色
        paragraph.setFontColor(ColorConstants.RED);
        // 段落设置下划
        paragraph.setUnderline();
        // 段落首行缩进
        paragraph.setFirstLineIndent(40);
        // 设置段落对齐模式,对齐模式以段落对齐模式设置而显示
        paragraph.setTextAlignment(TextAlignment.CENTER);

        return paragraph;
    }

    /** * 创建文本对象 * * 注意要点:文本对象不能直接添加到document * * Paragraph 和 Text 关系, * 同一个设置如果 Text 存在,则以 Text 设置为显示方式 * 如果 Text 没有设置,以 Paragraph 设置为显示方式 * @return */
    public static Text createText() throws IOException { 
   
        Text text = new Text("将进酒");
        // 字体
        text.setFont(createPdfFont());
        // 字体加粗
        text.setBold();
        // 字体颜色
        text.setFontColor(ColorConstants.BLACK);
        // 字体大小
        text.setFontSize(24);
        // 字体添加下划线
        text.setUnderline();
        // 字体设置文本对齐模式
        text.setTextAlignment(TextAlignment.LEFT);

        return text;
    }


    /** * 获取临时文件路径 * @return */
    private static String getPdfFileName(){ 
   
        String userDir = System.getProperty("user.dir");
        String separator = System.getProperty("file.separator");
        return userDir + separator + "learn.pdf";
    }
}

合并PDF

package top.simba1949;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PdfMerger;

import java.io.IOException;

/** * @author Anthony * @date 2020/12/9 19:48 */
public class AddCover { 
   
    public static final String DEST = "D:\\IDE\\IDEA\\workspace\\learn\\test-spring-boot\\itextpdf-learn\\src\\main\\resources\\static\\dest.pdf";
    public static final String RESOURCE_ONE = "D:\\IDE\\IDEA\\workspace\\learn\\test-spring-boot\\itextpdf-learn\\src\\main\\resources\\static\\resource1.pdf";
    public static final String RESOURCE_TWO = "D:\\IDE\\IDEA\\workspace\\learn\\test-spring-boot\\itextpdf-learn\\src\\main\\resources\\static\\resource2.pdf";

    public static void main(String[] args) throws IOException { 
   
        // 目标pdf
        PdfDocument dest = new PdfDocument(new PdfWriter(DEST));
        // 源pdf
        PdfDocument cover = new PdfDocument(new PdfReader(RESOURCE_ONE));
        PdfDocument resource = new PdfDocument(new PdfReader(RESOURCE_TWO));

        PdfMerger merger = new PdfMerger(dest);
        // 将源pdf文件指定位置写入到目标pdf中
        merger.merge(cover, 1, 1);
        merger.merge(resource, 1, 1);

        cover.close();
        resource.close();
        merger.close();
    }
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/148177.html原文链接:https://javaforall.cn