Java 里的 iText 详解

5 阅读3分钟

iText 是一个强大的 PDF 操作库,用于创建、编辑和处理 PDF 文档。下面详细介绍在 Java 8 环境中使用 iText 的方法。

1. 环境配置

Maven 依赖

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

<!-- 对于 iText 7 -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext7-core</artifactId>
    <version>7.2.5</version>
    <type>pom</type>
</dependency>

2. 基础 PDF 创建

创建简单 PDF

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileOutputStream;
import java.io.IOException;

public class BasicPdfCreation {
    public static void main(String[] args) {
        Document document = new Document();
        
        try {
            PdfWriter.getInstance(document, 
                new FileOutputStream("hello_world.pdf"));
            document.open();
            document.add(new Paragraph("Hello World!"));
            document.add(new Paragraph("这是使用 iText 创建的 PDF 文档"));
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}

3. 文本格式化

字体和样式设置

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class TextFormattingExample {
    public static void main(String[] args) throws Exception {
        Document document = new Document();
        PdfWriter.getInstance(document, 
            new FileOutputStream("formatted_text.pdf"));
        document.open();
        
        // 创建中文字体
        BaseFont chineseFont = BaseFont.createFont(
            "STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        
        // 不同字体样式
        Font titleFont = new Font(chineseFont, 18, Font.BOLD);
        Font normalFont = new Font(chineseFont, 12, Font.NORMAL);
        Font italicFont = new Font(chineseFont, 12, Font.ITALIC);
        Font boldFont = new Font(chineseFont, 12, Font.BOLD);
        
        document.add(new Paragraph("PDF 文档标题", titleFont));
        document.add(new Paragraph("普通文本内容", normalFont));
        document.add(new Paragraph("斜体文本", italicFont));
        document.add(new Paragraph("粗体文本", boldFont));
        
        document.close();
    }
}

4. 表格创建

基本表格

import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPCell;

public class TableExample {
    public static void main(String[] args) throws Exception {
        Document document = new Document();
        PdfWriter.getInstance(document, 
            new FileOutputStream("table_example.pdf"));
        document.open();
        
        // 创建 3 列表格
        PdfPTable table = new PdfPTable(3);
        
        // 添加表头
        table.addCell("姓名");
        table.addCell("年龄");
        table.addCell("职业");
        
        // 添加数据
        table.addCell("张三");
        table.addCell("25");
        table.addCell("工程师");
        
        table.addCell("李四");
        table.addCell("30");
        table.addCell("设计师");
        
        document.add(table);
        document.close();
    }
}

5. 图像处理

插入图片

import com.itextpdf.text.Image;

public class ImageExample {
    public static void main(String[] args) throws Exception {
        Document document = new Document();
        PdfWriter.getInstance(document, 
            new FileOutputStream("image_example.pdf"));
        document.open();
        
        // 插入图片
        Image image = Image.getInstance("path/to/your/image.jpg");
        image.scaleToFit(400, 300); // 调整图片大小
        image.setAlignment(Image.ALIGN_CENTER);
        
        document.add(new Paragraph("图片示例:"));
        document.add(image);
        
        document.close();
    }
}

6. PDF 操作

读取 PDF

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

public class ReadPdfExample {
    public static void main(String[] args) throws Exception {
        PdfReader reader = new PdfReader("input.pdf");
        
        // 获取页数
        int pages = reader.getNumberOfPages();
        System.out.println("总页数: " + pages);
        
        // 提取文本
        for (int i = 1; i <= pages; i++) {
            String text = PdfTextExtractor.getTextFromPage(reader, i);
            System.out.println("第 " + i + " 页内容:");
            System.out.println(text);
        }
        
        reader.close();
    }
}

合并 PDF

import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;

public class MergePdfExample {
    public static void main(String[] args) throws Exception {
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, 
            new FileOutputStream("merged.pdf"));
        document.open();
        
        // 要合并的文件列表
        String[] files = {"file1.pdf", "file2.pdf", "file3.pdf"};
        
        for (String file : files) {
            PdfReader reader = new PdfReader(file);
            copy.addDocument(reader);
            reader.close();
        }
        
        document.close();
    }
}

7. 高级功能

添加水印

import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.BaseFont;

public class WatermarkExample {
    public static void main(String[] args) throws Exception {
        PdfReader reader = new PdfReader("input.pdf");
        PdfStamper stamper = new PdfStamper(reader, 
            new FileOutputStream("watermarked.pdf"));
        
        // 设置透明度
        PdfGState gstate = new PdfGState();
        gstate.setFillOpacity(0.3f);
        
        // 获取总页数
        int pages = reader.getNumberOfPages();
        
        // 创建中文字体
        BaseFont font = BaseFont.createFont(
            "STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        
        // 为每一页添加水印
        for (int i = 1; i <= pages; i++) {
            PdfContentByte content = stamper.getOverContent(i);
            content.saveState();
            content.setGState(gstate);
            content.beginText();
            content.setFontAndSize(font, 48);
            content.showTextAligned(Element.ALIGN_CENTER, 
                "机密文档", 300, 400, 45);
            content.endText();
            content.restoreState();
        }
        
        stamper.close();
        reader.close();
    }
}

添加页眉页脚

import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

public class HeaderFooterExample extends PdfPageEventHelper {
    
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            PdfContentByte cb = writer.getDirectContent();
            BaseFont font = BaseFont.createFont(
                "STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            
            // 添加页眉
            cb.beginText();
            cb.setFontAndSize(font, 10);
            cb.showTextAligned(Element.ALIGN_CENTER, 
                "公司文档 - 机密", 
                document.getPageSize().getWidth() / 2, 
                document.getPageSize().getHeight() - 30, 0);
            cb.endText();
            
            // 添加页脚
            cb.beginText();
            cb.setFontAndSize(font, 10);
            cb.showTextAligned(Element.ALIGN_CENTER, 
                "第 " + writer.getPageNumber() + " 页", 
                document.getPageSize().getWidth() / 2, 30, 0);
            cb.endText();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws Exception {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, 
            new FileOutputStream("header_footer.pdf"));
        
        writer.setPageEvent(new HeaderFooterExample());
        
        document.open();
        for (int i = 0; i < 10; i++) {
            document.add(new Paragraph("这是第 " + (i+1) + " 页的内容"));
            document.newPage();
        }
        document.close();
    }
}

8. 使用 iText 7(新版)

iText 7 基础示例

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

public class IText7Example {
    public static void main(String[] args) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(
            new PdfWriter("itext7_example.pdf"));
        Document document = new Document(pdfDoc);
        
        // 添加内容
        document.add(new Paragraph("Hello iText 7!"));
        document.add(new Paragraph("这是使用 iText 7 创建的 PDF"));
        
        document.close();
    }
}

9. 最佳实践和注意事项

资源管理

public class ResourceManagement {
    public static void safePdfCreation() {
        Document document = null;
        FileOutputStream fos = null;
        
        try {
            document = new Document();
            fos = new FileOutputStream("output.pdf");
            PdfWriter.getInstance(document, fos);
            document.open();
            document.add(new Paragraph("安全创建 PDF"));
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 确保资源被正确关闭
            if (document != null) {
                document.close();
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

异常处理

public class ExceptionHandling {
    public static void createPdfWithHandling() {
        try {
            // PDF 创建代码
            Document document = new Document();
            PdfWriter.getInstance(document, 
                new FileOutputStream("output.pdf"));
            document.open();
            document.add(new Paragraph("内容"));
            document.close();
            
        } catch (DocumentException e) {
            System.err.println("文档处理错误: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("IO 错误: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("未知错误: " + e.getMessage());
        }
    }
}

总结

iText 提供了丰富的功能来处理 PDF 文档:

  1. 创建 PDF:从简单的文本到复杂的布局
  2. 格式化:支持多种字体、颜色和样式
  3. 表格和图像:创建数据表格和插入图片
  4. PDF 操作:读取、合并、分割 PDF
  5. 高级功能:水印、页眉页脚、加密等

在使用时要注意:

  • 正确管理资源(及时关闭 Document 和流)
  • 处理中文字体问题
  • 选择合适的 iText 版本(5.x 或 7.x)
  • 遵守 iText 的许可证要求