📜  iText-创建PDF文档(1)

📅  最后修改于: 2023-12-03 15:01:27.473000             🧑  作者: Mango

iText-创建PDF文档

iText是一个Java库,可以用于创建和操作PDF文档,包括文字、图片、表格等内容的添加和编辑。它是免费的,使用GPL/LGPL/AGPL许可证的开源软件。

安装

iText的最新版本可以从官方网站 https://itextpdf.com/en/downloads 下载。

也可以通过Maven或Gradle等包管理器来引入依赖。例如,在Maven中添加以下依赖:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.2</version>
</dependency>
使用

以下是一个简单的iText例子,用于创建一个包含“Hello World!”文字的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.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class HelloWorld {

    public static void main(String[] args) {
        Document document = new Document();
        try {
            PdfWriter.getInstance(document, new FileOutputStream(new File("hello.pdf")));
            document.open();
            document.add(new Paragraph("Hello World!"));
            document.close();
        } catch (FileNotFoundException | DocumentException e) {
            e.printStackTrace();
        }
    }
}

这里创建了一个Document对象,然后使用PdfWriter将其写入到FileOutputStream中。Document对象调用add方法加入一个新段落,并传入字符串“Hello World!”作为内容。

生成的PDF文件将被保存在与Java程序相同的目录下,并命名为“hello.pdf”。

添加更多内容

除了简单的文本,iText还支持添加图片、表格、超链接等更多内容。

例如,以下代码来创建一个包含图片和表格的PDF:

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

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

public class ImageTableExample {

    public static void main(String[] args)
            throws DocumentException, IOException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("example.pdf"));
        document.open();
        Font font = FontFactory.getFont(FontFactory.COURIER_BOLD, 16, BaseColor.BLACK);
        Image img = Image.getInstance("example.png");
        img.scaleToFit(500f, 500f);
        Paragraph para = new Paragraph("This is an example image:", font);
        document.add(para);
        document.add(img);
        document.newPage();
        PdfPTable table = new PdfPTable(3);
        PdfPCell cell = new PdfPCell(new Phrase("Table Header"));
        cell.setColspan(3);
        table.addCell(cell);
        table.addCell("Col 1 Row 1");
        table.addCell("Col 2 Row 1");
        table.addCell("Col 3 Row 1");
        table.addCell("Col 1 Row 2");
        table.addCell("Col 2 Row 2");
        table.addCell("Col 3 Row 2");
        document.add(table);
        document.close();
    }
}

这里创建了一个图片和一个3列的表格。图片使用Image类以文件路径参数,调用scaleToFit方法修改大小。表格可以使用PdfPTable创建,可以使用PdfPCell创建单元格,并设置它们的内容。使用document.newPage()可以添加新的页面。

更多关于iText的用法可以在官方网站的文档中了解到 https://itextpdf.com/en/docs