Home Java javaTutorial How to create and fill PDF form fields in Java (code example)

How to create and fill PDF form fields in Java (code example)

Jan 24, 2019 am 11:34 AM
java

The content of this article is about how to create and fill PDF form fields (code examples) in Java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Form fields can be divided into many different types according to their uses. Common ones include text boxes, multi-line text boxes, password boxes, hidden fields, check boxes, radio buttons and drop-down selection boxes, etc. The purpose is to collect user input or selected data. In the following example, we will share how to add and fill form fields in PDF through Java programming. Filling the form fields here can be divided into two situations, one is filling when creating the form field, and the other is filling in the document that has already created the form field. In addition, for documents that have created form fields and filled them out, you can also set read-only to prevent modification and editing.

Summary of key points:

1. Create form fields

2. Fill in form fields

3.Set form fields read-only

Tools: Free Spire.PDF for Java v2.0.0 (free version)

JarFile import

Steps1:Create a new folder in the Java program and name it Lib. And copy the two jar files in the product package to the newly created folder.

Step 2:After copying the files, add them to the reference class library: Select these two jar files and right-click , select “Build Path” – “Add to Build Path”. Complete the citation.

JavaCode sample (for reference)

1.Create and fill PDFForm fields

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.fields.*;
import com.spire.pdf.graphics.*;

public class AddFormFieldsToPdf {

    public static void main(String[] args) throws Exception {
        
        //创建PdfDocument对象,并添加页面
        PdfDocument doc = new PdfDocument();        
        PdfPageBase page = doc.getPages().add();

        //初始化位置变量
        float baseX = 100;
        float baseY = 0;

        //创建画刷对象
        PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
        PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.black));
        
        //创建TrueType字体
        PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,10),true); 

        //添加文本框
        String text = "姓名:";//添加文本
        page.getCanvas().drawString(text, font, brush1, new Point2D.Float(0, baseY));//在PDF中绘制文字
        Rectangle2D.Float tbxBounds = new Rectangle2D.Float(baseX, baseY , 150, 15);//创建Rectangle2D对象
        PdfTextBoxField textBox = new PdfTextBoxField(page, "TextBox");//创建文本框对象
        textBox.setBounds(tbxBounds);//设置文本框的Bounds
        textBox.setText("刘兴");//填充文本框
        textBox.setFont(font);//应用文本框的字体
        doc.getForm().getFields().add(textBox);//添加文本框到PDF域的集合
        baseY +=25;

        //添加复选框
        page.getCanvas().drawString("所在院系:", font, brush1, new Point2D.Float(0, baseY));
        java.awt.geom.Rectangle2D.Float rec1 = new java.awt.geom.Rectangle2D.Float(baseX, baseY, 15, 15);
        PdfCheckBoxField checkBoxField = new PdfCheckBoxField(page, "CheckBox1");//创建第一个复选框对象
        checkBoxField.setBounds(rec1);
        checkBoxField.setChecked(false);//填充复选框
        page.getCanvas().drawString("经管系", font, brush2, new Point2D.Float(baseX + 20, baseY));
        java.awt.geom.Rectangle2D.Float rec2 = new java.awt.geom.Rectangle2D.Float(baseX + 70, baseY, 15, 15);
        PdfCheckBoxField checkBoxField1 = new PdfCheckBoxField(page, "CheckBox2");//创建第二个复选框对象
        checkBoxField1.setBounds(rec2);
        checkBoxField1.setChecked(true);//填充复选框
        page.getCanvas().drawString("创新班", font,  brush2, new Point2D.Float(baseX+90, baseY));      
        doc.getForm().getFields().add(checkBoxField);//添加复选框到PDF
        baseY += 25;

        //添加列表框
        page.getCanvas().drawString("录取批次:", font, brush1, new Point2D.Float(0, baseY));
        java.awt.geom.Rectangle2D.Float rec = new java.awt.geom.Rectangle2D.Float(baseX, baseY, 150, 50);
        PdfListBoxField listBoxField = new PdfListBoxField(page, "ListBox");//创建列表框对象
        listBoxField.getItems().add(new PdfListFieldItem("第一批次", "item1"));
        listBoxField.getItems().add(new PdfListFieldItem("第二批次", "item2"));
        listBoxField.getItems().add(new PdfListFieldItem("第三批次", "item3"));;
        listBoxField.setBounds(rec);
        listBoxField.setFont(font);
        listBoxField.setSelectedIndex(0);//填充列表框
        doc.getForm().getFields().add(listBoxField);//添加列表框到PDF
        baseY += 60;

        //添加单选按钮
        page.getCanvas().drawString("招收方式:", font, brush1, new Point2D.Float(0, baseY));
        PdfRadioButtonListField radioButtonListField = new PdfRadioButtonListField(page, "Radio");//创建单选按钮对象
        PdfRadioButtonListItem radioItem1 = new PdfRadioButtonListItem("Item1");//创建第一个单选按钮
        radioItem1.setBounds(new Rectangle2D.Float(baseX, baseY, 15, 15));
        page.getCanvas().drawString("全日制", font, brush2, new Point2D.Float(baseX + 20, baseY));
        PdfRadioButtonListItem radioItem2 = new PdfRadioButtonListItem("Item2");//创建第二个单选按钮
        radioItem2.setBounds(new Rectangle2D.Float(baseX + 70, baseY, 15, 15));
        page.getCanvas().drawString("成人教育", font, brush2, new Point2D.Float(baseX + 90, baseY));
        radioButtonListField.getItems().add(radioItem1);
        radioButtonListField.getItems().add(radioItem2);
        radioButtonListField.setSelectedIndex(0);//选择填充第一个单选按钮
        doc.getForm().getFields().add(radioButtonListField);//添加单选按钮到PDF
        baseY += 25;

        //添加组合框
        page.getCanvas().drawString("最高学历:", font, brush1, new Point2D.Float(0, baseY));
        Rectangle2D.Float cmbBounds = new Rectangle2D.Float(baseX, baseY, 150, 15);//创建cmbBounds对象
        PdfComboBoxField comboBoxField = new PdfComboBoxField(page, "ComboBox");//创建comboBoxField对象
        comboBoxField.setBounds(cmbBounds);
        comboBoxField.getItems().add(new PdfListFieldItem("博士", "item1"));
        comboBoxField.getItems().add(new PdfListFieldItem("硕士", "itme2"));
        comboBoxField.getItems().add(new PdfListFieldItem("本科", "item3"));
        comboBoxField.getItems().add(new PdfListFieldItem("大专", "item4"));
        comboBoxField.setSelectedIndex(0);      
        comboBoxField.setFont(font);
        doc.getForm().getFields().add(comboBoxField);//添加组合框到PDF
        baseY += 25;

        //添加签名域
        page.getCanvas().drawString("本人签字确认\n以上信息属实:", font, brush1, new Point2D.Float(0, baseY));
        PdfSignatureField sgnField= new PdfSignatureField(page,"sgnField");//创建sgnField对象
        Rectangle2D.Float sgnBounds = new Rectangle2D.Float(baseX, baseY, 150, 80);//创建sgnBounds对象
        sgnField.setBounds(sgnBounds);          
        doc.getForm().getFields().add(sgnField);//添加sgnField到PDF
        baseY += 90;

        //添加按钮
        page.getCanvas().drawString("", font, brush1, new Point2D.Float(0, baseY));
        Rectangle2D.Float btnBounds = new Rectangle2D.Float(baseX, baseY, 50, 15);//创建btnBounds对象
        PdfButtonField buttonField = new PdfButtonField(page, "Button");//创建buttonField对象
        buttonField.setBounds(btnBounds);
        buttonField.setText("提交");//设置按钮显示文本
        buttonField.setFont(font);
        doc.getForm().getFields().add(buttonField);//添加按钮到PDF  
        
        //保存文档
        doc.saveToFile("result.pdf", FileFormat.PDF);              
    }
}
Copy after login

