java引入itextpdf生成pdf文件
时间: 2025-01-13 10:59:27 浏览: 76
### Java 使用 iTextPDF 库创建 PDF 文件
#### Maven 依赖配置
要在项目中使用 iText7 来创建 PDF 文档,首先需要在 `pom.xml` 中添加相应的依赖项:
```xml
<dependencies>
<!-- itext7 core library -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.1.13</version>
</dependency>
<!-- html to pdf conversion support -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>3.0.2</version>
</dependency>
<!-- Asian font support for displaying Chinese characters correctly -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>7.1.13</version>
</dependency>
</dependencies>
```
#### 创建简单 PDF 的示例代码
下面是一个简单的例子,展示如何使用 iText7 在 Java 程序里创建一个包含文本和表格的基础 PDF 文件。
```java
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
public class CreateSimplePdf {
public static void main(String[] args) throws Exception {
String dest = "simple_pdf_example.pdf";
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
// Add a paragraph with some text content.
Paragraph p = new Paragraph("This is an example of creating a simple PDF using iText.");
document.add(p);
// Define table structure and add data rows.
Table table = new Table(new float[]{1, 2});
table.addCell("Header Col 1");
table.addCell("Header Col 2");
for (int r=1; r<=5; ++r){
table.addCell("Row "+r+" Cell A");
table.addCell("Row "+r+" Cell B");
}
document.add(table);
// Close the document after writing all elements.
document.close();
}
}
```
这段程序会生成名为 `simple_pdf_example.pdf` 的文件,在其中包含了段落以及带有两列五行数据的表格[^3]。
阅读全文
相关推荐


















