> Java > java지도 시간 > 본문

Java에서 PDF 양식 필드를 만들고 채우는 방법(코드 예)

不言
풀어 주다: 2019-01-24 11:34:48
앞으로
4755명이 탐색했습니다.

이 문서의 내용은 Java에서 PDF 양식 필드(코드 예제)를 만들고 채우는 방법에 대한 것입니다. 필요한 친구가 참고할 수 있기를 바랍니다.

양식 필드는 용도에 따라 다양한 유형으로 나눌 수 있습니다. 일반적인 유형으로는 텍스트 상자, 여러 줄 텍스트 상자, 비밀번호 상자, 숨겨진 필드, 확인란, 라디오 버튼 상자 및 드롭다운 선택 상자가 있습니다. 사용자 입력 또는 선택한 데이터를 수집하는 데 사용됩니다. 다음 예에서는 Java 프로그래밍을 통해 PDF에 양식 필드를 추가하고 채우는 방법을 공유합니다. 여기서 양식 필드를 채우는 것은 두 가지 상황으로 나눌 수 있는데, 하나는 양식 필드를 생성할 때 채우는 것이고, 다른 하나는 이미 양식 필드를 생성한 문서를 채우는 것입니다. 또한 양식 필드를 생성하고 작성한 문서의 경우 수정 및 편집을 방지하기 위해 읽기 전용으로 설정할 수도 있습니다.

핵심 요약:

1. 양식 필드 만들기

2. 양식 필드 채우기

3. 양식 필드를 읽기 전용으로 설정

도구: Free Spire.PDF for Java v2.0.0(무료 버전) )

JarFile import

Steps1:Java 프로그램에 새 폴더를 만들고 이름을 Lib로 지정합니다. 그리고 제품 패키지에 있는 두 개의 jar 파일을 새로 생성된 폴더에 복사합니다.

2단계: 파일을 복사한 후 참조 클래스 라이브러리에 추가합니다. 이 두 jar 파일을 선택하고 마우스 오른쪽 버튼을 클릭한 다음 "Build Path" - "Add to Build Path"를 선택합니다. . 인용을 완료하세요.

Java코드 예제(참조용)

1.PDF 만들기 및 채우기양식 필드

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);              
    }
}
로그인 후 복사

만들기(채우기) 효과:

2.기존 양식 필드 문서 로드 및 채우기

테스트 문서는 다음과 같습니다.

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);
    }
}
로그인 후 복사

채우기 효과:

3. 양식 필드 제한 편집 (읽기 전용)

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");   
     }
  }
로그인 후 복사

생성된 문서에서 양식 필드는 편집할 수 없으며 읽기 전용입니다.

위 내용은 Java에서 PDF 양식 필드를 만들고 채우는 방법(코드 예)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:cnblogs.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!