既存のPDF内のテーブルを操作する

既存のPDF内のテーブルを操作する

Aspose.PDF for .NETがサポートする最初の機能の1つは、テーブルを操作する能力であり、ゼロから生成されたPDFファイルや既存のPDFファイルにテーブルを追加するための優れたサポートを提供します。また、データベースの内容に基づいて動的なテーブルを作成するために、テーブルをデータベース(DOM)と統合する機能も得られます。この新しいリリースでは、PDFドキュメントのページに既に存在する単純なテーブルを検索および解析する新機能を実装しました。Aspose.PDF.Text.TableAbsorberという新しいクラスがこれらの機能を提供します。TableAbsorberの使用は、既存のTextFragmentAbsorberクラスと非常に似ています。以下のコードスニペットは、特定のテーブルセルの内容を更新する手順を示しています。

以下のコードスニペットは、Aspose.PDF.Drawingライブラリでも動作します。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ManipulateTable()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Tables();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "input.pdf"))
    {
        // Create TableAbsorber object to find tables
        var absorber = new Aspose.Pdf.Text.TableAbsorber();

        // Visit first page with absorber
        absorber.Visit(document.Pages[1]);

        // Get access to first table on page, their first cell and text fragments in it
        Aspose.Pdf.Text.TextFragment fragment = absorber.TableList[0].RowList[0].CellList[0].TextFragments[1];

        // Change text of the first text fragment in the cell
        fragment.Text = "hi world";

        // Save PDF document
        document.Save(dataDir + "ManipulateTable_out.pdf");
    }
}

PDFドキュメント内の古いテーブルを新しいテーブルに置き換える

特定のテーブルを見つけて、望ましいテーブルに置き換える必要がある場合は、TableAbsorberクラスのReplace()メソッドを使用してそれを行うことができます。以下の例は、PDFドキュメント内のテーブルを置き換える機能を示しています。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ReplaceTable()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Tables();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "Table_input2.pdf"))
    {
        // Create TableAbsorber object to find tables
        var absorber = new Aspose.Pdf.Text.TableAbsorber();

        // Visit first page with absorber
        absorber.Visit(document.Pages[1]);

        // Get first table on the page
        Aspose.Pdf.Text.AbsorbedTable table = absorber.TableList[0];

        // Create new table
        var newTable = new Aspose.Pdf.Table();
        newTable.ColumnWidths = "100 100 100";
        newTable.DefaultCellBorder = new Aspose.Pdf.BorderInfo(BorderSide.All, 1F);

        Row row = newTable.Rows.Add();
        row.Cells.Add("Col 1");
        row.Cells.Add("Col 2");
        row.Cells.Add("Col 3");

        // Replace the table with new one
        absorber.Replace(document.Pages[1], table, newTable);

        // Save PDF document
        document.Save(dataDir + "ReplaceTable_out.pdf");
    }
}