在Java项目中引入iText库的方法主要取决于你所使用的构建工具,以下是几种常见的方式:
1. 使用Maven引入(推荐)
如果你的项目使用Maven管理依赖,只需在pom.xml
文件中添加iText的依赖坐标即可:
<!-- iText核心库 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version> <!-- 稳定版本 -->
</dependency>
<!-- 如果需要处理HTML到PDF的转换,还需添加xmlworker -->
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.13.3</version>
</dependency>
注意:iText 7之后的版本包结构有所变化,如果使用iText 7,依赖坐标为:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.2.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>7.2.5</version>
</dependency>
2. 使用Gradle引入
如果项目使用Gradle,在build.gradle
文件中添加:
// iText 5.x版本
implementation 'com.itextpdf:itextpdf:5.5.13.3'
implementation 'com.itextpdf.tool:xmlworker:5.5.13.3'
// 或iText 7.x版本
implementation 'com.itextpdf:kernel:7.2.5'
implementation 'com.itextpdf:layout:7.2.5'
3. 手动下载JAR包引入
如果不使用构建工具,可以手动下载JAR包并添加到项目中:
- 访问iText的Maven仓库:
- 下载对应版本的JAR文件(如
itextpdf-5.5.13.3.jar
) - 在IDE中添加JAR到项目:
- Eclipse:右键项目 → Build Path → Add External Archives...
- IntelliJ IDEA:File → Project Structure → Modules → Dependencies → + → JARs or directories...
版本选择建议
- 如需简单的PDF生成功能,iText 5.x足够使用且文档丰富
- 如需更现代的API和高级功能(如PDF/A支持、更好的字体处理),可选择iText 7.x
- 注意:iText 7的API与5.x不兼容,迁移时需要修改代码
引入完成后,就可以在代码中使用iText的类和方法来操作PDF了,例如前面示例中的Document
、PdfWriter
等类。