IronPDF チュートリアル C#のPDFフォーム C#でPDFフォーム:インタラクティブなフォームを作成、入力、処理する。 カーティス・チャウ 更新日:2026年2月5日 IronPDF をダウンロード NuGet ダウンロード DLL ダウンロード Windows 版 無料トライアル LLM向けのコピー LLM向けのコピー LLM 用の Markdown としてページをコピーする ChatGPTで開く このページについてChatGPTに質問する ジェミニで開く このページについてGeminiに問い合わせる Grokで開く このページについてGrokに質問する 困惑の中で開く このページについてPerplexityに問い合わせる 共有する Facebook で共有 Xでシェア(Twitter) LinkedIn で共有 URLをコピー 記事をメールで送る This article was translated from English: Does it need improvement? Translated View the article in English PDF AcroForms in C# .NET with IronPDF は、既存の政府フォームの読み取りや入力から、HTMLから新しいフォームを作成したり、送信されたデータを抽出したり、何千ものドキュメントをバッチ処理したり、インタラクティブなフォームフィールドを完全にプログラムで制御できるようにします。 IronPDFはテキスト入力、チェックボックス、ラジオボタン、ドロップダウン、署名フィールドなど、あらゆる標準的なフィールドタイプを扱うことができます。 TL;DR:クイックスタートガイド。 このチュートリアルでは、既存のフォームフィールドの読み取りから、完成したドキュメントのバッチ生成まで、C# .NETでの対話型PDFフォームの作成、入力、処理について説明します。 対象者: .NET開発者で、政府、医療、金融、または人事プロセスのPDFフォームワークフローを自動化している人。 構築するもの: PDF フォーム (テキスト、チェックボックス、ラジオボタン、ドロップダウン) の読み取りと入力、HTML から PDF フォームの作成、送信されたデータの抽出、入力の検証、値をロックするためのフォームの平坦化、W-9 処理の自動化、完成したフォームのバッチ生成。 動作環境: .NET 10、.NET 8 LTS、.NET Framework 4.6.2+、.NET Standard 2.0。出力は、Adobe Acrobat、Preview、およびすべての主要なPDFリーダーで動作します。 このアプローチを使用する場合:アプリケーションが、手動でデータ入力することなく、PDFフォームに入力、作成、または処理を大規模に行う必要がある場合。 技術的に重要な理由 AcroFormフィールドは構造化オブジェクトであり、プログラムで読み書きすることが予測可能です。 IronPDFはHTMLのフォーム要素をAcroFormのフォーム要素に変換し、柔軟なデザインを可能にします。 わずか数行のコードで最初のPDFフォームを埋めてください: 今すぐ NuGet で PDF を作成してみましょう: NuGet パッケージ マネージャーを使用して IronPDF をインストールします PM > Install-Package IronPdf このコード スニペットをコピーして実行します。 var pdf = IronPdf.PdfDocument.FromFile("form.pdf"); pdf.Form.FindFormField("name").Value = "John Smith"; pdf.SaveAs("filled-form.pdf"); 実際の環境でテストするためにデプロイする 今すぐ無料トライアルでプロジェクトに IronPDF を使い始めましょう 30日間無料トライアル IronPDFを購入または30日間のトライアルにサインアップした後、アプリケーションの最初にライセンスキーを追加してください。 IronPdf.License.LicenseKey = "KEY"; IronPdf.License.LicenseKey = "KEY"; Imports IronPdf IronPdf.License.LicenseKey = "KEY" $vbLabelText $csharpLabel 今日あなたのプロジェクトでIronPDFを無料トライアルで使用開始。 最初のステップ: 無料で始める 購入の準備ができていませんか? PM > Install-Package IronPdf IronPDF を NuGet でチェックしてください。1000万回以上のダウンロードで、C#によるPDF開発を変革しています。 DLL または Windowsインストーラー をダウンロードすることもできます。 目次を参照してください。 TL;DR:クイックスタートガイド クイック概要。 PDFフォームを理解する Why are Interactive PDF Forms Still Essential in 2025? PDFアクロフォームとは何ですか? 既存のフォームの読み取りと入力 どのようにPDFを開き、すべてのフォームフィールドをリストしますか? テキストフィールド、チェックボックス、ドロップダウンをどのように入力しますか? データオブジェクトと辞書からフォームに入力するには? 入力前にどのようにフォームデータを検証しますか。 ゼロからフォームを作成する PDFフォームにテキスト入力フィールドを作成するには? PDFフォームにチェックボックスとラジオボタンを追加するには? PDFフォームでドロップダウンリストを作成するには? PDFフォームに署名フィールドを追加するには? フォーム要素のスタイルと位置はどのように決まりますか。 フォーム処理ワークフロー 記入済みPDFフォームからデータを抽出する方法。 PDFフォームをフラットにしてフィールド値をロックするには? エンドユーザー向けのPDFフォームの事前入力はどのように行うのですか? どのようにフォームデータ処理パイプラインを構築しますか? 政府フォームオートメーション W-9のようなIRSの納税申告書を自動化するには? フォームを可変データでバッチ処理するには? 政府PDF標準への準拠をどのように保証しますか。 なぜインタラクティブPDFフォームは2025年においても不可欠なのか ウェブフォームやクラウドベースのドキュメントソリューションの普及にもかかわらず、PDFフォームは重要なビジネスプロセスを支配し続けています。 政府機関、医療機関、金融機関、法律事務所は、いずれも公式文書としてPDFフォームを多用しています。 医療分野だけでも、患者記録の88%がPDFとして保存または共有されています。 世界中の税務当局は、年間数十億件のフォーム提出を処理しており、その大部分は電子 PDF 文書として届きます。 もっと現代的な選択肢がありそうなのに、なぜこのような形式が残っているのでしょうか。その答えは、法的要件、普遍的な互換性、文書の完全性の組み合わせにあります。 PDFフォームは、表示するデバイスやオペレーティングシステムに関係なく、正確な書式を保持します。 Windowsのデスクトップで入力したフォームは、Macのラップトップで開いたり、役所で印刷したりしても同じように表示されます。この一貫性は、正確な書式設定が有効性に影響を及ぼす可能性のある法的文書、規制当局への提出書類、公式記録を扱う際に非常に重要です。 ウェブフォームには確かにその役割がありますが、いくつかの理由から、PDFフォームを完全に置き換えることはできません。 多くの規制機関では、特にPDFでの提出を要求しています。 法的手続きでは、数年後に確実に保管・検証できる形式の文書が求められることがよくあります。 オフラインアクセスは、現場作業員や遠隔地、インターネット接続が保証されない状況でも重要です。 さらに、PDFフォームはデジタル署名、暗号化、追跡が可能で、コンプライアンスに不可欠な監査証跡を提供します。 PDFソフトウェア市場はこのような継続的な需要を反映しており、2024年の市場規模は48億ドルで、2030年まで毎年8~11%の成長が予測されています。.NET開発者にとって、これは技術的な課題であると同時に大きなチャンスでもあります。 PDFフォームの自動化をマスターすることは、あらゆる業界で何百万もの文書に触れるワークフローを合理化できることを意味します。 PDFアクロフォームとは何ですか? AcroFormsは、PDF仕様に組み込まれた標準的な対話型フォーム技術です。 Adobe によって開発され、現在は ISO 標準として維持されている AcroForms は、PDF 文書に記入可能なフィールドを含めることができ、ユーザーは準拠する PDF リーダーを使用して記入することができます。 Adobe AcrobatやPreviewで税務フォームを開き、フィールドに入力するとき、あなたはその文書に埋め込まれたAcroForm要素とやりとりしています。 AcroForm の各フォームフィールドにはいくつかの重要な特性があります。 フィールド名は、プログラムがフィールドを見つけ、操作するために使用する一意の識別子として機能します。 フィールドタイプは、テキスト、チェックボックス、ラジオボタン、ドロップダウン選択、署名など、フィールドが受け付ける入力の種類を決定します。 valueプロパティは、フィールドの現在の内容を保持し、プログラムで読み書きできます。 追加のプロパティは、外観、検証ルール、デフォルト値を制御します。 AcroForms は、ほとんどのデータ収集のニーズをカバーする、いくつかの異なるフィールドタイプをサポートしています。 テキストフィールドは、自由形式のテキスト入力を受け付け、1行または複数行に設定できます。 チェックボックスフィールドは、二者択一を表し、複数の選択を可能にするためにグループ化することができます。 ラジオボタンフィールドは、1つの選択肢を選択すると自動的に他の選択肢の選択が解除されるグループで動作します。 コンボボックスとリストボックスは、あらかじめ定義されたオプションを選択するためのものです。 署名フィールドは、デジタル署名のための指定領域を提供します。 これらのフィールドタイプとその動作を理解することは、効果的なフォーム自動化のために不可欠です。 AcroFormsの構造はプログラムによる操作に適しています。 各フィールドには名前と値があるため、ドキュメント内のすべてのフィールドを繰り返し処理し、現在の値を読み取り、簡単なコードを使用して新しい値を設定することができます。 この予測可能な構造により、本ガイドで扱う自動化ワークフローが可能になります。 PDFを開き、すべてのフォームフィールドを一覧表示するにはどうすればよいですか? プログラムでPDFフォームに入力する前に、その構造を理解する必要があります。 ドキュメントを開き、フィールドを列挙すると、フィールドタイプや既存のコンテンツとともに、値を設定するために使用するフィールド名が表示されます。 この発見ステップは、内部フィールド構造に関する文書がないサードパーティのフォームを使用する場合に特に役立ちます。 入力PDF この例では、application-form.pdfという既存のPDFフォームを使用します。 翻訳対象は、対話型のフォームフィールドを含むPDFであれば何でもかまいません。政府の書式、お客様の組織のアプリケーションテンプレート、またはお客様が処理する必要のあるサードパーティのドキュメントなどです。 以下のコードは、このファイルを読み込み、すべての対話型フォームフィールドを繰り返し処理します。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/list-form-fields.cs using IronPdf; // Load an existing PDF form document PdfDocument pdfForm = PdfDocument.FromFile("application-form.pdf"); // Access the form object and iterate through all fields foreach (var field in pdfForm.Form) { // Access field properties: field.Name, field.Type, field.Value, field.ReadOnly } Imports IronPdf ' Load an existing PDF form document Dim pdfForm As PdfDocument = PdfDocument.FromFile("application-form.pdf") ' Access the form object and iterate through all fields For Each field In pdfForm.Form ' Access field properties: field.Name, field.Type, field.Value, field.ReadOnly Next $vbLabelText $csharpLabel PdfDocument.FromFile()メソッドは、PDFをメモリにロードし、Formコレクションは、ドキュメント内のすべてのインタラクティブフィールドへのアクセスを提供します。 各フィールドは、Name(プログラムによるアクセスに使用される一意の識別子)、Type(テキストフィールド、チェックボックス、ラジオボタン、ドロップダウン、シグネチャ)、Value(現在のコンテンツ)、ReadOnly(フィールドを変更できるかどうか)といったプロパティを公開しています。 不慣れなフォームに対してこの列挙を実行すると、それを正しく埋めるコードを書くために必要な完全なフィールド・インベントリが得られます。 多くのフィールドを持つフォームの場合、タイプでフィルタリングしたり、特定のフィールド名を検索したりすることができます。 FindFormField メソッドは、正確な名前でフィールドを検索し、一致するものがない場合は例外をスローします。 フィールドが存在するかどうか確信が持てない場合は、try-catchブロックを使用してください。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/find-form-field.cs using IronPdf; PdfDocument pdfForm = PdfDocument.FromFile("employee-onboarding.pdf"); // Find specific fields by name - use try-catch for fields that may not exist try { var firstNameField = pdfForm.Form.FindFormField("firstName"); // Use firstNameField.Value to get or set the field value } catch (Exception) { // Field not found in this document } // For fields you know exist, you can access them directly var lastNameField = pdfForm.Form.FindFormField("lastName"); var departmentField = pdfForm.Form.FindFormField("department"); Imports IronPdf Dim pdfForm As PdfDocument = PdfDocument.FromFile("employee-onboarding.pdf") ' Find specific fields by name - use try-catch for fields that may not exist Try Dim firstNameField = pdfForm.Form.FindFormField("firstName") ' Use firstNameField.Value to get or set the field value Catch ex As Exception ' Field not found in this document End Try ' For fields you know exist, you can access them directly Dim lastNameField = pdfForm.Form.FindFormField("lastName") Dim departmentField = pdfForm.Form.FindFormField("department") $vbLabelText $csharpLabel フォームフィールド値の読み取りの詳細については、Extract PDF Form Fields in C#ガイドを参照してください。 テキストフィールド、チェックボックス、ドロップダウンをどのように入力しますか? PDFフォームのフィールド名がわかれば、それを埋めるのに必要なコードは数行だけです。 各フィールドタイプは、特定の形式で値を受け入れます。 テキストフィールドは文字列値を直接受け取ります。 チェックボックスは、チェックされた状態には"Yes"、チェックされていない状態には"No"を使用します。 ラジオボタンは、選択されたオプションの値を受け入れます。 ドロップダウンフィールドは、事前に定義された選択肢のリストから任意の値を受け入れます。 入力PDF 顧客登録フォーム(customer-registration.pdf)には、名前、電子メール、電話、住所のテキストフィールドがあります; ニュースレターのオプトイン用チェックボックス また、アカウントタイプを選択するためのドロップダウンも必要です。 この例では、フォームをロードし、各フィールドにサンプルの顧客データを入力します。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/fill-text-checkbox-dropdown.cs using IronPdf; // Load the form document PdfDocument pdf = PdfDocument.FromFile("customer-registration.pdf"); // Fill text fields with customer information pdf.Form.FindFormField("fullName").Value = "Sarah Johnson"; pdf.Form.FindFormField("email").Value = "sarah.johnson@example.com"; pdf.Form.FindFormField("phone").Value = "(555) 123-4567"; pdf.Form.FindFormField("address").Value = "742 Evergreen Terrace\r\nSpringfield, IL 62701"; // Check a checkbox field pdf.Form.FindFormField("newsletterOptIn").Value = "Yes"; // Select an option from a dropdown pdf.Form.FindFormField("accountType").Value = "Premium"; // Save the filled form pdf.SaveAs("customer-registration-completed.pdf"); Imports IronPdf ' Load the form document Dim pdf As PdfDocument = PdfDocument.FromFile("customer-registration.pdf") ' Fill text fields with customer information pdf.Form.FindFormField("fullName").Value = "Sarah Johnson" pdf.Form.FindFormField("email").Value = "sarah.johnson@example.com" pdf.Form.FindFormField("phone").Value = "(555) 123-4567" pdf.Form.FindFormField("address").Value = "742 Evergreen Terrace" & vbCrLf & "Springfield, IL 62701" ' Check a checkbox field pdf.Form.FindFormField("newsletterOptIn").Value = "Yes" ' Select an option from a dropdown pdf.Form.FindFormField("accountType").Value = "Premium" ' Save the filled form pdf.SaveAs("customer-registration-completed.pdf") $vbLabelText $csharpLabel サンプル出力 FindFormField()メソッドは、正確な名前で各フィールドを検索し、Valueプロパティを設定することで、フィールドの内容を入力します。 アドレス・フィールドの改行にrrnが使われていることに注目してください。 複数行テキストエリアは、これらのエスケープシーケンスを正しく解釈するため、アドレスやコメントなど、複数行にまたがるコンテンツの書式設定が可能です。 チェックボックスは、"Yes "と "No "の値でチェック状態が切り替わり、ドロップダウンは、あらかじめ定義されたオプションのいずれかに一致する任意の値を受け入れます。 ラジオボタンを使用するには、グループ内のすべてのボタンが同じフィールド名を共有することを理解する必要があります。 値を設定すると、一致するオプションが選択され、そのグループ内の他のすべての選択が解除されます。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/radio-button-group.cs using IronPdf; PdfDocument pdf = PdfDocument.FromFile("survey-form.pdf"); // Get a radio button group and examine its options var satisfactionField = pdf.Form.FindFormField("satisfactionLevel"); // Access available options from the radio button annotations foreach (var annotation in satisfactionField.Annotations) { // annotation.OnAppearance contains the option value } // Select one option from the group satisfactionField.Value = "Very Satisfied"; pdf.SaveAs("survey-completed.pdf"); Imports IronPdf Dim pdf As PdfDocument = PdfDocument.FromFile("survey-form.pdf") ' Get a radio button group and examine its options Dim satisfactionField = pdf.Form.FindFormField("satisfactionLevel") ' Access available options from the radio button annotations For Each annotation In satisfactionField.Annotations ' annotation.OnAppearance contains the option value Next ' Select one option from the group satisfactionField.Value = "Very Satisfied" pdf.SaveAs("survey-completed.pdf") $vbLabelText $csharpLabel ドロップダウンフィールドも同様に機能します。 値を設定する前に、Choices プロパティで利用可能な選択肢を調べることができます。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/dropdown-choices.cs using IronPdf; PdfDocument pdf = PdfDocument.FromFile("order-form.pdf"); var shippingMethod = pdf.Form.FindFormField("shippingMethod"); // Access all available shipping options via shippingMethod.Choices // Select express shipping shippingMethod.Value = "Express (2-3 days)"; pdf.SaveAs("order-form-filled.pdf"); Imports IronPdf Dim pdf As PdfDocument = PdfDocument.FromFile("order-form.pdf") Dim shippingMethod = pdf.Form.FindFormField("shippingMethod") ' Access all available shipping options via shippingMethod.Choices ' Select express shipping shippingMethod.Value = "Express (2-3 days)" pdf.SaveAs("order-form-filled.pdf") $vbLabelText $csharpLabel すべてのフォーム フィールド タイプを入力するための包括的なガイドについては、Fill & Edit PDF Forms in C# および Programmatically Fill PDF Forms を参照してください。 データオブジェクトと辞書からフォームに入力するには? 実際のアプリケーションでは、フォームの値をハードコードすることはほとんどありません。 データは、データベース、APIレスポンス、ユーザー入力、または設定ファイルから得られます。 このデータを辞書やカスタムオブジェクトに整理することで、フォーム入力コードの保守性と再利用性が高まります。 入力PDF ローン申込書(loan-application.pdf)には、氏名、生年月日、SSN、住所欄、雇用形態、年収、条件同意のチェックボックスがあります。 以下のコードは、Dictionary<string, string> に格納されたデータを使ってフォームを埋めています。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/fill-from-dictionary.cs using IronPdf; using System.Collections.Generic; // Form data stored in a dictionary var formData = new Dictionary<string, string> { { "applicantName", "Michael Chen" }, { "dateOfBirth", "1985-03-15" }, { "ssn", "XXX-XX-1234" }, { "streetAddress", "456 Oak Avenue" }, { "city", "Portland" }, { "state", "OR" }, { "zipCode", "97201" }, { "employmentStatus", "Full-Time" }, { "annualIncome", "75000" }, { "agreeToTerms", "Yes" } }; PdfDocument pdf = PdfDocument.FromFile("loan-application.pdf"); // Iterate through the dictionary and fill matching fields foreach (var entry in formData) { var field = pdf.Form.FindFormField(entry.Key); if (field != null) { field.Value = entry.Value; } } pdf.SaveAs("loan-application-filled.pdf"); Imports IronPdf Imports System.Collections.Generic ' Form data stored in a dictionary Dim formData As New Dictionary(Of String, String) From { {"applicantName", "Michael Chen"}, {"dateOfBirth", "1985-03-15"}, {"ssn", "XXX-XX-1234"}, {"streetAddress", "456 Oak Avenue"}, {"city", "Portland"}, {"state", "OR"}, {"zipCode", "97201"}, {"employmentStatus", "Full-Time"}, {"annualIncome", "75000"}, {"agreeToTerms", "Yes"} } Dim pdf As PdfDocument = PdfDocument.FromFile("loan-application.pdf") ' Iterate through the dictionary and fill matching fields For Each entry In formData Dim field = pdf.Form.FindFormField(entry.Key) If field IsNot Nothing Then field.Value = entry.Value End If Next pdf.SaveAs("loan-application-filled.pdf") $vbLabelText $csharpLabel サンプル出力 辞書ベースのアプローチは、データとロジックをきれいに分離します。 foreachループは、各キーと値のペアを繰り返し、FindFormField()を使用して対応するPDFフィールドを見つけ、フィールドが存在すれば値を代入します。 ヌルチェック(if (field != null))は、辞書にドキュメント内のどのフィールドとも一致しないキーが含まれる場合に例外が発生するのを防ぎます。 これは、フォームに存在しない余分なフィールドを含むデータソースを扱う場合に特に役立ちます。 より複雑なシナリオの場合、フォームデータを表すクラスを定義し、リフレクションやマッピング関数を使用してプロパティ値をフォームフィールドに転送することもできます。 using IronPdf; using System; // Define a strongly-typed class for the form data public class EmployeeRecord { public string FirstName { get; set; } public string LastName { get; set; } public string EmployeeId { get; set; } public string Department { get; set; } public DateTime HireDate { get; set; } public string JobTitle { get; set; } public bool DirectDeposit { get; set; } } public class FormFiller { public void FillEmployeeForm(EmployeeRecord employee, string templatePath, string outputPath) { PdfDocument pdf = PdfDocument.FromFile(templatePath); // Map object properties to form fields pdf.Form.FindFormField("firstName").Value = employee.FirstName; pdf.Form.FindFormField("lastName").Value = employee.LastName; pdf.Form.FindFormField("employeeId").Value = employee.EmployeeId; pdf.Form.FindFormField("department").Value = employee.Department; pdf.Form.FindFormField("hireDate").Value = employee.HireDate.ToString("MM/dd/yyyy"); pdf.Form.FindFormField("jobTitle").Value = employee.JobTitle; pdf.Form.FindFormField("directDeposit").Value = employee.DirectDeposit ? "Yes" : "No"; pdf.SaveAs(outputPath); } } // Usage example class Program { static void Main() { var employee = new EmployeeRecord { FirstName = "Jennifer", LastName = "Martinez", EmployeeId = "EMP-2024-0892", Department = "Engineering", HireDate = new DateTime(2024, 6, 15), JobTitle = "Senior Developer", DirectDeposit = true }; var filler = new FormFiller(); filler.FillEmployeeForm(employee, "new-hire-form.pdf", "jennifer-martinez-onboarding.pdf"); } } using IronPdf; using System; // Define a strongly-typed class for the form data public class EmployeeRecord { public string FirstName { get; set; } public string LastName { get; set; } public string EmployeeId { get; set; } public string Department { get; set; } public DateTime HireDate { get; set; } public string JobTitle { get; set; } public bool DirectDeposit { get; set; } } public class FormFiller { public void FillEmployeeForm(EmployeeRecord employee, string templatePath, string outputPath) { PdfDocument pdf = PdfDocument.FromFile(templatePath); // Map object properties to form fields pdf.Form.FindFormField("firstName").Value = employee.FirstName; pdf.Form.FindFormField("lastName").Value = employee.LastName; pdf.Form.FindFormField("employeeId").Value = employee.EmployeeId; pdf.Form.FindFormField("department").Value = employee.Department; pdf.Form.FindFormField("hireDate").Value = employee.HireDate.ToString("MM/dd/yyyy"); pdf.Form.FindFormField("jobTitle").Value = employee.JobTitle; pdf.Form.FindFormField("directDeposit").Value = employee.DirectDeposit ? "Yes" : "No"; pdf.SaveAs(outputPath); } } // Usage example class Program { static void Main() { var employee = new EmployeeRecord { FirstName = "Jennifer", LastName = "Martinez", EmployeeId = "EMP-2024-0892", Department = "Engineering", HireDate = new DateTime(2024, 6, 15), JobTitle = "Senior Developer", DirectDeposit = true }; var filler = new FormFiller(); filler.FillEmployeeForm(employee, "new-hire-form.pdf", "jennifer-martinez-onboarding.pdf"); } } Imports IronPdf Imports System ' Define a strongly-typed class for the form data Public Class EmployeeRecord Public Property FirstName As String Public Property LastName As String Public Property EmployeeId As String Public Property Department As String Public Property HireDate As DateTime Public Property JobTitle As String Public Property DirectDeposit As Boolean End Class Public Class FormFiller Public Sub FillEmployeeForm(employee As EmployeeRecord, templatePath As String, outputPath As String) Dim pdf As PdfDocument = PdfDocument.FromFile(templatePath) ' Map object properties to form fields pdf.Form.FindFormField("firstName").Value = employee.FirstName pdf.Form.FindFormField("lastName").Value = employee.LastName pdf.Form.FindFormField("employeeId").Value = employee.EmployeeId pdf.Form.FindFormField("department").Value = employee.Department pdf.Form.FindFormField("hireDate").Value = employee.HireDate.ToString("MM/dd/yyyy") pdf.Form.FindFormField("jobTitle").Value = employee.JobTitle pdf.Form.FindFormField("directDeposit").Value = If(employee.DirectDeposit, "Yes", "No") pdf.SaveAs(outputPath) End Sub End Class ' Usage example Module Program Sub Main() Dim employee As New EmployeeRecord With { .FirstName = "Jennifer", .LastName = "Martinez", .EmployeeId = "EMP-2024-0892", .Department = "Engineering", .HireDate = New DateTime(2024, 6, 15), .JobTitle = "Senior Developer", .DirectDeposit = True } Dim filler As New FormFiller() filler.FillEmployeeForm(employee, "new-hire-form.pdf", "jennifer-martinez-onboarding.pdf") End Sub End Module $vbLabelText $csharpLabel サンプル出力 入力前にどのようにフォームデータを検証しますか? PDFフォームに入力する前にデータを検証することで、エラーを早期に発見し、要件に適合したドキュメントを作成することができます。 PDF フォームには独自の検証ルールを含めることができますが、そのようなルールだけに頼っていると、エラーの表面化は処理の最後になってしまいます。 C#コードにバリデーションを実装することで、よりコントロールしやすくなり、エラーメッセージも改善されます。 using IronPdf; using System; using System.Collections.Generic; using System.Text.RegularExpressions; public class FormValidationResult { public bool IsValid { get; set; } public List<string> Errors { get; set; } = new List<string>(); } public class FormValidator { public FormValidationResult ValidateApplicationData(Dictionary<string, string> formData, PdfDocument pdf) { var result = new FormValidationResult { IsValid = true }; // Check that all required fields have values var requiredFields = new[] { "applicantName", "email", "phone", "ssn" }; foreach (var fieldName in requiredFields) { if (!formData.ContainsKey(fieldName) || string.IsNullOrWhiteSpace(formData[fieldName])) { result.Errors.Add($"Required field '{fieldName}' is missing or empty"); result.IsValid = false; } } // Validate email format if (formData.ContainsKey("email")) { var emailPattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$"; if (!Regex.IsMatch(formData["email"], emailPattern)) { result.Errors.Add("Email address format is invalid"); result.IsValid = false; } } // Validate phone number format if (formData.ContainsKey("phone")) { var phonePattern = @"^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$"; if (!Regex.IsMatch(formData["phone"], phonePattern)) { result.Errors.Add("Phone number format is invalid"); result.IsValid = false; } } // Verify that form fields exist in the PDF foreach (var fieldName in formData.Keys) { try { var field = pdf.Form.FindFormField(fieldName); // Field exists } catch { result.Errors.Add($"Field '{fieldName}' does not exist in the PDF form"); result.IsValid = false; } } // Check dropdown values against available choices if (formData.ContainsKey("state")) { try { var stateField = pdf.Form.FindFormField("state"); if (stateField.Choices != null) { bool validChoice = false; foreach (var choice in stateField.Choices) { if (choice == formData["state"]) { validChoice = true; break; } } if (!validChoice) { result.Errors.Add($"'{formData["state"]}' is not a valid option for the state field"); result.IsValid = false; } } } catch { // State field doesn't exist, skip validation } } return result; } } // Usage example class Program { static void Main() { var formData = new Dictionary<string, string> { { "applicantName", "John Doe" }, { "email", "invalid-email" }, { "phone", "555-1234" }, { "state", "XX" } }; PdfDocument pdf = PdfDocument.FromFile("application.pdf"); var validator = new FormValidator(); var validationResult = validator.ValidateApplicationData(formData, pdf); if (validationResult.IsValid) { // Proceed with form fill } else { // Handle validation errors in validationResult.Errors } } } using IronPdf; using System; using System.Collections.Generic; using System.Text.RegularExpressions; public class FormValidationResult { public bool IsValid { get; set; } public List<string> Errors { get; set; } = new List<string>(); } public class FormValidator { public FormValidationResult ValidateApplicationData(Dictionary<string, string> formData, PdfDocument pdf) { var result = new FormValidationResult { IsValid = true }; // Check that all required fields have values var requiredFields = new[] { "applicantName", "email", "phone", "ssn" }; foreach (var fieldName in requiredFields) { if (!formData.ContainsKey(fieldName) || string.IsNullOrWhiteSpace(formData[fieldName])) { result.Errors.Add($"Required field '{fieldName}' is missing or empty"); result.IsValid = false; } } // Validate email format if (formData.ContainsKey("email")) { var emailPattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$"; if (!Regex.IsMatch(formData["email"], emailPattern)) { result.Errors.Add("Email address format is invalid"); result.IsValid = false; } } // Validate phone number format if (formData.ContainsKey("phone")) { var phonePattern = @"^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$"; if (!Regex.IsMatch(formData["phone"], phonePattern)) { result.Errors.Add("Phone number format is invalid"); result.IsValid = false; } } // Verify that form fields exist in the PDF foreach (var fieldName in formData.Keys) { try { var field = pdf.Form.FindFormField(fieldName); // Field exists } catch { result.Errors.Add($"Field '{fieldName}' does not exist in the PDF form"); result.IsValid = false; } } // Check dropdown values against available choices if (formData.ContainsKey("state")) { try { var stateField = pdf.Form.FindFormField("state"); if (stateField.Choices != null) { bool validChoice = false; foreach (var choice in stateField.Choices) { if (choice == formData["state"]) { validChoice = true; break; } } if (!validChoice) { result.Errors.Add($"'{formData["state"]}' is not a valid option for the state field"); result.IsValid = false; } } } catch { // State field doesn't exist, skip validation } } return result; } } // Usage example class Program { static void Main() { var formData = new Dictionary<string, string> { { "applicantName", "John Doe" }, { "email", "invalid-email" }, { "phone", "555-1234" }, { "state", "XX" } }; PdfDocument pdf = PdfDocument.FromFile("application.pdf"); var validator = new FormValidator(); var validationResult = validator.ValidateApplicationData(formData, pdf); if (validationResult.IsValid) { // Proceed with form fill } else { // Handle validation errors in validationResult.Errors } } } Imports IronPdf Imports System Imports System.Collections.Generic Imports System.Text.RegularExpressions Public Class FormValidationResult Public Property IsValid As Boolean Public Property Errors As List(Of String) = New List(Of String)() End Class Public Class FormValidator Public Function ValidateApplicationData(formData As Dictionary(Of String, String), pdf As PdfDocument) As FormValidationResult Dim result As New FormValidationResult With {.IsValid = True} ' Check that all required fields have values Dim requiredFields = New String() {"applicantName", "email", "phone", "ssn"} For Each fieldName In requiredFields If Not formData.ContainsKey(fieldName) OrElse String.IsNullOrWhiteSpace(formData(fieldName)) Then result.Errors.Add($"Required field '{fieldName}' is missing or empty") result.IsValid = False End If Next ' Validate email format If formData.ContainsKey("email") Then Dim emailPattern = "^[^@\s]+@[^@\s]+\.[^@\s]+$" If Not Regex.IsMatch(formData("email"), emailPattern) Then result.Errors.Add("Email address format is invalid") result.IsValid = False End If End If ' Validate phone number format If formData.ContainsKey("phone") Then Dim phonePattern = "^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$" If Not Regex.IsMatch(formData("phone"), phonePattern) Then result.Errors.Add("Phone number format is invalid") result.IsValid = False End If End If ' Verify that form fields exist in the PDF For Each fieldName In formData.Keys Try Dim field = pdf.Form.FindFormField(fieldName) ' Field exists Catch result.Errors.Add($"Field '{fieldName}' does not exist in the PDF form") result.IsValid = False End Try Next ' Check dropdown values against available choices If formData.ContainsKey("state") Then Try Dim stateField = pdf.Form.FindFormField("state") If stateField.Choices IsNot Nothing Then Dim validChoice = False For Each choice In stateField.Choices If choice = formData("state") Then validChoice = True Exit For End If Next If Not validChoice Then result.Errors.Add($"'{formData("state")}' is not a valid option for the state field") result.IsValid = False End If End If Catch ' State field doesn't exist, skip validation End Try End If Return result End Function End Class ' Usage example Class Program Shared Sub Main() Dim formData = New Dictionary(Of String, String) From { {"applicantName", "John Doe"}, {"email", "invalid-email"}, {"phone", "555-1234"}, {"state", "XX"} } Dim pdf As PdfDocument = PdfDocument.FromFile("application.pdf") Dim validator As New FormValidator() Dim validationResult = validator.ValidateApplicationData(formData, pdf) If validationResult.IsValid Then ' Proceed with form fill Else ' Handle validation errors in validationResult.Errors End If End Sub End Class $vbLabelText $csharpLabel この検証レイヤーは、必須フィールドの欠落をチェックし、一般的なデータ型の書式パターンを検証し、指定されたドロップダウン値がフォームの選択肢に存在することを確認し、データ内のすべてのフィールド名が実際にPDF内に存在することを検証します。 フォームへの入力を試みる前にこれらの問題を検出することで、部分的な入力を防ぎ、デバッグをはるかに容易にします。 どのようにPDFフォームにテキスト入力フィールドを作成しますか? PDFフォームをゼロから作成することで、フォームの構造や外観を完全に制御することができます。 IronPdfのHTML-to-PDFレンダリングエンジンは標準的なHTMLフォーム要素を解釈し、PDFのAcroFormフィールドに変換します。 このアプローチでは、スタイリングにCSSを使用するなど、使い慣れたウェブ技術を使用してフォームをデザインできます。 フォームの作成に関する完全なガイドは、C#でPDFフォームを作成するをご覧ください。 次のコードは、HTMLとCSSを使ってフォームの構造とスタイルを定義し、テキスト入力フィールドとtextareaを持つ顧客フィードバックフォームを作成します。 出力されるPDFには、ユーザーがどのPDFリーダーでも入力できるように、入力可能なフォームフィールドが含まれています。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-text-input-form.cs using IronPdf; // Define the form layout using HTML with form elements string formHtml = @" <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px; } h1 { color: #333; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; font-weight: bold; color: #555; } input[type='text'], textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; } textarea { height: 100px; resize: none; } .required::after { content: ' *'; color: red; } </style> </head> <body> <h1>Customer Feedback Form</h1> <form> <div class='form-group'> <label class='required'>Full Name</label> <input type='text' name='customerName' /> </div> <div class='form-group'> <label class='required'>Email Address</label> <input type='text' name='customerEmail' /> </div> <div class='form-group'> <label>Phone Number</label> <input type='text' name='customerPhone' /> </div> <div class='form-group'> <label>Order Number</label> <input type='text' name='orderNumber' /> </div> <div class='form-group'> <label class='required'>Your Feedback</label> <textarea name='feedbackText'></textarea> </div> </form> </body> </html>"; // Create the renderer and enable form creation ChromePdfRenderer renderer = new ChromePdfRenderer(); renderer.RenderingOptions.CreatePdfFormsFromHtml = true; // Render the HTML to a PDF with interactive form fields PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml); pdf.SaveAs("customer-feedback-form.pdf"); Imports IronPdf ' Define the form layout using HTML with form elements Dim formHtml As String = " <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px; } h1 { color: #333; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; font-weight: bold; color: #555; } input[type='text'], textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; } textarea { height: 100px; resize: none; } .required::after { content: ' *'; color: red; } </style> </head> <body> <h1>Customer Feedback Form</h1> <form> <div class='form-group'> <label class='required'>Full Name</label> <input type='text' name='customerName' /> </div> <div class='form-group'> <label class='required'>Email Address</label> <input type='text' name='customerEmail' /> </div> <div class='form-group'> <label>Phone Number</label> <input type='text' name='customerPhone' /> </div> <div class='form-group'> <label>Order Number</label> <input type='text' name='orderNumber' /> </div> <div class='form-group'> <label class='required'>Your Feedback</label> <textarea name='feedbackText'></textarea> </div> </form> </body> </html>" ' Create the renderer and enable form creation Dim renderer As New ChromePdfRenderer() renderer.RenderingOptions.CreatePdfFormsFromHtml = True ' Render the HTML to a PDF with interactive form fields Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml) pdf.SaveAs("customer-feedback-form.pdf") $vbLabelText $csharpLabel サンプル出力 重要な設定は、RenderingOptionsのCreatePdfFormsFromHtml = trueで、これはChromePdfRendererにHTMLの<input>と<textarea>要素を同等のPDF AcroFormに変換するように指示します。 この設定がないと、入力はインタラクティブ性のない静的なビジュアル要素としてレンダリングされます。 各入力要素のname属性は、結果のPDFのフィールド名になります。 これらは、プログラムでフォームに入力する際に使用する識別子です。 フォーム入力コードが読みやすく、保守しやすいように、説明的で一貫性のある名前を選んでください。 HTMLからPDFへの変換については、C#でHTMLをPDFに変換するチュートリアルをご覧ください。 PDFフォームにチェックボックスとラジオボタンを追加するにはどうすればよいですか? チェックボックスとラジオボタンは、選択ベースの入力をキャプチャします。 HTMLでは、チェックボックスはtype='checkbox'を使用し、ラジオボタンはtype='radio'を使用します。 同じ名前の属性を共有するラジオボタンは、自動的に相互に排他的なグループを形成します。 このスニペットは、食事の好みのための複数のチェックボックスと、チケットタイプの選択のためのラジオボタンを備えたイベント登録フォームを作成します。 HTML構造はフォームのレイアウトを定義し、CSSはスタイリングを提供します。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-checkbox-radio-form.cs using IronPdf; string formHtml = @" <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px; } h1 { color: #2c3e50; } h2 { color: #34495e; font-size: 16px; margin-top: 25px; } .option-group { margin: 10px 0; } .option-group label { margin-left: 8px; cursor: pointer; } .checkbox-section { background: #f9f9f9; padding: 15px; border-radius: 5px; margin: 15px 0; } </style> </head> <body> <h1>Event Registration</h1> <form> <h2>Select Your Ticket Type</h2> <div class='option-group'> <input type='radio' name='ticketType' value='General' id='general' /> <label for='general'>General Admission ($50)</label> </div> <div class='option-group'> <input type='radio' name='ticketType' value='VIP' id='vip' /> <label for='vip'>VIP Access ($150)</label> </div> <div class='option-group'> <input type='radio' name='ticketType' value='Premium' id='premium' /> <label for='premium'>Premium Package ($300)</label> </div> <h2>Which Sessions Will You Attend?</h2> <div class='checkbox-section'> <div class='option-group'> <input type='checkbox' name='sessionMorning' value='Yes' id='morning' /> <label for='morning'>Morning Keynote (9:00 AM)</label> </div> <div class='option-group'> <input type='checkbox' name='sessionWorkshop' value='Yes' id='workshop' /> <label for='workshop'>Afternoon Workshop (2:00 PM)</label> </div> <div class='option-group'> <input type='checkbox' name='sessionNetworking' value='Yes' id='networking' /> <label for='networking'>Evening Networking (6:00 PM)</label> </div> </div> <h2>Dietary Requirements</h2> <div class='option-group'> <input type='checkbox' name='dietVegetarian' value='Yes' id='vegetarian' /> <label for='vegetarian'>Vegetarian</label> </div> <div class='option-group'> <input type='checkbox' name='dietVegan' value='Yes' id='vegan' /> <label for='vegan'>Vegan</label> </div> <div class='option-group'> <input type='checkbox' name='dietGlutenFree' value='Yes' id='glutenfree' /> <label for='glutenfree'>Gluten-Free</label> </div> </form> </body> </html>"; ChromePdfRenderer renderer = new ChromePdfRenderer(); renderer.RenderingOptions.CreatePdfFormsFromHtml = true; PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml); pdf.SaveAs("event-registration-form.pdf"); Imports IronPdf Dim formHtml As String = " <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px; } h1 { color: #2c3e50; } h2 { color: #34495e; font-size: 16px; margin-top: 25px; } .option-group { margin: 10px 0; } .option-group label { margin-left: 8px; cursor: pointer; } .checkbox-section { background: #f9f9f9; padding: 15px; border-radius: 5px; margin: 15px 0; } </style> </head> <body> <h1>Event Registration</h1> <form> <h2>Select Your Ticket Type</h2> <div class='option-group'> <input type='radio' name='ticketType' value='General' id='general' /> <label for='general'>General Admission ($50)</label> </div> <div class='option-group'> <input type='radio' name='ticketType' value='VIP' id='vip' /> <label for='vip'>VIP Access ($150)</label> </div> <div class='option-group'> <input type='radio' name='ticketType' value='Premium' id='premium' /> <label for='premium'>Premium Package ($300)</label> </div> <h2>Which Sessions Will You Attend?</h2> <div class='checkbox-section'> <div class='option-group'> <input type='checkbox' name='sessionMorning' value='Yes' id='morning' /> <label for='morning'>Morning Keynote (9:00 AM)</label> </div> <div class='option-group'> <input type='checkbox' name='sessionWorkshop' value='Yes' id='workshop' /> <label for='workshop'>Afternoon Workshop (2:00 PM)</label> </div> <div class='option-group'> <input type='checkbox' name='sessionNetworking' value='Yes' id='networking' /> <label for='networking'>Evening Networking (6:00 PM)</label> </div> </div> <h2>Dietary Requirements</h2> <div class='option-group'> <input type='checkbox' name='dietVegetarian' value='Yes' id='vegetarian' /> <label for='vegetarian'>Vegetarian</label> </div> <div class='option-group'> <input type='checkbox' name='dietVegan' value='Yes' id='vegan' /> <label for='vegan'>Vegan</label> </div> <div class='option-group'> <input type='checkbox' name='dietGlutenFree' value='Yes' id='glutenfree' /> <label for='glutenfree'>Gluten-Free</label> </div> </form> </body> </html>" Dim renderer As New ChromePdfRenderer() renderer.RenderingOptions.CreatePdfFormsFromHtml = True Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml) pdf.SaveAs("event-registration-form.pdf") $vbLabelText $csharpLabel サンプル出力 3つのラジオボタンがname='ticketType'を共有し、1つのオプションしか選択できないグループを作成していることに注目してください。 各チェックボックスは、どのような組み合わせでも選択できる独立した選択肢を表すため、固有の名前が付けられています。 PDFフォームでドロップダウンリストを作成するには? ドロップダウンリストは、複数の定義済みオプションを提供しながら、スペースを節約します。 HTMLの<select>要素と<option>の子要素は、PDFのコンボボックスフィールドを作成します。 ユーザーは、フィールドをクリックして選択肢のリストを表示し、1つを選択します。 ここでは、部署選択、経験レベル、開始日の希望、勤務地など、複数のドロップダウンメニューを備えた求人応募フォームを作成します。 各 <select> 要素には、定義済みの <option> 値が含まれています。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-dropdown-form.cs using IronPdf; string formHtml = @" <!DOCTYPE html> <html> <head> <style> body { font-family: 'Segoe UI', Arial, sans-serif; max-width: 650px; margin: 30px auto; padding: 25px; background: #fff; } h1 { color: #1a5f7a; margin-bottom: 30px; } .form-row { display: flex; gap: 20px; margin-bottom: 20px; } .form-group { flex: 1; } label { display: block; margin-bottom: 6px; font-weight: 600; color: #333; } select, input[type='text'] { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; box-sizing: border-box; } </style> </head> <body> <h1>Job Application Form</h1> <form> <div class='form-row'> <div class='form-group'> <label>First Name</label> <input type='text' name='firstName' /> </div> <div class='form-group'> <label>Last Name</label> <input type='text' name='lastName' /> </div> </div> <div class='form-row'> <div class='form-group'> <label>Department</label> <select name='department'> <option value=''>Select Department</option> <option value='Engineering'>Engineering</option> <option value='Marketing'>Marketing</option> <option value='Sales'>Sales</option> <option value='Human Resources'>Human Resources</option> <option value='Finance'>Finance</option> <option value='Operations'>Operations</option> </select> </div> <div class='form-group'> <label>Experience Level</label> <select name='experienceLevel'> <option value=''>Select Level</option> <option value='Entry'>Entry Level (0-2 years)</option> <option value='Mid'>Mid Level (3-5 years)</option> <option value='Senior'>Senior (6-10 years)</option> <option value='Executive'>Executive (10+ years)</option> </select> </div> </div> <div class='form-row'> <div class='form-group'> <label>Preferred Start Date</label> <select name='startDate'> <option value='Immediate'>Immediately</option> <option value='TwoWeeks'>In 2 weeks</option> <option value='OneMonth'>In 1 month</option> <option value='Flexible'>Flexible</option> </select> </div> <div class='form-group'> <label>Work Location Preference</label> <select name='workLocation'> <option value='OnSite'>On-Site</option> <option value='Remote'>Fully Remote</option> <option value='Hybrid'>Hybrid</option> </select> </div> </div> </form> </body> </html>"; ChromePdfRenderer renderer = new ChromePdfRenderer(); renderer.RenderingOptions.CreatePdfFormsFromHtml = true; PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml); pdf.SaveAs("job-application-form.pdf"); Imports IronPdf Dim formHtml As String = " <!DOCTYPE html> <html> <head> <style> body { font-family: 'Segoe UI', Arial, sans-serif; max-width: 650px; margin: 30px auto; padding: 25px; background: #fff; } h1 { color: #1a5f7a; margin-bottom: 30px; } .form-row { display: flex; gap: 20px; margin-bottom: 20px; } .form-group { flex: 1; } label { display: block; margin-bottom: 6px; font-weight: 600; color: #333; } select, input[type='text'] { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; box-sizing: border-box; } </style> </head> <body> <h1>Job Application Form</h1> <form> <div class='form-row'> <div class='form-group'> <label>First Name</label> <input type='text' name='firstName' /> </div> <div class='form-group'> <label>Last Name</label> <input type='text' name='lastName' /> </div> </div> <div class='form-row'> <div class='form-group'> <label>Department</label> <select name='department'> <option value=''>Select Department</option> <option value='Engineering'>Engineering</option> <option value='Marketing'>Marketing</option> <option value='Sales'>Sales</option> <option value='Human Resources'>Human Resources</option> <option value='Finance'>Finance</option> <option value='Operations'>Operations</option> </select> </div> <div class='form-group'> <label>Experience Level</label> <select name='experienceLevel'> <option value=''>Select Level</option> <option value='Entry'>Entry Level (0-2 years)</option> <option value='Mid'>Mid Level (3-5 years)</option> <option value='Senior'>Senior (6-10 years)</option> <option value='Executive'>Executive (10+ years)</option> </select> </div> </div> <div class='form-row'> <div class='form-group'> <label>Preferred Start Date</label> <select name='startDate'> <option value='Immediate'>Immediately</option> <option value='TwoWeeks'>In 2 weeks</option> <option value='OneMonth'>In 1 month</option> <option value='Flexible'>Flexible</option> </select> </div> <div class='form-group'> <label>Work Location Preference</label> <select name='workLocation'> <option value='OnSite'>On-Site</option> <option value='Remote'>Fully Remote</option> <option value='Hybrid'>Hybrid</option> </select> </div> </div> </form> </body> </html>" Dim renderer As New ChromePdfRenderer() renderer.RenderingOptions.CreatePdfFormsFromHtml = True Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml) pdf.SaveAs("job-application-form.pdf") $vbLabelText $csharpLabel サンプル出力 各select要素の最初の<option>(値は空)は、"Select Department "のようなプレースホルダプロンプトとして機能します。 PDFがレンダリングされると、これらはコンボボックスフィールドとなり、ユーザーがクリックすると選択肢の全リストが表示されます。 このフォームにプログラムで入力する場合は、フィールドの値を"エンジニアリング"や"リモート"など、オプションの値のいずれかと正確に一致するように設定してください。 PDFフォームに署名フィールドを追加するには? 署名フィールドは、ユーザーがデジタル署名を適用できる領域を指定します。 HTMLにはネイティブの署名入力タイプはありませんが、IronPdfを使えばどんなPDF文書にもプログラムで署名フィールドを追加することができます。 以下のコードでは、まずHTMLから秘密保持契約文書を作成し、次にSignatureFormFieldをページ上の特定の位置にプログラムで追加します。 署名欄はPDF座標(x、y、幅、高さをポイント単位で)を使って配置します。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/add-signature-field.cs using IronPdf; using IronSoftware.Forms; // First create the base form using HTML string formHtml = @" <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 30px; } h1 { text-align: center; color: #2c3e50; } .agreement-text { background: #f5f5f5; padding: 20px; border-radius: 5px; margin: 20px 0; line-height: 1.6; } .signature-section { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; } .signature-line { margin-top: 60px; border-bottom: 1px solid #333; width: 300px; } .signature-label { font-size: 12px; color: #666; margin-top: 5px; } .date-field { margin-top: 20px; } .date-field label { font-weight: bold; } .date-field input { padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 150px; } </style> </head> <body> <h1>Non-Disclosure Agreement</h1> <div class='agreement-text'> <p>By signing this document, I acknowledge that I have read and understood the terms of the Non-Disclosure Agreement dated as of the date signed below. I agree to maintain the confidentiality of all proprietary information disclosed to me during my engagement with the Company.</p> <p>I understand that violation of this agreement may result in legal action and that I am bound by these terms for a period of five (5) years from the date of signature.</p> </div> <div class='signature-section'> <div class='date-field'> <label>Date:</label> <input type='text' name='signatureDate' /> </div> <div class='signature-line'></div> <div class='signature-label'>Authorized Signature</div> </div> </body> </html>"; ChromePdfRenderer renderer = new ChromePdfRenderer(); renderer.RenderingOptions.CreatePdfFormsFromHtml = true; PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml); // Add a signature field programmatically // Parameters: name, page index, x position, y position, width, height SignatureFormField signatureField = new SignatureFormField( "authorizedSignature", // Field name 0, // Page index (first page) 72, // X position in points from left 200, // Y position in points from bottom 250, // Width in points 60 // Height in points ); pdf.Form.Add(signatureField); pdf.SaveAs("nda-with-signature.pdf"); Imports IronPdf Imports IronSoftware.Forms ' First create the base form using HTML Dim formHtml As String = " <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 30px; } h1 { text-align: center; color: #2c3e50; } .agreement-text { background: #f5f5f5; padding: 20px; border-radius: 5px; margin: 20px 0; line-height: 1.6; } .signature-section { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; } .signature-line { margin-top: 60px; border-bottom: 1px solid #333; width: 300px; } .signature-label { font-size: 12px; color: #666; margin-top: 5px; } .date-field { margin-top: 20px; } .date-field label { font-weight: bold; } .date-field input { padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 150px; } </style> </head> <body> <h1>Non-Disclosure Agreement</h1> <div class='agreement-text'> <p>By signing this document, I acknowledge that I have read and understood the terms of the Non-Disclosure Agreement dated as of the date signed below. I agree to maintain the confidentiality of all proprietary information disclosed to me during my engagement with the Company.</p> <p>I understand that violation of this agreement may result in legal action and that I am bound by these terms for a period of five (5) years from the date of signature.</p> </div> <div class='signature-section'> <div class='date-field'> <label>Date:</label> <input type='text' name='signatureDate' /> </div> <div class='signature-line'></div> <div class='signature-label'>Authorized Signature</div> </div> </body> </html>" Dim renderer As New ChromePdfRenderer() renderer.RenderingOptions.CreatePdfFormsFromHtml = True Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml) ' Add a signature field programmatically ' Parameters: name, page index, x position, y position, width, height Dim signatureField As New SignatureFormField( "authorizedSignature", ' Field name 0, ' Page index (first page) 72, ' X position in points from left 200, ' Y position in points from bottom 250, ' Width in points 60 ' Height in points ) pdf.Form.Add(signatureField) pdf.SaveAs("nda-with-signature.pdf") $vbLabelText $csharpLabel サンプル出力 SignatureFormFieldコンストラクタは6つのパラメータを取ります:フィールド名("authorizedSignature")、ページインデックス(最初のページは0)、ポイント単位の位置/サイズ(x=72, y=200, width=250, height=60)。 PDFの座標はページの左下隅を原点とし、1インチあたり72ポイントです。 電子署名に対応したPDFリーダーでは、署名欄がインタラクティブな領域として表示されます。 ユーザーは、このフィールドをクリックして、証明書ベースの署名を適用できます。 証明書ベースの署名を含むデジタル署名の詳細については、Digital Signature Guide for PDFs in C#とC# PDF デジタル署名の例を参照してください。 フォーム要素のスタイルと位置はどのように設定しますか? CSSは、HTMLからPDFを作成する際に、フォームの外観を広範囲に制御します。 色、フォント、枠線、間隔、レイアウトを調整して、組織のブランディングに合わせたり、特定のデザイン要件を満たすことができます。 このスニペットは、Googleフォント、グラデーション背景、2列レイアウトのためのCSSグリッド、角丸とフォーカス状態を持つカスタムフォームフィールドのスタイリングなどの高度なCSS機能を使用して、視覚的に洗練されたお問い合わせフォームを作成します。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/styled-form-css.cs using IronPdf; string formHtml = @" <!DOCTYPE html> <html> <head> <style> @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap'); body { font-family: 'Inter', sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; margin: 0; padding: 40px; box-sizing: border-box; } .form-container { background: white; max-width: 550px; margin: 0 auto; padding: 40px; border-radius: 12px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); } h1 { margin: 0 0 10px 0; color: #1a1a2e; font-weight: 600; } .subtitle { color: #666; margin-bottom: 30px; font-size: 14px; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 8px; font-weight: 600; color: #333; font-size: 14px; } input[type='text'], select, textarea { width: 100%; padding: 12px 16px; border: 2px solid #e1e1e1; border-radius: 8px; font-size: 14px; transition: border-color 0.3s; box-sizing: border-box; font-family: 'Inter', sans-serif; } input[type='text']:focus, select:focus, textarea:focus { border-color: #667eea; outline: none; } textarea { height: 120px; resize: none; } .checkbox-group { display: flex; align-items: center; gap: 10px; padding: 12px; background: #f8f9fa; border-radius: 8px; } .checkbox-group input[type='checkbox'] { width: 20px; height: 20px; accent-color: #667eea; } .two-column { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; } .footer-note { margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; font-size: 12px; color: #888; text-align: center; } </style> </head> <body> <div class='form-container'> <h1>Contact Request</h1> <p class='subtitle'>Fill out the form below and we will get back to you within 24 hours.</p> <form> <div class='two-column'> <div class='form-group'> <label>First Name</label> <input type='text' name='firstName' /> </div> <div class='form-group'> <label>Last Name</label> <input type='text' name='lastName' /> </div> </div> <div class='form-group'> <label>Email Address</label> <input type='text' name='email' /> </div> <div class='form-group'> <label>Subject</label> <select name='subject'> <option value=''>Choose a topic...</option> <option value='General'>General Inquiry</option> <option value='Support'>Technical Support</option> <option value='Sales'>Sales Question</option> <option value='Partnership'>Partnership Opportunity</option> </select> </div> <div class='form-group'> <label>Message</label> <textarea name='message'></textarea> </div> <div class='form-group'> <div class='checkbox-group'> <input type='checkbox' name='newsletter' value='Yes' id='newsletter' /> <label for='newsletter' style='margin: 0; font-weight: normal;'> Subscribe to our newsletter for updates </label> </div> </div> </form> <p class='footer-note'>Your information is secure and will never be shared with third parties.</p> </div> </body> </html>"; ChromePdfRenderer renderer = new ChromePdfRenderer(); renderer.RenderingOptions.CreatePdfFormsFromHtml = true; // Set page size and margins renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4; renderer.RenderingOptions.MarginTop = 0; renderer.RenderingOptions.MarginBottom = 0; renderer.RenderingOptions.MarginLeft = 0; renderer.RenderingOptions.MarginRight = 0; PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml); pdf.SaveAs("styled-contact-form.pdf"); Imports IronPdf Dim formHtml As String = " <!DOCTYPE html> <html> <head> <style> @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap'); body { font-family: 'Inter', sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; margin: 0; padding: 40px; box-sizing: border-box; } .form-container { background: white; max-width: 550px; margin: 0 auto; padding: 40px; border-radius: 12px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); } h1 { margin: 0 0 10px 0; color: #1a1a2e; font-weight: 600; } .subtitle { color: #666; margin-bottom: 30px; font-size: 14px; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 8px; font-weight: 600; color: #333; font-size: 14px; } input[type='text'], select, textarea { width: 100%; padding: 12px 16px; border: 2px solid #e1e1e1; border-radius: 8px; font-size: 14px; transition: border-color 0.3s; box-sizing: border-box; font-family: 'Inter', sans-serif; } input[type='text']:focus, select:focus, textarea:focus { border-color: #667eea; outline: none; } textarea { height: 120px; resize: none; } .checkbox-group { display: flex; align-items: center; gap: 10px; padding: 12px; background: #f8f9fa; border-radius: 8px; } .checkbox-group input[type='checkbox'] { width: 20px; height: 20px; accent-color: #667eea; } .two-column { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; } .footer-note { margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; font-size: 12px; color: #888; text-align: center; } </style> </head> <body> <div class='form-container'> <h1>Contact Request</h1> <p class='subtitle'>Fill out the form below and we will get back to you within 24 hours.</p> <form> <div class='two-column'> <div class='form-group'> <label>First Name</label> <input type='text' name='firstName' /> </div> <div class='form-group'> <label>Last Name</label> <input type='text' name='lastName' /> </div> </div> <div class='form-group'> <label>Email Address</label> <input type='text' name='email' /> </div> <div class='form-group'> <label>Subject</label> <select name='subject'> <option value=''>Choose a topic...</option> <option value='General'>General Inquiry</option> <option value='Support'>Technical Support</option> <option value='Sales'>Sales Question</option> <option value='Partnership'>Partnership Opportunity</option> </select> </div> <div class='form-group'> <label>Message</label> <textarea name='message'></textarea> </div> <div class='form-group'> <div class='checkbox-group'> <input type='checkbox' name='newsletter' value='Yes' id='newsletter' /> <label for='newsletter' style='margin: 0; font-weight: normal;'> Subscribe to our newsletter for updates </label> </div> </div> </form> <p class='footer-note'>Your information is secure and will never be shared with third parties.</p> </div> </body> </html>" Dim renderer As New ChromePdfRenderer() renderer.RenderingOptions.CreatePdfFormsFromHtml = True ' Set page size and margins renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4 renderer.RenderingOptions.MarginTop = 0 renderer.RenderingOptions.MarginBottom = 0 renderer.RenderingOptions.MarginLeft = 0 renderer.RenderingOptions.MarginRight = 0 Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml) pdf.SaveAs("styled-contact-form.pdf") $vbLabelText $csharpLabel サンプル出力 HTMLはGoogle FontsのInterフォントを使用し(@import url(...))、ボディにグラデーションの背景を適用し、角丸とドロップシャドウでフォームコンテナをスタイルします。 RenderingOptionsでは、すべての余白をゼロに設定し、グラデーションがページ全体を満たすようにA4用紙サイズを使用しています。 洗練されたスタイルにもかかわらず、すべてのフォームフィールドは、結果のPDFで完全にインタラクティブなままです。 ユーザーは、各フィールドをクリックして入力することができます。 CSSレンダリングオプションとレスポンシブレイアウトの詳細については、レスポンシブCSSでHTMLをPDFに変換するとPDFでレンダリングオプションを使うを参照してください。 記入された PDF フォームからデータを抽出する方法は? ユーザーがPDFフォームに入力した後、アプリケーションは入力された値を取得し、処理、保存、他のシステムへの転送を行う必要があります。 フォームデータの抽出は、フィールドに値を書き込むのではなく、フィールドから値を読み取ることで、入力プロセスを逆転させます。 入力PDF ユーザーがすでに記入した申請書(completed-application.pdf)を受け取ったとします。 これは、電子メール、ファイルアップロード、または文書管理システムを介して送信されたフォームを受信し、データベースへの保存やさらなる処理のためにデータを抽出する必要がある一般的なシナリオです。 以下のコードは、入力されたフォームをロードし、すべてのフィールド値を辞書に抽出します。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/extract-form-data.cs using IronPdf; using System.Collections.Generic; // Load a filled PDF form PdfDocument filledForm = PdfDocument.FromFile("completed-application.pdf"); // Extract all form data into a dictionary var extractedData = new Dictionary<string, string>(); foreach (var field in filledForm.Form) { extractedData[field.Name] = field.Value ?? string.Empty; } // Access extracted data // extractedData.GetValueOrDefault("firstName") // extractedData.GetValueOrDefault("lastName") // extractedData.GetValueOrDefault("email") // extractedData.GetValueOrDefault("department") Imports IronPdf Imports System.Collections.Generic ' Load a filled PDF form Dim filledForm As PdfDocument = PdfDocument.FromFile("completed-application.pdf") ' Extract all form data into a dictionary Dim extractedData As New Dictionary(Of String, String)() For Each field In filledForm.Form extractedData(field.Name) = If(field.Value, String.Empty) Next ' Access extracted data ' extractedData.TryGetValue("firstName", Nothing) ' extractedData.TryGetValue("lastName", Nothing) ' extractedData.TryGetValue("email", Nothing) ' extractedData.TryGetValue("department", Nothing) $vbLabelText $csharpLabel 抽出プロセスは、Formコレクションを繰り返し、各フィールドのNameとValueプロパティを読み取ります。 ヌルコーラス演算子(? string.Empty) は、空のフィールドや未設定のフィールドが null ではなく空の文字列を返すようにし、下流処理での null 参照の問題を防ぎます。 一度抽出された辞書は、その名前をキーとして、どのフィールド値にも簡単にアクセスできます。 より構造化された抽出のために、フォームフィールドを強く型付けされたオブジェクトに直接マッピングすることができます。 using IronPdf; using System; public class ApplicationData { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Phone { get; set; } public string Department { get; set; } public string ExperienceLevel { get; set; } public bool AcceptsTerms { get; set; } } public class FormDataExtractor { public ApplicationData ExtractApplicationData(string pdfPath) { PdfDocument pdf = PdfDocument.FromFile(pdfPath); return new ApplicationData { FirstName = GetFieldValue(pdf, "firstName"), LastName = GetFieldValue(pdf, "lastName"), Email = GetFieldValue(pdf, "email"), Phone = GetFieldValue(pdf, "phone"), Department = GetFieldValue(pdf, "department"), ExperienceLevel = GetFieldValue(pdf, "experienceLevel"), AcceptsTerms = GetFieldValue(pdf, "acceptTerms") == "Yes" }; } private string GetFieldValue(PdfDocument pdf, string fieldName) { var field = pdf.Form.FindFormField(fieldName); return field?.Value ?? string.Empty; } } // Usage class Program { static void Main() { var extractor = new FormDataExtractor(); var application = extractor.ExtractApplicationData("submitted-form.pdf"); // Access application.FirstName, application.LastName, application.Department, etc. } } using IronPdf; using System; public class ApplicationData { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Phone { get; set; } public string Department { get; set; } public string ExperienceLevel { get; set; } public bool AcceptsTerms { get; set; } } public class FormDataExtractor { public ApplicationData ExtractApplicationData(string pdfPath) { PdfDocument pdf = PdfDocument.FromFile(pdfPath); return new ApplicationData { FirstName = GetFieldValue(pdf, "firstName"), LastName = GetFieldValue(pdf, "lastName"), Email = GetFieldValue(pdf, "email"), Phone = GetFieldValue(pdf, "phone"), Department = GetFieldValue(pdf, "department"), ExperienceLevel = GetFieldValue(pdf, "experienceLevel"), AcceptsTerms = GetFieldValue(pdf, "acceptTerms") == "Yes" }; } private string GetFieldValue(PdfDocument pdf, string fieldName) { var field = pdf.Form.FindFormField(fieldName); return field?.Value ?? string.Empty; } } // Usage class Program { static void Main() { var extractor = new FormDataExtractor(); var application = extractor.ExtractApplicationData("submitted-form.pdf"); // Access application.FirstName, application.LastName, application.Department, etc. } } Imports IronPdf Imports System Public Class ApplicationData Public Property FirstName As String Public Property LastName As String Public Property Email As String Public Property Phone As String Public Property Department As String Public Property ExperienceLevel As String Public Property AcceptsTerms As Boolean End Class Public Class FormDataExtractor Public Function ExtractApplicationData(pdfPath As String) As ApplicationData Dim pdf As PdfDocument = PdfDocument.FromFile(pdfPath) Return New ApplicationData With { .FirstName = GetFieldValue(pdf, "firstName"), .LastName = GetFieldValue(pdf, "lastName"), .Email = GetFieldValue(pdf, "email"), .Phone = GetFieldValue(pdf, "phone"), .Department = GetFieldValue(pdf, "department"), .ExperienceLevel = GetFieldValue(pdf, "experienceLevel"), .AcceptsTerms = GetFieldValue(pdf, "acceptTerms") = "Yes" } End Function Private Function GetFieldValue(pdf As PdfDocument, fieldName As String) As String Dim field = pdf.Form.FindFormField(fieldName) Return If(field?.Value, String.Empty) End Function End Class ' Usage Class Program Shared Sub Main() Dim extractor As New FormDataExtractor() Dim application = extractor.ExtractApplicationData("submitted-form.pdf") ' Access application.FirstName, application.LastName, application.Department, etc. End Sub End Class $vbLabelText $csharpLabel フォームデータの読み取りの例については、C# PDF Forms ExamplesとExtract PDF Form Fields Guideを参照してください。 フィールドの値をロックするために PDF フォームをフラットにするにはどうすればよいですか? PDFフォームをフラット化することで、インタラクティブなフィールドを静的コンテンツに変換します。 視覚的な外観は変わりませんが、ユーザーは値を編集できなくなります。 この手法には、完成したフォームの永続的な記録の作成、アーカイブ用の文書の準備、提出後の偶発的または意図的な修正の防止など、いくつかの目的があります。 入力PDF ここでは、クライアント名、契約日、契約金額、支払い条件のフィールドを含む契約書テンプレート(contract-template.pdf)を使用します。 これは、テンプレートに特定の取引情報を入力し、フィールドをロックして最終的な改ざん防止ドキュメントを作成するという典型的なワークフローを反映しています。 次のコードは、テンプレートをロードし、契約の詳細を入力し、すべてのフィールドを読み取り専用に設定します。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/flatten-form-readonly.cs using IronPdf; // Load and fill the form PdfDocument pdf = PdfDocument.FromFile("contract-template.pdf"); pdf.Form.FindFormField("clientName").Value = "Acme Corporation"; pdf.Form.FindFormField("contractDate").Value = "January 15, 2025"; pdf.Form.FindFormField("contractValue").Value = "$50,000"; pdf.Form.FindFormField("paymentTerms").Value = "Net 30"; // Make all form fields read-only to prevent further editing foreach (var field in pdf.Form) { field.ReadOnly = true; } // Save the document with locked fields pdf.SaveAs("contract-acme-signed.pdf"); Imports IronPdf ' Load and fill the form Dim pdf As PdfDocument = PdfDocument.FromFile("contract-template.pdf") pdf.Form.FindFormField("clientName").Value = "Acme Corporation" pdf.Form.FindFormField("contractDate").Value = "January 15, 2025" pdf.Form.FindFormField("contractValue").Value = "$50,000" pdf.Form.FindFormField("paymentTerms").Value = "Net 30" ' Make all form fields read-only to prevent further editing For Each field In pdf.Form field.ReadOnly = True Next ' Save the document with locked fields pdf.SaveAs("contract-acme-signed.pdf") $vbLabelText $csharpLabel サンプル出力 このコードではまず、clientName、contractDate、contractValue、paymentTermsのようなフィールドに契約の詳細を入力します。 foreachループは、フォームのすべてのフィールドを繰り返し、field.ReadOnly = trueを設定します。 保存後も、ユーザーはPDFリーダーでフォームの値を見ることができますが、フィールドをクリックしても修正はできません。 この技術は、アーカイブや法的文書に適した永久的な記録を作成します。 パスワード保護を含むその他の PDF セキュリティ オプションについては、Sign and Secure PDFs Tutorial および PDF Password Protection Guide を参照してください。 エンドユーザー向けに PDF フォームをプリフィルするにはどうすればよいですか? 既知の情報をフォームに事前に入力することで、データ入力を減らし、ユーザーエクスペリエンスを向上させます。 システムに顧客情報がすでにある場合、ドキュメントを送信する前にフォームフィールドに入力し、ユーザーに残りのフィールドのみを確認、入力してもらうことができます。 using IronPdf; using System; public class CustomerPortalService { public byte[] GeneratePreFilledRenewalForm(int customerId) { // Simulate fetching customer data from database var customer = GetCustomerById(customerId); // Load the renewal form template PdfDocument pdf = PdfDocument.FromFile("templates/subscription-renewal.pdf"); // Pre-fill known customer information pdf.Form.FindFormField("customerId").Value = customer.Id.ToString(); pdf.Form.FindFormField("customerName").Value = customer.FullName; pdf.Form.FindFormField("email").Value = customer.Email; pdf.Form.FindFormField("phone").Value = customer.Phone; pdf.Form.FindFormField("address").Value = customer.Address; pdf.Form.FindFormField("currentPlan").Value = customer.SubscriptionPlan; pdf.Form.FindFormField("renewalDate").Value = DateTime.Now.AddDays(30).ToString("MM/dd/yyyy"); // Leave editable fields empty for customer input: // - newPlan (dropdown for plan selection) // - paymentMethod (radio buttons) // - additionalNotes (textarea) // - signature (signature field) // Return as byte array for web download or email attachment return pdf.BinaryData; } // Simulated data access private Customer GetCustomerById(int id) { return new Customer { Id = id, FullName = "Robert Williams", Email = "robert.williams@email.com", Phone = "(555) 987-6543", Address = "123 Business Park Drive\r\nSuite 400\r\nChicago, IL 60601", SubscriptionPlan = "Professional" }; } } public class Customer { public int Id { get; set; } public string FullName { get; set; } public string Email { get; set; } public string Phone { get; set; } public string Address { get; set; } public string SubscriptionPlan { get; set; } } using IronPdf; using System; public class CustomerPortalService { public byte[] GeneratePreFilledRenewalForm(int customerId) { // Simulate fetching customer data from database var customer = GetCustomerById(customerId); // Load the renewal form template PdfDocument pdf = PdfDocument.FromFile("templates/subscription-renewal.pdf"); // Pre-fill known customer information pdf.Form.FindFormField("customerId").Value = customer.Id.ToString(); pdf.Form.FindFormField("customerName").Value = customer.FullName; pdf.Form.FindFormField("email").Value = customer.Email; pdf.Form.FindFormField("phone").Value = customer.Phone; pdf.Form.FindFormField("address").Value = customer.Address; pdf.Form.FindFormField("currentPlan").Value = customer.SubscriptionPlan; pdf.Form.FindFormField("renewalDate").Value = DateTime.Now.AddDays(30).ToString("MM/dd/yyyy"); // Leave editable fields empty for customer input: // - newPlan (dropdown for plan selection) // - paymentMethod (radio buttons) // - additionalNotes (textarea) // - signature (signature field) // Return as byte array for web download or email attachment return pdf.BinaryData; } // Simulated data access private Customer GetCustomerById(int id) { return new Customer { Id = id, FullName = "Robert Williams", Email = "robert.williams@email.com", Phone = "(555) 987-6543", Address = "123 Business Park Drive\r\nSuite 400\r\nChicago, IL 60601", SubscriptionPlan = "Professional" }; } } public class Customer { public int Id { get; set; } public string FullName { get; set; } public string Email { get; set; } public string Phone { get; set; } public string Address { get; set; } public string SubscriptionPlan { get; set; } } Imports IronPdf Imports System Public Class CustomerPortalService Public Function GeneratePreFilledRenewalForm(customerId As Integer) As Byte() ' Simulate fetching customer data from database Dim customer = GetCustomerById(customerId) ' Load the renewal form template Dim pdf As PdfDocument = PdfDocument.FromFile("templates/subscription-renewal.pdf") ' Pre-fill known customer information pdf.Form.FindFormField("customerId").Value = customer.Id.ToString() pdf.Form.FindFormField("customerName").Value = customer.FullName pdf.Form.FindFormField("email").Value = customer.Email pdf.Form.FindFormField("phone").Value = customer.Phone pdf.Form.FindFormField("address").Value = customer.Address pdf.Form.FindFormField("currentPlan").Value = customer.SubscriptionPlan pdf.Form.FindFormField("renewalDate").Value = DateTime.Now.AddDays(30).ToString("MM/dd/yyyy") ' Leave editable fields empty for customer input: ' - newPlan (dropdown for plan selection) ' - paymentMethod (radio buttons) ' - additionalNotes (textarea) ' - signature (signature field) ' Return as byte array for web download or email attachment Return pdf.BinaryData End Function ' Simulated data access Private Function GetCustomerById(id As Integer) As Customer Return New Customer With { .Id = id, .FullName = "Robert Williams", .Email = "robert.williams@email.com", .Phone = "(555) 987-6543", .Address = "123 Business Park Drive" & vbCrLf & "Suite 400" & vbCrLf & "Chicago, IL 60601", .SubscriptionPlan = "Professional" } End Function End Class Public Class Customer Public Property Id As Integer Public Property FullName As String Public Property Email As String Public Property Phone As String Public Property Address As String Public Property SubscriptionPlan As String End Class $vbLabelText $csharpLabel サンプル出力 このパターンは、更新フォーム、アプリケーションの更新、年次レビュー、および部分的な情報がすでにシステムに存在するあらゆるシナリオに適しています。 ユーザーは、すでに詳細が入力されたドキュメントを受け取るので、新しい情報や変更された情報を入力するだけです。 フォーム データ処理パイプラインはどのように構築しますか? フォーム送信を大規模に処理するには、抽出、検証、変換、保存を処理する構造化アプローチが必要です。 シンプルなパイプラインパターンにより、このプロセスを整理し、保守しやすくします。 using IronPdf; using System; using System.Collections.Generic; using System.IO; public class FormSubmission { public string SubmissionId { get; set; } public DateTime ReceivedAt { get; set; } public string SourceFile { get; set; } public Dictionary<string, string> FormData { get; set; } public bool IsValid { get; set; } public List<string> ValidationErrors { get; set; } } public class FormProcessingPipeline { public FormSubmission ProcessSubmission(string pdfPath) { var submission = new FormSubmission { SubmissionId = Guid.NewGuid().ToString("N").Substring(0, 8).ToUpper(), ReceivedAt = DateTime.UtcNow, SourceFile = Path.GetFileName(pdfPath), FormData = new Dictionary<string, string>(), ValidationErrors = new List<string>() }; // Step 1: Extract form data PdfDocument pdf = PdfDocument.FromFile(pdfPath); foreach (var field in pdf.Form) { submission.FormData[field.Name] = field.Value ?? string.Empty; } // Step 2: Validate required fields var requiredFields = new[] { "fullName", "email", "signatureDate" }; foreach (var fieldName in requiredFields) { if (!submission.FormData.ContainsKey(fieldName) || string.IsNullOrWhiteSpace(submission.FormData[fieldName])) { submission.ValidationErrors.Add($"Missing required field: {fieldName}"); } } submission.IsValid = submission.ValidationErrors.Count == 0; // Step 3: Return the processed submission return submission; } public void ProcessBatch(string folderPath) { var pdfFiles = Directory.GetFiles(folderPath, "*.pdf"); var results = new List<FormSubmission>(); foreach (var file in pdfFiles) { try { var submission = ProcessSubmission(file); results.Add(submission); } catch (Exception ex) { // Handle error for file: ex.Message } } // Summary int validCount = 0; int invalidCount = 0; foreach (var r in results) { if (r.IsValid) validCount++; else invalidCount++; } // Results summary: results.Count processed, validCount valid, invalidCount invalid } } using IronPdf; using System; using System.Collections.Generic; using System.IO; public class FormSubmission { public string SubmissionId { get; set; } public DateTime ReceivedAt { get; set; } public string SourceFile { get; set; } public Dictionary<string, string> FormData { get; set; } public bool IsValid { get; set; } public List<string> ValidationErrors { get; set; } } public class FormProcessingPipeline { public FormSubmission ProcessSubmission(string pdfPath) { var submission = new FormSubmission { SubmissionId = Guid.NewGuid().ToString("N").Substring(0, 8).ToUpper(), ReceivedAt = DateTime.UtcNow, SourceFile = Path.GetFileName(pdfPath), FormData = new Dictionary<string, string>(), ValidationErrors = new List<string>() }; // Step 1: Extract form data PdfDocument pdf = PdfDocument.FromFile(pdfPath); foreach (var field in pdf.Form) { submission.FormData[field.Name] = field.Value ?? string.Empty; } // Step 2: Validate required fields var requiredFields = new[] { "fullName", "email", "signatureDate" }; foreach (var fieldName in requiredFields) { if (!submission.FormData.ContainsKey(fieldName) || string.IsNullOrWhiteSpace(submission.FormData[fieldName])) { submission.ValidationErrors.Add($"Missing required field: {fieldName}"); } } submission.IsValid = submission.ValidationErrors.Count == 0; // Step 3: Return the processed submission return submission; } public void ProcessBatch(string folderPath) { var pdfFiles = Directory.GetFiles(folderPath, "*.pdf"); var results = new List<FormSubmission>(); foreach (var file in pdfFiles) { try { var submission = ProcessSubmission(file); results.Add(submission); } catch (Exception ex) { // Handle error for file: ex.Message } } // Summary int validCount = 0; int invalidCount = 0; foreach (var r in results) { if (r.IsValid) validCount++; else invalidCount++; } // Results summary: results.Count processed, validCount valid, invalidCount invalid } } Imports IronPdf Imports System Imports System.Collections.Generic Imports System.IO Public Class FormSubmission Public Property SubmissionId As String Public Property ReceivedAt As DateTime Public Property SourceFile As String Public Property FormData As Dictionary(Of String, String) Public Property IsValid As Boolean Public Property ValidationErrors As List(Of String) End Class Public Class FormProcessingPipeline Public Function ProcessSubmission(pdfPath As String) As FormSubmission Dim submission As New FormSubmission With { .SubmissionId = Guid.NewGuid().ToString("N").Substring(0, 8).ToUpper(), .ReceivedAt = DateTime.UtcNow, .SourceFile = Path.GetFileName(pdfPath), .FormData = New Dictionary(Of String, String)(), .ValidationErrors = New List(Of String)() } ' Step 1: Extract form data Dim pdf As PdfDocument = PdfDocument.FromFile(pdfPath) For Each field In pdf.Form submission.FormData(field.Name) = If(field.Value, String.Empty) Next ' Step 2: Validate required fields Dim requiredFields As String() = {"fullName", "email", "signatureDate"} For Each fieldName In requiredFields If Not submission.FormData.ContainsKey(fieldName) OrElse String.IsNullOrWhiteSpace(submission.FormData(fieldName)) Then submission.ValidationErrors.Add($"Missing required field: {fieldName}") End If Next submission.IsValid = submission.ValidationErrors.Count = 0 ' Step 3: Return the processed submission Return submission End Function Public Sub ProcessBatch(folderPath As String) Dim pdfFiles As String() = Directory.GetFiles(folderPath, "*.pdf") Dim results As New List(Of FormSubmission)() For Each file In pdfFiles Try Dim submission As FormSubmission = ProcessSubmission(file) results.Add(submission) Catch ex As Exception ' Handle error for file: ex.Message End Try Next ' Summary Dim validCount As Integer = 0 Dim invalidCount As Integer = 0 For Each r In results If r.IsValid Then validCount += 1 Else invalidCount += 1 End If Next ' Results summary: results.Count processed, validCount valid, invalidCount invalid End Sub End Class $vbLabelText $csharpLabel このパイプライン構造は、データベースストレージ、電子メール通知、外部APIとの統合、またはワークフローが必要とするその他の処理手順を含むように拡張することができます。 重要なのは、抽出、検証、下流処理の分離を維持することです。 高性能バッチ処理については、マルチスレッドと並列処理パターンをカバーする非同期PDF生成ガイドを参照してください。 W-9のようなIRSの納税申告書をどのように自動化しますか? 官公庁の書式は、最も処理量の多いPDF処理シナリオの一部です。 W-9(Request for Taxpayer Identification Number)だけでも、ベンダーや請負業者への入社手続きで年間数百万回記入されています。 個人請負業者に給与を支払う企業には必ずW-9の提出が必要であり、この収集プロセスを自動化することで、管理時間を大幅に短縮することができます。 using IronPdf; using System; public class W9FormData { public string Name { get; set; } public string BusinessName { get; set; } public string FederalTaxClassification { get; set; } public string ExemptPayeeCode { get; set; } public string FatcaExemptionCode { get; set; } public string Address { get; set; } public string CityStateZip { get; set; } public string AccountNumbers { get; set; } public string TaxpayerIdNumber { get; set; } public DateTime SignatureDate { get; set; } } public class W9FormProcessor { public void FillW9Form(W9FormData data, string templatePath, string outputPath) { PdfDocument pdf = PdfDocument.FromFile(templatePath); // The W-9 form has specific field names defined by the IRS // These correspond to the official form structure // Line 1: Name as shown on your income tax return SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name); // Line 2: Business name/disregarded entity name SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_2[0]", data.BusinessName); // Line 3: Federal tax classification (checkbox selection) // The W-9 uses checkbox fields for classification switch (data.FederalTaxClassification) { case "Individual": SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[0]", "1"); break; case "CCorporation": SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[1]", "2"); break; case "SCorporation": SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[2]", "3"); break; case "Partnership": SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[3]", "4"); break; case "LLC": SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[5]", "6"); break; } // Line 5: Address SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address); // Line 6: City, state, and ZIP code SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_8[0]", data.CityStateZip); // Part I: Taxpayer Identification Number (SSN or EIN) // For security, typically only last 4 digits are pre-filled or field is left for manual entry if (!string.IsNullOrEmpty(data.TaxpayerIdNumber) && data.TaxpayerIdNumber.Length >= 4) { // TIN left blank for security - user must enter manually } // Signature date SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]", data.SignatureDate.ToString("MM/dd/yyyy")); pdf.SaveAs(outputPath); } private void SetFieldIfExists(PdfDocument pdf, string fieldName, string value) { var field = pdf.Form.FindFormField(fieldName); if (field != null && !string.IsNullOrEmpty(value)) { field.Value = value; } } } // Usage example class Program { static void Main() { var vendorData = new W9FormData { Name = "Johnson Consulting LLC", BusinessName = "", FederalTaxClassification = "LLC", Address = "456 Commerce Street", CityStateZip = "Austin, TX 78701", SignatureDate = DateTime.Today }; var processor = new W9FormProcessor(); processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf"); } } using IronPdf; using System; public class W9FormData { public string Name { get; set; } public string BusinessName { get; set; } public string FederalTaxClassification { get; set; } public string ExemptPayeeCode { get; set; } public string FatcaExemptionCode { get; set; } public string Address { get; set; } public string CityStateZip { get; set; } public string AccountNumbers { get; set; } public string TaxpayerIdNumber { get; set; } public DateTime SignatureDate { get; set; } } public class W9FormProcessor { public void FillW9Form(W9FormData data, string templatePath, string outputPath) { PdfDocument pdf = PdfDocument.FromFile(templatePath); // The W-9 form has specific field names defined by the IRS // These correspond to the official form structure // Line 1: Name as shown on your income tax return SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name); // Line 2: Business name/disregarded entity name SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_2[0]", data.BusinessName); // Line 3: Federal tax classification (checkbox selection) // The W-9 uses checkbox fields for classification switch (data.FederalTaxClassification) { case "Individual": SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[0]", "1"); break; case "CCorporation": SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[1]", "2"); break; case "SCorporation": SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[2]", "3"); break; case "Partnership": SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[3]", "4"); break; case "LLC": SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[5]", "6"); break; } // Line 5: Address SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address); // Line 6: City, state, and ZIP code SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_8[0]", data.CityStateZip); // Part I: Taxpayer Identification Number (SSN or EIN) // For security, typically only last 4 digits are pre-filled or field is left for manual entry if (!string.IsNullOrEmpty(data.TaxpayerIdNumber) && data.TaxpayerIdNumber.Length >= 4) { // TIN left blank for security - user must enter manually } // Signature date SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]", data.SignatureDate.ToString("MM/dd/yyyy")); pdf.SaveAs(outputPath); } private void SetFieldIfExists(PdfDocument pdf, string fieldName, string value) { var field = pdf.Form.FindFormField(fieldName); if (field != null && !string.IsNullOrEmpty(value)) { field.Value = value; } } } // Usage example class Program { static void Main() { var vendorData = new W9FormData { Name = "Johnson Consulting LLC", BusinessName = "", FederalTaxClassification = "LLC", Address = "456 Commerce Street", CityStateZip = "Austin, TX 78701", SignatureDate = DateTime.Today }; var processor = new W9FormProcessor(); processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf"); } } Imports IronPdf Imports System Public Class W9FormData Public Property Name As String Public Property BusinessName As String Public Property FederalTaxClassification As String Public Property ExemptPayeeCode As String Public Property FatcaExemptionCode As String Public Property Address As String Public Property CityStateZip As String Public Property AccountNumbers As String Public Property TaxpayerIdNumber As String Public Property SignatureDate As DateTime End Class Public Class W9FormProcessor Public Sub FillW9Form(data As W9FormData, templatePath As String, outputPath As String) Dim pdf As PdfDocument = PdfDocument.FromFile(templatePath) ' The W-9 form has specific field names defined by the IRS ' These correspond to the official form structure ' Line 1: Name as shown on your income tax return SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name) ' Line 2: Business name/disregarded entity name SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_2[0]", data.BusinessName) ' Line 3: Federal tax classification (checkbox selection) ' The W-9 uses checkbox fields for classification Select Case data.FederalTaxClassification Case "Individual" SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[0]", "1") Case "CCorporation" SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[1]", "2") Case "SCorporation" SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[2]", "3") Case "Partnership" SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[3]", "4") Case "LLC" SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[5]", "6") End Select ' Line 5: Address SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address) ' Line 6: City, state, and ZIP code SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_8[0]", data.CityStateZip) ' Part I: Taxpayer Identification Number (SSN or EIN) ' For security, typically only last 4 digits are pre-filled or field is left for manual entry If Not String.IsNullOrEmpty(data.TaxpayerIdNumber) AndAlso data.TaxpayerIdNumber.Length >= 4 Then ' TIN left blank for security - user must enter manually End If ' Signature date SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]", data.SignatureDate.ToString("MM/dd/yyyy")) pdf.SaveAs(outputPath) End Sub Private Sub SetFieldIfExists(pdf As PdfDocument, fieldName As String, value As String) Dim field = pdf.Form.FindFormField(fieldName) If field IsNot Nothing AndAlso Not String.IsNullOrEmpty(value) Then field.Value = value End If End Sub End Class ' Usage example Module Program Sub Main() Dim vendorData As New W9FormData With { .Name = "Johnson Consulting LLC", .BusinessName = "", .FederalTaxClassification = "LLC", .Address = "456 Commerce Street", .CityStateZip = "Austin, TX 78701", .SignatureDate = DateTime.Today } Dim processor As New W9FormProcessor() processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf") End Sub End Module $vbLabelText $csharpLabel 政府機関の書式では、複雑な階層構造のフィールド命名規則が使用されることがよくあります。 上記のW-9フィールド名は、IRSの公式PDFで使用されているXFA由来の命名パターンに従っています。 政府の書式を扱うときは、自動化コードを書く前に、必ず政府の公式ウェブサイトから最新版をダウンロードし、そのフィールド構造を調べてください。 可変データでフォームをバッチ処理するには? バッチ処理は、データベースクエリ、CSVファイル、APIレスポンスなどのデータソースから、複数の完成したフォームを生成します。 この能力は、年次税務書類の配布、従業員の入社案内、顧客明細書の作成などのシナリオに不可欠です。 using IronPdf; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class VendorRecord { public string VendorId { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string ZipCode { get; set; } public string TaxClassification { get; set; } } public class BatchFormGenerator { private readonly string _templatePath; private readonly string _outputDirectory; public BatchFormGenerator(string templatePath, string outputDirectory) { _templatePath = templatePath; _outputDirectory = outputDirectory; if (!Directory.Exists(_outputDirectory)) { Directory.CreateDirectory(_outputDirectory); } } public void GenerateVendorForms(List<VendorRecord> vendors) { var startTime = DateTime.Now; int successCount = 0; int errorCount = 0; foreach (var vendor in vendors) { try { GenerateSingleForm(vendor); successCount++; } catch (Exception ex) { errorCount++; // Handle error: ex.Message } } var elapsed = DateTime.Now - startTime; // Results: successCount successful, errorCount errors, elapsed time } private void GenerateSingleForm(VendorRecord vendor) { PdfDocument pdf = PdfDocument.FromFile(_templatePath); // Fill vendor information fields SetField(pdf, "vendorId", vendor.VendorId); SetField(pdf, "companyName", vendor.CompanyName); SetField(pdf, "contactName", vendor.ContactName); SetField(pdf, "address", vendor.Address); SetField(pdf, "city", vendor.City); SetField(pdf, "state", vendor.State); SetField(pdf, "zipCode", vendor.ZipCode); SetField(pdf, "taxClassification", vendor.TaxClassification); SetField(pdf, "generatedDate", DateTime.Today.ToString("MM/dd/yyyy")); // Create a safe filename from company name string safeFileName = string.Join("_", vendor.CompanyName.Split(Path.GetInvalidFileNameChars())); string outputPath = Path.Combine(_outputDirectory, $"vendor-form-{vendor.VendorId}-{safeFileName}.pdf"); pdf.SaveAs(outputPath); } private void SetField(PdfDocument pdf, string fieldName, string value) { var field = pdf.Form.FindFormField(fieldName); if (field != null) { field.Value = value ?? string.Empty; } } } // Usage example with sample data class Program { static void Main() { var vendors = new List<VendorRecord> { new VendorRecord { VendorId = "V001", CompanyName = "Alpha Supplies Inc", ContactName = "Maria Garcia", Address = "100 Industrial Way", City = "Chicago", State = "IL", ZipCode = "60601", TaxClassification = "Corporation" }, new VendorRecord { VendorId = "V002", CompanyName = "Beta Services LLC", ContactName = "James Wilson", Address = "200 Tech Park Drive", City = "Austin", State = "TX", ZipCode = "78701", TaxClassification = "LLC" }, new VendorRecord { VendorId = "V003", CompanyName = "Gamma Consulting", ContactName = "Sarah Chen", Address = "300 Business Center", City = "Seattle", State = "WA", ZipCode = "98101", TaxClassification = "Partnership" } }; var generator = new BatchFormGenerator("vendor-info-template.pdf", "output/vendor-forms"); generator.GenerateVendorForms(vendors); } } using IronPdf; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class VendorRecord { public string VendorId { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string ZipCode { get; set; } public string TaxClassification { get; set; } } public class BatchFormGenerator { private readonly string _templatePath; private readonly string _outputDirectory; public BatchFormGenerator(string templatePath, string outputDirectory) { _templatePath = templatePath; _outputDirectory = outputDirectory; if (!Directory.Exists(_outputDirectory)) { Directory.CreateDirectory(_outputDirectory); } } public void GenerateVendorForms(List<VendorRecord> vendors) { var startTime = DateTime.Now; int successCount = 0; int errorCount = 0; foreach (var vendor in vendors) { try { GenerateSingleForm(vendor); successCount++; } catch (Exception ex) { errorCount++; // Handle error: ex.Message } } var elapsed = DateTime.Now - startTime; // Results: successCount successful, errorCount errors, elapsed time } private void GenerateSingleForm(VendorRecord vendor) { PdfDocument pdf = PdfDocument.FromFile(_templatePath); // Fill vendor information fields SetField(pdf, "vendorId", vendor.VendorId); SetField(pdf, "companyName", vendor.CompanyName); SetField(pdf, "contactName", vendor.ContactName); SetField(pdf, "address", vendor.Address); SetField(pdf, "city", vendor.City); SetField(pdf, "state", vendor.State); SetField(pdf, "zipCode", vendor.ZipCode); SetField(pdf, "taxClassification", vendor.TaxClassification); SetField(pdf, "generatedDate", DateTime.Today.ToString("MM/dd/yyyy")); // Create a safe filename from company name string safeFileName = string.Join("_", vendor.CompanyName.Split(Path.GetInvalidFileNameChars())); string outputPath = Path.Combine(_outputDirectory, $"vendor-form-{vendor.VendorId}-{safeFileName}.pdf"); pdf.SaveAs(outputPath); } private void SetField(PdfDocument pdf, string fieldName, string value) { var field = pdf.Form.FindFormField(fieldName); if (field != null) { field.Value = value ?? string.Empty; } } } // Usage example with sample data class Program { static void Main() { var vendors = new List<VendorRecord> { new VendorRecord { VendorId = "V001", CompanyName = "Alpha Supplies Inc", ContactName = "Maria Garcia", Address = "100 Industrial Way", City = "Chicago", State = "IL", ZipCode = "60601", TaxClassification = "Corporation" }, new VendorRecord { VendorId = "V002", CompanyName = "Beta Services LLC", ContactName = "James Wilson", Address = "200 Tech Park Drive", City = "Austin", State = "TX", ZipCode = "78701", TaxClassification = "LLC" }, new VendorRecord { VendorId = "V003", CompanyName = "Gamma Consulting", ContactName = "Sarah Chen", Address = "300 Business Center", City = "Seattle", State = "WA", ZipCode = "98101", TaxClassification = "Partnership" } }; var generator = new BatchFormGenerator("vendor-info-template.pdf", "output/vendor-forms"); generator.GenerateVendorForms(vendors); } } Imports IronPdf Imports System Imports System.Collections.Generic Imports System.IO Public Class VendorRecord Public Property VendorId As String Public Property CompanyName As String Public Property ContactName As String Public Property Address As String Public Property City As String Public Property State As String Public Property ZipCode As String Public Property TaxClassification As String End Class Public Class BatchFormGenerator Private ReadOnly _templatePath As String Private ReadOnly _outputDirectory As String Public Sub New(templatePath As String, outputDirectory As String) _templatePath = templatePath _outputDirectory = outputDirectory If Not Directory.Exists(_outputDirectory) Then Directory.CreateDirectory(_outputDirectory) End If End Sub Public Sub GenerateVendorForms(vendors As List(Of VendorRecord)) Dim startTime = DateTime.Now Dim successCount As Integer = 0 Dim errorCount As Integer = 0 For Each vendor In vendors Try GenerateSingleForm(vendor) successCount += 1 Catch ex As Exception errorCount += 1 ' Handle error: ex.Message End Try Next Dim elapsed = DateTime.Now - startTime ' Results: successCount successful, errorCount errors, elapsed time End Sub Private Sub GenerateSingleForm(vendor As VendorRecord) Dim pdf As PdfDocument = PdfDocument.FromFile(_templatePath) ' Fill vendor information fields SetField(pdf, "vendorId", vendor.VendorId) SetField(pdf, "companyName", vendor.CompanyName) SetField(pdf, "contactName", vendor.ContactName) SetField(pdf, "address", vendor.Address) SetField(pdf, "city", vendor.City) SetField(pdf, "state", vendor.State) SetField(pdf, "zipCode", vendor.ZipCode) SetField(pdf, "taxClassification", vendor.TaxClassification) SetField(pdf, "generatedDate", DateTime.Today.ToString("MM/dd/yyyy")) ' Create a safe filename from company name Dim safeFileName As String = String.Join("_", vendor.CompanyName.Split(Path.GetInvalidFileNameChars())) Dim outputPath As String = Path.Combine(_outputDirectory, $"vendor-form-{vendor.VendorId}-{safeFileName}.pdf") pdf.SaveAs(outputPath) End Sub Private Sub SetField(pdf As PdfDocument, fieldName As String, value As String) Dim field = pdf.Form.FindFormField(fieldName) If field IsNot Nothing Then field.Value = If(value, String.Empty) End If End Sub End Class ' Usage example with sample data Module Program Sub Main() Dim vendors As New List(Of VendorRecord) From { New VendorRecord With { .VendorId = "V001", .CompanyName = "Alpha Supplies Inc", .ContactName = "Maria Garcia", .Address = "100 Industrial Way", .City = "Chicago", .State = "IL", .ZipCode = "60601", .TaxClassification = "Corporation" }, New VendorRecord With { .VendorId = "V002", .CompanyName = "Beta Services LLC", .ContactName = "James Wilson", .Address = "200 Tech Park Drive", .City = "Austin", .State = "TX", .ZipCode = "78701", .TaxClassification = "LLC" }, New VendorRecord With { .VendorId = "V003", .CompanyName = "Gamma Consulting", .ContactName = "Sarah Chen", .Address = "300 Business Center", .City = "Seattle", .State = "WA", .ZipCode = "98101", .TaxClassification = "Partnership" } } Dim generator As New BatchFormGenerator("vendor-info-template.pdf", "output/vendor-forms") generator.GenerateVendorForms(vendors) End Sub End Module $vbLabelText $csharpLabel 非常に大規模なバッチの場合、システムリソースを圧迫することなくスループットを最大化するために、並行性を制御した並列処理の実装を検討してください。 政府のPDF標準への準拠をどのように保証しますか? 政府機関では、長期保存とアクセシビリティのために、文書が特定のPDF標準に準拠することがしばしば求められます。 PDF/Aは、電子文書の信頼できる長期保存のために設計されたPDFのISO標準サブセットです。 IronPDFはこれらのコンプライアンス要件を満たすためにPDF/Aフォーマットでのエクスポートをサポートしています。 次のコードは、HTMLから政府の公式フォームを作成し、申請者データを入力し、SaveAsPdfA()メソッドを使用してPDF/A-3b準拠のドキュメントとして保存します。 このフォーマットにより、文書は数十年先も読み続けられ、ほとんどの政府提出要件に適合します。 :path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/pdfa-compliance.cs using IronPdf; // Create or load a form document string formHtml = @" <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; margin: 40px; } h1 { color: #003366; } .form-section { margin: 20px 0; } label { display: block; margin: 10px 0 5px 0; font-weight: bold; } input, select { padding: 8px; width: 300px; border: 1px solid #ccc; } </style> </head> <body> <h1>Official Government Form</h1> <p>This document complies with PDF/A-3b archival standards.</p> <form> <div class='form-section'> <label>Applicant Name</label> <input type='text' name='applicantName' /> </div> <div class='form-section'> <label>Application Date</label> <input type='text' name='applicationDate' /> </div> <div class='form-section'> <label>Department</label> <select name='department'> <option value=''>Select Department</option> <option value='Revenue'>Department of Revenue</option> <option value='Labor'>Department of Labor</option> <option value='Commerce'>Department of Commerce</option> </select> </div> </form> </body> </html>"; ChromePdfRenderer renderer = new ChromePdfRenderer(); renderer.RenderingOptions.CreatePdfFormsFromHtml = true; PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml); // Fill form fields pdf.Form.FindFormField("applicantName").Value = "Government Services Corp"; pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy"); pdf.Form.FindFormField("department").Value = "Commerce"; // Convert to PDF/A-3b for archival compliance pdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b); Imports IronPdf ' Create or load a form document Dim formHtml As String = " <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; margin: 40px; } h1 { color: #003366; } .form-section { margin: 20px 0; } label { display: block; margin: 10px 0 5px 0; font-weight: bold; } input, select { padding: 8px; width: 300px; border: 1px solid #ccc; } </style> </head> <body> <h1>Official Government Form</h1> <p>This document complies with PDF/A-3b archival standards.</p> <form> <div class='form-section'> <label>Applicant Name</label> <input type='text' name='applicantName' /> </div> <div class='form-section'> <label>Application Date</label> <input type='text' name='applicationDate' /> </div> <div class='form-section'> <label>Department</label> <select name='department'> <option value=''>Select Department</option> <option value='Revenue'>Department of Revenue</option> <option value='Labor'>Department of Labor</option> <option value='Commerce'>Department of Commerce</option> </select> </div> </form> </body> </html>" Dim renderer As New ChromePdfRenderer() renderer.RenderingOptions.CreatePdfFormsFromHtml = True Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml) ' Fill form fields pdf.Form.FindFormField("applicantName").Value = "Government Services Corp" pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy") pdf.Form.FindFormField("department").Value = "Commerce" ' Convert to PDF/A-3b for archival compliance pdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b) $vbLabelText $csharpLabel サンプル出力 SaveAsPdfA()メソッドは、出力ファイル名とPdfAVersions列挙値(PdfA3bなど)を受け取ります。 IronPDFは保存プロセスにおいて、自動的にすべてのフォントを埋め込み、カラースペースを標準化し、暗号化を取り除き、PDF/A要件に従ってメタデータを構成します。 このような変換を行うことで、どのソフトウェアで文書を開こうとも、数十年先も読みやすく、視覚的に同じであることが保証されます。 政府機関にフォームを提出する場合は、その政府機関固有の要件を確認してください。 基本的なアーカイブのためにPDF/A-1bを要求する場合もあれば、XMLデータファイルのような埋め込み添付ファイルを許可するためにPDF/A-3bを指定する場合もあります。 たとえば、国税庁では、さまざまな提出タイプに対応した特定のPDFバージョンを受け付けていますし、入国管理局のフォームには独自の技術仕様があることがよくあります。 PDF/A 変換の完全なドキュメントは、C# で PDF を PDF/A-3b に変換すると PDF/A コンプライアンス ガイドを参照してください。 アクセシビリティ基準については、PDF/UAドキュメントを作成するをご覧ください。 次のステップ これで、手作業によるデータ入力に何時間も費やしているPDFフォームのワークフローを自動化するために必要なものがすべて揃いました。 ベンダーのオンボーディングのためのW-9フォームの処理、EHRシステムからの患者受け入れフォームの事前入力、CRMへの提出されたアプリケーションデータの取り込みなど、このガイドのテクニックは、今あなたの受信トレイにあるフォームに直接翻訳することができます。 フォーム以外のPDF編集機能の完全なチュートリアルについては、PDF編集チュートリアルを参照してください。 前に進むには、顧客アプリケーションや従業員の入社案内など、チームがすでに使用している既存のフォームに入力し、編集することから始め、このガイドの辞書アプローチを使用して簡単なパイプラインを構築します。そこから、HTMLから新しいフォームを作成して設計の柔軟性を高めたり、デジタル署名フィールドを追加して法的拘束力のある署名を必要とするフォームを作成したりできます。 政府のアーカイブ基準を満たす必要がある場合、PDF/Aコンプライアンスガイドは長期保存をカバーし、PDF/UAアクセシビリティガイドはフォームがセクション508の監査に合格することを保証します。 構築開始の準備はできましたか? IronPdfをダウンロードして無料トライアルでお試しください。 同じライブラリで、単一のフォーム入力から、.NET環境全体にわたる大容量バッチ処理まで、すべてを処理します。 フォームの自動化や統合について質問がある場合は、当社のエンジニアリング・サポート・チームにお問い合わせください。 よくある質問 C#を使用してPDFフォームを作成するにはどうすればよいですか? C#でPDFフォームを作成するには、IronPDFを使ってHTMLフォームをPDFドキュメントに変換します。これにより、インタラクティブなフォームのカスタマイズや設計が容易になります。 既存の PDF フォームに C# でプログラム的に入力することは可能ですか? はい、IronPDFはC#コードを使用してフォームフィールドにアクセスし、修正することで、C#で既存のPDFフォームをプログラムで埋めることができます。 IronPDFを使ってPDFフォームからデータを抽出できますか? IronPdfはPDFドキュメントからフォームデータを抽出する機能を提供し、PDFフォームに入力された情報の取得と処理を容易にします。 PDFフォームをフラットにするとはどういう意味ですか? PDFフォームのフラット化にはフォームフィールドを静的コンテンツに変換することが含まれます。IronPDFはフォームを平坦化することでデータの整合性を確保し、フォーム送信後の変更を防ぎます。 W-9のような政府フォームの処理を自動化するにはどうすればよいですか? IronPDFはW-9のような政府フォームの処理を自動化し、フォームデータの入力、抽出、管理をプログラムで行うことができ、ワークフローを合理化します。 PDFフォームの作成にHTMLを使用する利点は何ですか? IronPDFでPDFフォームを作成するためにHTMLを使用することは、デザインの柔軟性と既存のウェブテクノロジーとの統合のしやすさを提供し、ダイナミックでレスポンシブなフォーム作成を可能にします。 IronPDFはインタラクティブなフォーム要素を扱えますか? はい、IronPDFはテキストフィールド、チェックボックス、ボタンなどのインタラクティブなフォーム要素をサポートし、C#でダイナミックなPDFフォームの作成と操作を可能にします。 PDFフォームの外観をカスタマイズできますか? IronPdfはPDFフォームの外観を完全にカスタマイズすることができ、フォーム要素にCSSスタイルを適用してプロフェッショナルで一貫性のある外観にすることができます。 カーティス・チャウ 今すぐエンジニアリングチームとチャット テクニカルライター Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。 準備はできましたか? Nuget ダウンロード 17,386,124 | バージョン: 2026.2 リリース NuGet 無料版 総ダウンロード数: 17,386,124 ライセンスを見る