Java如何在iText中创建Chapter?

这个简短的示例向您展示了如何使用iText在PDF文档中创建章节。要创建章节,我们使用com.itextpdf.text.Chapter该类。我们可以将章节标题和章节编号作为Chapter构造函数的参数传递。

要为该章创建一个部分,我们可以使用com.itextpdf.text.Section该类。要添加一个部分,我们调用对象的Chapter.addSection()方法Chapter。让我们看下面的例子:

package org.nhooo.example.itextpdf;

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

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class ChapterDemo {
    public static void main(String[] args) {
        // 创建一个新文件
        Document document = new Document();
        try {
            // 准备PDF编写器并打开文档。
            PdfWriter.getInstance(document, new FileOutputStream("ChapterDemo.pdf"));
            document.open();

            // 创建一个新的Chapter对象
            Chapter chapter = new Chapter("Chapter One", 1);

            // 在本章中添加章节
            Section section = chapter.addSection("This is Section 1", 2);
            Paragraph paragraph = new Paragraph("This is the paragraph of the Section 1");
            section.add(paragraph);

            chapter.addSection("This is Section 2", 2);

            document.add(chapter);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}

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>