# 如何在Python中填寫PDF表單欄位
透過IronPDF,在Python中以程式方式填寫PDF表單:載入現有的PDF,按欄位名稱定位,設置值,並在幾行程式碼中保存結果。
*as-heading:2(快速入門:填寫PDF表單欄位)*
```python
1. Install IronPDF: `pip install ironpdf`
2. Load your PDF: `form_document = PdfDocument.FromFile("form.pdf")`
3. Find form field: `field = form_document.Form.FindFormField("fieldname")`
4. Set field value: `field.Value = "Your Value"`
5. Save filled PDF: `form_document.SaveAs("filled_form.pdf")`
```
<div class="hsg-featured-snippet">
<h2>如何在Python中填寫PDF表單欄位</h2>
<ol>
<li><a class="js-modal-open" data-modal-id="download-modal" href="#download-modal">安裝IronPDF Python程式庫</a></li>
<li>載入包含表單欄位的現有PDF文件</li>
<li>使用<strong>Form</strong>屬性的<code>FindFormField</code>方法根據名稱存取表單欄位</li>
<li>為欄位的<strong>Value</strong>屬性分配新值</li>
<li>使用<code>SaveAs</code>導出已修改的文件</li>
</ol>
</div>
透過網頁UI收集資料,然後生成填寫的PDF以進行存檔或後續處理是常見的文件自動化模式。 與其手動將資料轉錄到PDF表單,不如讓Python腳本立即處理:讀取欄位名稱,填寫值,並生成準備好儲存或分發的完成文件。
IronPDF使此工作流程直接:一個API從HTML建立表單,一個方法根據名稱定位欄位,一個屬性設置其值。 現有的PDF表單中不僅僅包含文字輸入。 通過相同的`Value`方法支持複選框、單選按鈕和下拉欄位。 本指南的其餘部分將逐步介紹主要場景:從HTML標記生成表單,填寫現有文件中的欄位,讀取所有欄位型別,從資料源運行批量填寫。
## 如何使用HTML在Python中建立和填寫PDF表單?
IronPDF可以直接將HTML `<input>` 元素轉換為可編輯的PDF欄位,使您從網頁樣式的表單定義到可填寫的PDF文件擁有直接的路徑。 您可以使用熟悉的HTML和CSS設計表單,然後立即填寫它們,而無需中間手動步驟。
下面的範例將HTML表單呈現為PDF,然後填寫`lastname`欄位,最後保存結果。
```python
from ironpdf import *
# Define HTML content for a simple form
form_html = """
<html>
<body>
<h2>Editable PDF Form</h2>
<form>
First name: <br> <input type='text' name='firstname' value=''> <br>
Last name: <br> <input type='text' name='lastname' value=''>
</form>
</body>
</html>
"""
# Instantiate a PDF renderer
renderer = ChromePdfRenderer()
# Enable HTML form-to-PDF-field conversion
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
# Render the HTML content to a PDF file
renderer.RenderHtmlAsPdf(form_html).SaveAs("BasicForm.pdf")
# Load the created PDF document
form_document = PdfDocument.FromFile("BasicForm.pdf")
# Access the "firstname" field and set its value
first_name_field = form_document.Form.FindFormField("firstname")
first_name_field.Value = "Minnie"
print("FirstNameField value: {}".format(first_name_field.Value))
# Access the "lastname" field and set its value
last_name_field = form_document.Form.FindFormField("lastname")
last_name_field.Value = "Mouse"
print("LastNameField value: {}".format(last_name_field.Value))
# Save the filled form
form_document.SaveAs("FilledForm.pdf")
```
將`<input>`元素轉換為對應的交互式PDF欄位。 沒有此標誌,文字輸入將呈現為靜態視覺元素,無法以程式方式填寫。
渲染後,`PdfDocument.FromFile`將保存的文件重新載入到記憶體中。 `FormField`物件。 分配給`Value`將資料寫入欄位。 `SaveAs`調用將已修改的文件寫入磁碟。
[[t:(設計用於PDF轉換的HTML表單時,保持欄位`name`屬性簡短且URL安全。 欄位名稱中的空格和特殊字元可以正常工作,但可能會使下游`FindFormField`查找變得複雜化。)]
)]]
### 未填寫前的空白表單樣子如何?

