通过 Java 将表格添加到 PDF

使用适用于 Java 库的 Aspose.PDF 以编程方式将表格插入到 PDF 文档

如何使用 Java 库在 PDF 文档中添加表格

为了添加表格,我们将使用 Aspose.PDF for Java API,这是一款功能丰富、功能强大且易于使用的适用于 Java 平台的转换 API。你可以直接从 Maven 下载它的最新版本,然后通过在 pom.xml 中添加以下配置将其安装在基于 Maven 的项目中。

Repository

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java AP</name>
    <url>https://releases.aspose.com/java/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>

通过 Java 将表格添加到 PDF


你需要 Aspose.PDF for Java 库 才能在你的环境中试用这些代码。

  1. 使用 “文档” 实例加载 PDF。
  2. 通过其索引访问该页面。
  3. 创建表对象。
  4. 设置表格设置(例如设置边框)。
  5. 填充表。
  6. 将表格添加到页面中。
  7. 保存该文件。

在 PDF 中添加表格-Java

Document pdfDocument = new Document(DATA_DIR.resolve("input.pdf").toString());
alizes a new instance of the Table
com.aspose.pdf.Table table = new com.aspose.pdf.Table();
he table border color as LightGray
table.setBorder(new BorderInfo(BorderSide.All, .5f, Color.getLightGray()));
he border for table cells
table.setDefaultCellBorder(new BorderInfo(BorderSide.All, .5f, Color.getLightGray()));
e a loop to add 10 rows
for (int row_count = 1; row_count < 10; row_count++) {
    // add row to table
    Row row = table.getRows().add();
    // add table cells
    row.getCells().add("Column (" + row_count + ", 1)");
    row.getCells().add("Column (" + row_count + ", 2)");
    row.getCells().add("Column (" + row_count + ", 3)");
}
able object to first page of input document
pdfDocument.getPages().get_Item(1).getParagraphs().add(table);
updated document containing table object
pdfDocument.save(DATA_DIR.resolve("document_with_table.pdf").toString());
pdfDocument.close();