Java如何使用iText文档类?

该com.itextpdf.text.Document是核心类iText库的。此类表示pdf文档。基本上,要使用文档,我们首先必须创建一个实例Document。创建实例后,我们通过调用open()方法打开文档。要向文档中添加一些内容,我们可以使用add()方法。最后,在处理完文档后,我们必须通过调用close()方法将其关闭。

如果您需要将文档编写并刷新到文件中,我们可以使用一个PdfWriter类。类的构造函数接受一个Document对象和一个OutputStream对象来完成工作。

package org.nhooo.example.itextpdf;

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

public class DocumentDemo {
    public static void main(String[] args) {
        // 创建文档的实例。
        Document document = new Document();
        try {
            // 要使用文档,我们必须打开文档,添加
            // 一些内容,最后关闭文档。
            document.open();
            document.add(new Paragraph("Hello World!"));
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}

Maven依赖

<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>