Java でインタラクティブ フォームを扱う方法

Java でインタラクティブ フォームを扱う方法

本ガイドでは、Java 用の Aspose.PDF FOSS を使用して PDF 文書内の AcroForm フィールドを作成および管理する方法を示します。ラジオボタン、チェックボックス、テキストフィールドの追加方法と、送信されたフォームフィールドの値を読み取る方法を学びます。

ラジオボタングループを作成する

RadioButtonField は相互に排他的なオプションのグループを表します。各オプションはラベルと Rectangle バウンディングボックスで追加されます。初期値は、オプションラベルのいずれかを引数に setValue() を呼び出すことで設定します。

try (Document doc = new Document()) {
    PageCollection pages = doc.getPages();
    Page page = pages.add();
    RadioButtonField radio = new RadioButtonField(page);
    radio.setPartialName("choice");
    radio.addOption("Yes", new Rectangle(50, 50, 70, 70));
    radio.addOption("No", new Rectangle(50, 80, 70, 100));
    doc.getForm().add(radio, 1);
    radio.setValue("Yes");
    doc.save("form.pdf");
}

チェックボックスを追加する

CheckboxField は単一のブールフィールドです。デフォルトでチェックされるように setChecked(true) を設定します。フィールドは特定のページ番号(1 から始まる)にフォームとして追加されます。

try (Document doc = new Document()) {
    PageCollection pages = doc.getPages();
    Page page = pages.add();
    CheckboxField cb = new CheckboxField(page, new Rectangle(50, 50, 70, 70));
    cb.setPartialName("agree");
    cb.setChecked(true);
    doc.getForm().add(cb, 1);
    doc.save("form.pdf");
}

テキストフィールドを追加する

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("Enter your name");
    doc.getForm().add(text, 1);
    doc.save("form.pdf");
}

選択された値を取得する

フォームをロードした後、フィールドの部分名で現在の値を取得します。フィールドを具体的な型にキャストして、型固有のメソッドを呼び出します:

try (Document doc = new Document("form.pdf")) {
    RadioButtonField radio = (RadioButtonField) doc.getForm().get("choice");
    String selected = radio.getValue();
    System.out.println("Selected: " + selected);
}

参照

 日本語