インタラクティブ フォーム
このガイドでは、Aspose.PDF FOSS for Java を使用して PDF ドキュメント内の AcroForm フィールドを作成および管理する方法を示します。ラジオボタン、チェックボックス、テキストフィールド、コンボボックス、リストボックスの追加方法と、送信されたフィールド値の取得方法を学びます。
AcroForm API
この Form クラスは Document.getForm() からアクセスでき、ドキュメント内のすべての AcroForm フィールドを管理します。フィールドは Form.add(field, pageNumber) を呼び出すことで追加されます。
RadioButtonField
ラジオボタンのグループを作成し、各オプションをそれぞれの Rectangle に配置します。各オプションはラベルとバウンディングボックスで追加されます。setValue() を呼び出してオプションを事前に選択します:
try (Document doc = new Document()) {
PageCollection pages = doc.getPages();
Page page = pages.add();
RadioButtonField radio = new RadioButtonField(page);
radio.setPartialName("color");
radio.addOption("Red", new Rectangle(50, 50, 70, 70));
radio.addOption("Blue", new Rectangle(50, 80, 70, 100));
doc.getForm().add(radio, 1);
radio.setValue("Red");
doc.save("form.pdf");
}setValue() はプログラムでオプションを選択します。getValue() は現在選択されているオプション名を返します。
CheckboxField
CheckboxField は PDF フォーム内の単一のブール入力フィールドを表します。setChecked(true) を設定すると、フィールドがデフォルトでチェックされた状態になります。1 から始まるページ番号でフォームに追加します。
try (Document doc = new Document()) {
PageCollection pages = doc.getPages();
Page page = pages.add();
CheckboxField cb = new CheckboxField(page, new Rectangle(100, 100, 120, 120));
cb.setPartialName("agree");
cb.setChecked(true);
doc.getForm().add(cb, 1);
doc.save("form.pdf");
}TextBoxField
TextBoxField は自由形式のテキスト入力を受け付けます。setValue() でデフォルト値を設定し、保存する前にフィールドをフォームに登録します。
try (Document doc = new Document()) {
PageCollection pages = doc.getPages();
Page page = pages.add();
TextBoxField text = new TextBoxField(page, new Rectangle(50, 200, 250, 220));
text.setPartialName("name");
text.setValue("Default text");
doc.getForm().add(text, 1);
doc.save("form.pdf");
}ComboBoxField と ListBoxField
ComboBoxField と ListBoxField は選択可能なオプションリストを提供します。両方とも addOption() を通じてオプション文字列を受け取り、選択内容を取得するために getValue() を公開します。
FormEditor
FormEditor は AcroForm フィールドを操作するためのファサードクラスです。bindPdf() でドキュメントをバインドし、変更を適用した後、save() を呼び出します。
フィールド値の読み取り
入力済みのフォームを読み込んだ後、doc.getForm().get(name) を呼び出し、具体的なフィールド型にキャストすることで、名前付きフィールドの現在の値を取得します:
try (Document doc = new Document("form.pdf")) {
RadioButtonField radio = (RadioButtonField) doc.getForm().get("color");
String selected = radio.getValue();
System.out.println("Selected: " + selected);
}