フォームフィールド名の特定

Contents
[ ]

Aspose.PDF for .NETは、PDFフォームを作成、編集、既に作成されたPDFフォームに記入する機能を提供します。Aspose.Pdf.Facades名前空間には、Formクラスが含まれており、FillFieldという名前の関数があり、フィールド名とフィールド値の2つの引数を取ります。したがって、フォームフィールドに記入するには、正確なフォームフィールド名を知っている必要があります。

実装の詳細

私たちはしばしば、Adobe Designerなどのツールで作成されたフォームに記入する必要があるシナリオに直面しますが、フォームフィールド名が不明な場合があります。したがって、フォームフィールドに記入するためには、まずすべてのPDFフォームフィールドの名前を読み取る必要があります。Formクラスは、すべてのフィールド名を返すFieldNamesというプロパティを提供しており、PDFにフィールドが含まれていない場合はnullを返します。ただし、このプロパティを使用すると、PDFフォーム内のすべてのフィールド名が取得されますが、どの名前がどのフィールドに対応しているかは不明な場合があります。

この問題の解決策として、各フィールドの外観属性を使用します。Formクラスには、位置、色、境界スタイル、フォント、リスト項目などの属性を返すGetFieldFacadeという名前の関数があります。これらの値を保存するために、フィールドの視覚的属性を記録するために使用されるFormFieldFacadeクラスを使用する必要があります。これらの属性を取得したら、各フィールドの下にフィールド名を表示するテキストフィールドを追加できます。

Aspose.Pdf.Facades名前空間には、PDFフォームを操作する機能を提供するFormEditorというクラスがあります。PDFフォームを開き、既存の各フォームフィールドの下にテキストフィールドを追加し、新しい名前でPDFフォームを保存します。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void IdentifyFormFieldsNames()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles();
    // First a input pdf file should be assigned
    var form = new Aspose.Pdf.Facades.Form(dataDir + "FilledForm.pdf");
    // Get all field names
    var allfields = form.FieldNames;
    // Create an array which will hold the location coordinates of Form fields
    var box = new System.Drawing.Rectangle[allfields.Length];
    for (int i = 0; i < allfields.Length; i++)
    {
        // Get the appearance attributes of each field, consequtively
        var facade = form.GetFieldFacade(allfields[i]);
        // Box in FormFieldFacade class holds field's location
        box[i] = facade.Box;
    }
    // Save PDF document
    form.Save(dataDir + "IdentifyFormFields_1_out.pdf");

    // Create PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "FilledForm - 2.pdf"))
    {
        // Now we need to add a textfield just upon the original one
        using (var editor = new Aspose.Pdf.Facades.FormEditor(document))
        {
            for (int i = 0; i < allfields.Length; i++)
            {
                // Add text field beneath every existing form field
                editor.AddField(Aspose.Pdf.Facades.FieldType.Text, 
                "TextField" + i, allfields[i], 1, 
                box[i].Left, box[i].Top, box[i].Left + 50, box[i].Top + 10);
            }
            // Save PDF document
            editor.Save(dataDir + "IdentifyFormFields_out.pdf");
        }
    }
}