渲染的PDF保留了HTML表單的視覺佈局。 每個文字輸入顯示為可點擊、可編輯的欄位。 當在PDF閱讀器中打開表單時,使用者仍然可以手動輸入欄位,也可以如上所示通過API填寫欄位。
### 填寫後的完成表單樣子如何?

填寫的文件顯示了寫入每個欄位的值。 表單結構和欄位的互動性完好無損:PDF可以按原狀保存以供存檔,或展平以將值鎖定到位以供分發。
## 如何填寫已有PDF文件中的欄位?
許多現實世界的工作流程涉及Adobe Acrobat、Word或其他工具中建立的PDF表單。 IronPDF可以載入包含[AcroForm欄位](https://ironpdf.com/python/how-to/python-create-pdf/)的任何PDF,並使用相同的`Value`API填寫它們,這與從HTML建立表單時使用的API相同。 AcroForm是[PDF規範中定義的標準交互式表單格式](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf),得到所有主要PDF閱讀器的支持。
```python
from ironpdf import *
# Load a pre-existing PDF with form fields
form_document = PdfDocument.FromFile("existing_form.pdf")
# Enumerate available field names (helpful when exploring an unfamiliar form)
for field in form_document.Form.Fields:
print("Field name:", field.Name, "| Current value:", field.Value)
# Fill a specific field by name
applicant_name_field = form_document.Form.FindFormField("applicant_name")
applicant_name_field.Value = "Jane Smith"
# Fill a second field
date_field = form_document.Form.FindFormField("application_date")
date_field.Value = "2026-05-03"
# Save the filled document
form_document.SaveAs("submitted_application.pdf")
```
在填寫前迭代`form_document.Form.Fields`在處理欄位名稱未記錄下來的表單時很有用。 迴圈列印每個欄位名稱及其當前值,給出寫入前表單期望的完整圖。
[[i:(IronPDF支持AcroForm欄位,這是標準交互式表單格式。 掃描的PDF和僅包含圖像的文件不包含欄位資料; 首先使用[IronOCR](https://ironsoftware.com/csharp/ocr/)從這些文件中提取文字。)]
)]]
## 如何處理複選框和其他欄位型別?
文字欄位是最常見的表單元素,但現實世界的表單包括複選框、單選按鈕和組合框下拉選單。 IronPDF通過相同的`Form.Fields`集合來暴露這些所有的。 `Value`屬性接受每種型別的適當字串。
下表顯示了三種最常見的非文字欄位型別的接受值:
<table class="content__data-table" data-content-table>
<caption>IronPDF非文字輸入型別的PDF表單欄位值慣例</caption>
<thead>
<tr><th>欄位型別</th><th>HTML輸入型別</th><th>要設置的值</th><th>備註</th></tr>
</thead>
<tbody>
<tr><td>複選框</td><td><code>type="checkbox"</code></td><td><code>"true"</code> or <code>"false"</code></td><td>不區分大小寫;使用字串而非布林值</td></tr>
<tr><td>單選按鈕</td><td><code>type="radio"</code></td><td>要選擇的選項的<code>value</code>屬性</td><td>相同的名稱,不同選項各有不同的值</td></tr>
<tr><td>下拉選單(組合框)</td><td><code><select></code></td><td>所需選項的顯示文字</td><td>必須完全匹配現有選項</td></tr>
</tbody>
</table>
```python
from ironpdf import *
# Load a form with multiple field types
form_document = PdfDocument.FromFile("application_form.pdf")
# Fill a text field
form_document.Form.FindFormField("full_name").Value = "Alex Rivera"
# Check a checkbox (use string "true")
form_document.Form.FindFormField("agree_terms").Value = "true"
# Select a radio button option by its value attribute
form_document.Form.FindFormField("employment_status").Value = "full_time"
# Select a dropdown option by display text
form_document.Form.FindFormField("country").Value = "United States"
form_document.SaveAs("completed_application.pdf")
```
在迭代`Value`屬性。 對於單選組和下拉選單,在寫入前列印現有的`Value`將顯示您當前的選擇,並確認該欄位的期望格式。
[[e:(如果`None`,則表單名稱在文件中不存在。 通過`form_document.Form.Fields`列印所有名稱以驗證拼寫並確認欄位存在。 表單名稱區分大小寫。)]
)]]
## 如何從資料源批量填寫表單?
從電子表格或資料庫查詢生成每條記錄一個填寫的PDF是團隊求助於程式化表單填寫的最常見原因之一。 IronPDF通過將每個填寫操作視為無狀態來處理此問題:載入模板、填寫欄位,使用唯一名稱保存,並重複。
```python
from ironpdf import *
# Sample data records (replace with database or CSV source)
applicants = [
{"name": "Alice Johnson", "id": "A001", "date": "2026-05-03"},
{"name": "Bob Williams", "id": "B002", "date": "2026-05-03"},
{"name": "Carol Davis", "id": "C003", "date": "2026-05-03"},
]
for applicant in applicants:
# Load template from disk on each iteration to avoid cross-contamination
form_document = PdfDocument.FromFile("application_template.pdf")
# Fill each field from the data record
form_document.Form.FindFormField("applicant_name").Value = applicant["name"]
form_document.Form.FindFormField("applicant_id").Value = applicant["id"]
form_document.Form.FindFormField("submission_date").Value = applicant["date"]
# Save each filled form with a unique filename
output_path = f"output/application_{applicant['id']}.pdf"
form_document.SaveAs(output_path)
print(f"Saved: {output_path}")
```
將模板載入迴圈內而不是之前一次操作,可防止在迭代過程中欄位值的累積。 每次調用`PdfDocument.FromFile`都會產生模板的新副本,因此填寫一條記錄不會影響下一條。
[[n:(對於高容量批次執行,考慮使用`PdfDocument.FromFile`先載入一次模板,如API支持的話,使用副本機制。 在部署前,根據您的容量需求對這兩種方法進行基準測試。)]
)]]
IronPDF不對一次運行中腳本可以生成的文件數量施加人為限制。 吞吐量由可用記憶體和輸出目的地的I/O速度決定。 對於非常大的批次,先寫入本地SSD,然後再轉移到網路儲存比直接寫入網路共享更快。
## 如何展平填寫的PDF表單?
展平將交互式表單欄位轉換為靜態頁面內容,將當前值鎖定在位。 展平的PDF是進行存檔、列印或發送給不應更改欄位值的收件人的正確選擇。
IronPDF提供[展平表單欄位方法](https://ironpdf.com/how-to/pdf-image-flatten-csharp/),可以操作已載入的任何`PdfDocument`。 在填寫欄位後調用該方法,然後保存結果。
```python
from ironpdf import *
# Load and fill a form
form_document = PdfDocument.FromFile("application_template.pdf")
form_document.Form.FindFormField("full_name").Value = "Jordan Lee"
form_document.Form.FindFormField("application_date").Value = "2026-05-03"
# Flatten all form fields to lock values as static content
form_document.Form.Flatten()
# Save the flattened, non-editable PDF
form_document.SaveAs("archived_application.pdf")
```
經過`Flatten()`處理後,文件不再包含交互式欄位物件。 接收到文件的下游系統會看到普通的文字內容而非表單小工具。 這對於PDF/A存檔合規性和防止多步驟審查流程中的意外編輯至關重要。
[[t:(當文件用於存檔時,立即在保存前展平。 如果需先對相同文件進行審查和更正,則直到最終保存前保持欄位為互動式。)]
)]]
## 如何在Python中安裝IronPDF?
IronPDF可從[PyPI](https://pypi.org/project/ironpdf/)獲得。 使用pip安裝:
```shell
:ProductInstall
```
安裝後,在每個腳本的頂部使用`from ironpdf import *`導入該庫。 提供[免費試用許可](https://ironpdf.com/python/get-started/license-keys/)以供評估。 生產部署需要在任何PDF操作運行之前通過`License.LicenseKey`屬性設置商用許可金鑰。
[[i:(IronPDF需要Python 3.6或更高版本。 該包包含用於將HTML轉為PDF渲染的無頭Chromium引擎,因此第一次導入可能需要片刻時間以初始化引擎。)]
)]]
## PDF表單自動化在Python中的後續步驟是什麼?
本指南介紹了如何從HTML建立PDF表單、填寫現有文件中的欄位、處理複選框和下拉欄位、從資料記錄生成批次填寫的表單,以及展平填寫的PDF以便存檔。 每個技術均使用相同的核心API:`SaveAs`寫入結果。
要探索IronPDF for Python中的相關功能:
- [從HTML模板建立PDF表單](https://ironpdf.com/python/how-to/python-create-pdf/):使用HTML和CSS設計完整的表單佈局
- [編輯和填寫現有PDF表單](https://ironpdf.com/how-to/edit-forms/):處理在IronPDF之外建立的文件中的AcroForm欄位
- [展平PDF表單欄位](https://ironpdf.com/how-to/pdf-image-flatten-csharp/):將欄位值鎖定為存檔或準備列印分發
- [從PDF中提取文字和圖像](https://ironpdf.com/python/examples/extract-pdf-text/):從填寫的文件中讀取資料
- [HTML轉換為PDF的指導](https://ironpdf.com/python/tutorials/html-to-pdf/):IronPDF所使用的渲染流程的深入介紹
- [在GitHub上探索IronPDF Python源碼範例](https://github.com/iron-software/IronPdfPython.Examples/tree/main/how-to/python-fill-pdf-form):本指南中所有場景的可運行程式碼
[啟動免費試用](#trial-license)以測試您的Python專案中的表單填寫。 當您準備好部署時,查看[許可選項](#licensing)以獲得個別開發者和企業套裝。
from ironpdf import *# Define HTML content for a simple formform_html = """<html><body><h2>Editable PDF Form</h2><form>First name: <br> <input type='text' name='firstname' value=''> <br>Last name: <br> <input type='text' name='lastname' value=''></form></body></html>"""# Instantiate a PDF rendererrenderer = ChromePdfRenderer()# Enable HTML form-to-PDF-field conversionrenderer.RenderingOptions.CreatePdfFormsFromHtml = True# Render the HTML content to a PDF filerenderer.RenderHtmlAsPdf(form_html).SaveAs("BasicForm.pdf")# Load the created PDF documentform_document = PdfDocument.FromFile("BasicForm.pdf")# Access the "firstname" field and set its valuefirst_name_field = form_document.Form.FindFormField("firstname")first_name_field.Value = "Minnie"print("FirstNameField value: {}".format(first_name_field.Value))# Access the "lastname" field and set its valuelast_name_field = form_document.Form.FindFormField("lastname")last_name_field.Value = "Mouse"print("LastNameField value: {}".format(last_name_field.Value))# Save the filled formform_document.SaveAs("FilledForm.pdf")
from ironpdf import *
# Define HTML content for a simple form
form_html = """
<html>
<body>
<h2>Editable PDF Form</h2>
<form>
First name: <br> <input type='text' name='firstname' value=''> <br>
Last name: <br> <input type='text' name='lastname' value=''>
</form>
</body>
</html>
"""
# Instantiate a PDF renderer
renderer = ChromePdfRenderer()
# Enable HTML form-to-PDF-field conversion
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
# Render the HTML content to a PDF file
renderer.RenderHtmlAsPdf(form_html).SaveAs("BasicForm.pdf")
# Load the created PDF document
form_document = PdfDocument.FromFile("BasicForm.pdf")
# Access the "firstname" field and set its value
first_name_field = form_document.Form.FindFormField("firstname")
first_name_field.Value = "Minnie"
print("FirstNameField value: {}".format(first_name_field.Value))
# Access the "lastname" field and set its value
last_name_field = form_document.Form.FindFormField("lastname")
last_name_field.Value = "Mouse"
print("LastNameField value: {}".format(last_name_field.Value))
# Save the filled form
form_document.SaveAs("FilledForm.pdf")
from ironpdf import *# Load a pre-existing PDF with form fieldsform_document = PdfDocument.FromFile("existing_form.pdf")# Enumerate available field names (helpful when exploring an unfamiliar form)for field in form_document.Form.Fields: print("Field name:", field.Name, "| Current value:", field.Value)# Fill a specific field by nameapplicant_name_field = form_document.Form.FindFormField("applicant_name")applicant_name_field.Value = "Jane Smith"# Fill a second fielddate_field = form_document.Form.FindFormField("application_date")date_field.Value = "2026-05-03"# Save the filled documentform_document.SaveAs("submitted_application.pdf")
from ironpdf import *
# Load a pre-existing PDF with form fields
form_document = PdfDocument.FromFile("existing_form.pdf")
# Enumerate available field names (helpful when exploring an unfamiliar form)
for field in form_document.Form.Fields:
print("Field name:", field.Name, "| Current value:", field.Value)
# Fill a specific field by name
applicant_name_field = form_document.Form.FindFormField("applicant_name")
applicant_name_field.Value = "Jane Smith"
# Fill a second field
date_field = form_document.Form.FindFormField("application_date")
date_field.Value = "2026-05-03"
# Save the filled document
form_document.SaveAs("submitted_application.pdf")
from ironpdf import *# Load a form with multiple field typesform_document = PdfDocument.FromFile("application_form.pdf")# Fill a text fieldform_document.Form.FindFormField("full_name").Value = "Alex Rivera"# Check a checkbox (use string "true")form_document.Form.FindFormField("agree_terms").Value = "true"# Select a radio button option by its value attributeform_document.Form.FindFormField("employment_status").Value = "full_time"# Select a dropdown option by display textform_document.Form.FindFormField("country").Value = "United States"form_document.SaveAs("completed_application.pdf")
from ironpdf import *
# Load a form with multiple field types
form_document = PdfDocument.FromFile("application_form.pdf")
# Fill a text field
form_document.Form.FindFormField("full_name").Value = "Alex Rivera"
# Check a checkbox (use string "true")
form_document.Form.FindFormField("agree_terms").Value = "true"
# Select a radio button option by its value attribute
form_document.Form.FindFormField("employment_status").Value = "full_time"
# Select a dropdown option by display text
form_document.Form.FindFormField("country").Value = "United States"
form_document.SaveAs("completed_application.pdf")
from ironpdf import *# Sample data records (replace with database or CSV source)applicants = [ {"name": "Alice Johnson", "id": "A001", "date": "2026-05-03"}, {"name": "Bob Williams", "id": "B002", "date": "2026-05-03"}, {"name": "Carol Davis", "id": "C003", "date": "2026-05-03"},]for applicant in applicants: # Load template from disk on each iteration to avoid cross-contamination form_document = PdfDocument.FromFile("application_template.pdf") # Fill each field from the data record form_document.Form.FindFormField("applicant_name").Value = applicant["name"] form_document.Form.FindFormField("applicant_id").Value = applicant["id"] form_document.Form.FindFormField("submission_date").Value = applicant["date"] # Save each filled form with a unique filename output_path = f"output/application_{applicant['id']}.pdf" form_document.SaveAs(output_path) print(f"Saved: {output_path}")
from ironpdf import *
# Sample data records (replace with database or CSV source)
applicants = [
{"name": "Alice Johnson", "id": "A001", "date": "2026-05-03"},
{"name": "Bob Williams", "id": "B002", "date": "2026-05-03"},
{"name": "Carol Davis", "id": "C003", "date": "2026-05-03"},
]
for applicant in applicants:
# Load template from disk on each iteration to avoid cross-contamination
form_document = PdfDocument.FromFile("application_template.pdf")
# Fill each field from the data record
form_document.Form.FindFormField("applicant_name").Value = applicant["name"]
form_document.Form.FindFormField("applicant_id").Value = applicant["id"]
form_document.Form.FindFormField("submission_date").Value = applicant["date"]
# Save each filled form with a unique filename
output_path = f"output/application_{applicant['id']}.pdf"
form_document.SaveAs(output_path)
print(f"Saved: {output_path}")
from ironpdf import *# Load and fill a formform_document = PdfDocument.FromFile("application_template.pdf")form_document.Form.FindFormField("full_name").Value = "Jordan Lee"form_document.Form.FindFormField("application_date").Value = "2026-05-03"# Flatten all form fields to lock values as static contentform_document.Form.Flatten()# Save the flattened, non-editable PDFform_document.SaveAs("archived_application.pdf")
from ironpdf import *
# Load and fill a form
form_document = PdfDocument.FromFile("application_template.pdf")
form_document.Form.FindFormField("full_name").Value = "Jordan Lee"
form_document.Form.FindFormField("application_date").Value = "2026-05-03"
# Flatten all form fields to lock values as static content
form_document.Form.Flatten()
# Save the flattened, non-editable PDF
form_document.SaveAs("archived_application.pdf")
What are the requirements to install IronPDF for Python?
IronPDF requires Python 3.6 or later and is available via PyPI. After installing with pip, import it in your script with `from ironpdf import *`. A free trial license is available for evaluation, with commercial options required for production use.
Does IronPDF support PDF forms with AcroForm fields?
Yes, IronPDF supports AcroForm fields, which are the standard interactive form format defined in the PDF specification. It can populate these fields using the same API as HTML-generated forms.
What is the recommended approach for filling forms with unclear field names?
When dealing with unclear field names, iterating through `form_document.Form.Fields` before filling them can provide a complete mapping of field names and their current values, aiding in filling the forms accurately.