Java中的PDF生成:最佳库概述
生成PDF文档是企业级Java开发中的典型任务之一。报告、发票、合同、证书——所有这些都可以方便地通过编程方式生成。在本文中,我们将介绍三种最流行的Java PDF处理库:iText、Apache PDFBox和OpenPDF。我们将分析它们的功能、特点,并提供实用的代码示例。
1. iText——强大且商业化的标准
iText是Java中创建PDF的事实标准。该库自2000年问世,提供最广泛的功能:从简单文本到复杂表单、水印、数字签名以及PDF/A支持。
许可: iText采用双重许可。对于开源项目(AGPL)免费,商业使用需要购买许可。
示例:创建带表格的简单PDF
import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Cell;import com.itextpdf.layout.element.Paragraph;import com.itextpdf.layout.element.Table;import com.itextpdf.layout.property.UnitValue;
public class ItextExample { public static void main(String[] args) throws Exception { String dest = "example_itext.pdf"; PdfWriter writer = new PdfWriter(dest); PdfDocument pdfDoc = new PdfDocument(writer); Document document = new Document(pdfDoc);
// 添加标题 document.add(new Paragraph("销售报告"));
// 创建表格 Table table = new Table(UnitValue.createPercentArray(3)).useAllAvailableWidth(); table.addHeaderCell(new Cell().add(new Paragraph("商品"))); table.addHeaderCell(new Cell().add(new Paragraph("数量"))); table.addHeaderCell(new Cell().add(new Paragraph("价格")));
table.addCell(new Cell().add(new Paragraph("笔记本电脑"))); table.addCell(new Cell().add(new Paragraph("10"))); table.addCell(new Cell().add(new Paragraph("1200 $")));
table.addCell(new Cell().add(new Paragraph("鼠标"))); table.addCell(new Cell().add(new Paragraph("50"))); table.addCell(new Cell().add(new Paragraph("25 $")));
document.add(table); document.close();
System.out.println("PDF已创建: " + dest); }}iText的优点:庞大的社区、优秀的文档、支持复杂场景(签名、表单、PDF/UA)。缺点:商业许可费用高昂。
2. Apache PDFBox——免费且开源
Apache PDFBox是一个完全免费的库,采用Apache 2.0许可。它不仅允许从头创建PDF,还可以编辑现有文档、提取文本、处理表单和图像。
示例:创建包含文本和图像的文档
import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;import org.apache.pdfbox.pdmodel.PDPageContentStream;import org.apache.pdfbox.pdmodel.font.PDType0Font;import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import java.io.File;
public class PdfBoxExample { public static void main(String[] args) throws Exception { PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
// 加载字体(需要字体文件) PDType0Font font = PDType0Font.load(document, new File("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf")); contentStream.setFont(font, 14); contentStream.beginText(); contentStream.newLineAtOffset(50, 700); conte