Create (fill) effect:

2.Load and populate the existing form field document

The test document is as follows:

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.*;

public class FillFormField_PDF{
    public static void main(String[] args){
        
        //创建PdfDocument对象,并加载PDF文档
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("output.pdf");

        //获取文档中的域
        PdfFormWidget form = (PdfFormWidget) doc.getForm();        
        //获取域控件集合
        PdfFormFieldWidgetCollection formWidgetCollection = form.getFieldsWidget();

        //遍历域控件并填充数据
        for (int i = 0; i < formWidgetCollection.getCount(); i++) {
            
            PdfField field = formWidgetCollection.get(i);         
            if (field instanceof PdfTextBoxFieldWidget) {
                PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget) field;
                textBoxField.setText("吴 敏");
            }  
            if (field instanceof PdfCheckBoxWidgetFieldWidget) {
                PdfCheckBoxWidgetFieldWidget checkBoxField = (PdfCheckBoxWidgetFieldWidget) field;
                switch(checkBoxField.getName()){
                case "CheckBox1":
                    checkBoxField.setChecked(true);
                    break;
                case "CheckBox2":
                    checkBoxField.setChecked(true);
                    break;
                }
            }
            if (field instanceof PdfRadioButtonListFieldWidget) {
                PdfRadioButtonListFieldWidget radioButtonListField = (PdfRadioButtonListFieldWidget) field;
                radioButtonListField.setSelectedIndex(1);
            }
            if (field instanceof PdfListBoxWidgetFieldWidget) {
                PdfListBoxWidgetFieldWidget listBox = (PdfListBoxWidgetFieldWidget) field;
                listBox.setSelectedIndex(1);
            }
            
            if (field instanceof PdfComboBoxWidgetFieldWidget) {
                PdfComboBoxWidgetFieldWidget comboBoxField = (PdfComboBoxWidgetFieldWidget) field;
                comboBoxField.setSelectedIndex(1);
            }
        }
        
        //保存文档
        doc.saveToFile("FillFormFields.pdf", FileFormat.PDF);
    }
}
Copy after login

Filling effect:

3.Restrict form field editing (Read-only)

import com.spire.pdf.PdfDocument;

public class FieldReadonly_PDF {
    public static void main(String[] args) throws Exception {
    {
    //创建PdfDocument对象,并加载包含表单域的PDF文档
    PdfDocument pdf = new PdfDocument();
    pdf.loadFromFile("test.pdf");
    
        //将文档中的所有表单域设置为只读
        pdf.getForm().setReadOnly(true);
    
        //保存文档
       pdf.saveToFile("result.pdf");   
     }
  }
Copy after login

In the generated document, the form fields will not be editable and will be read-only

The above is the detailed content of How to create and fill PDF form fields in Java (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles