通過 Java 在 PDF 文檔中添加表格

如何使用 Java 庫在 PDF 中添加表格

如何使用 Java 庫在 PDF 文件中添加表格

為了添加表,我們將使用[Aspose.PDF用於Java](https://products.aspose.com/pdf/java)API,這是一個功能豐富,功能強大且易於使用的Java平臺轉換API。您可以直接從 [Maven](https://repository.aspose.com/webapp/#/artifacts/browse/tree/General/repo/com/aspose/aspose-pdf)下載其最新版本,並通過將以下配置添加到 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](https://releases.aspose.com/pdf/java)來嘗試環境中的代碼。

  1. 載入包含文件實例的 PDF。
  2. 通過主頁索引訪問主頁。
  3. 建立表物件。
  4. 設定表格設定(例如設置邊框)。
  5. 填充表。
  6. 將表格添加到頁面。
  7. 儲存檔。

在 PDF 中新增表格 - Java


    Document doc = new Document(_dataDir + "input.pdf");
    // Initializes a new instance of the Table
    Table table = new Table();
    // Set the table border color as LightGray
    table.setBorder(new BorderInfo(BorderSide.All, .5f, Color.getLightGray()));
    // set the border for table cells
    table.setDefaultCellBorder(new BorderInfo(BorderSide.All, .5f, Color.getLightGray()));
    // create 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)");
    }
    // Add table object to first page of input document
    doc.getPages().get_Item(1).getParagraphs().add(table);
    // Save updated document containing table object
    doc.save(_dataDir + "document_with_table.pdf");