此示例是iText系列的第一个示例,我们将从学习使用iText PDF库创建PDF文档开始。我们将看到如何使用Document该类,获取的实例PdfWriter,创建一个简单Paragraph的文本并设置文本对齐方式和字体。
生成PDF文档的基本步骤是:
创建一个Document代表PDF文档的对象。
在PdfWrite需要的对象Document和OutputStream对象的写,我们加入了PDF的内容Document转换成PDF文件。
我们Document使用Paragraph对象将一个段落添加到实例中。
最后,我们需要通过调用Document.close()方法来关闭文档。
这是一个代码示例,演示了如何创建PDF文档。
package org.nhooo.example.itextpdf;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class DocumentCreate {
public static void main(String[] args) {
// 创建一个新文档。
Document document = new Document();
try {
// 获取PdfWriter的实例并创建一个HelloWorld.pdf
// 文件作为输出。
PdfWriter.getInstance(document,
new FileOutputStream(new File("HelloWorld.pdf")));
document.open();
// 为我们的pdf文档创建第一段
//创建。我们还设置了字体的对齐方式和字体
// 段。
String text = "Kode Java website provides beginners to Java " +
"programming some examples to use the Java API " +
"(Application Programming Interface) to develop " +
"applications. Learning from some examples will " +
"hopefully decrease the time required to learn " +
"Java.";
Paragraph paragraph = new Paragraph(text);
paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
paragraph.setFont(new Font(
Font.FontFamily.HELVETICA, 10, Font.NORMAL));
document.add(paragraph);
} 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>