Widget (위젯)¶
This class represents a PDF Form field “widget”. Widgets technically are a special case of PDF annotations, which allow users with limited permissions to enter information in a PDF. This is primarily used for filling out forms.
주석과 마찬가지로 위젯은 PDF 페이지에 존재합니다. 주석과 유사하게, 페이지의 첫 번째 위젯은 Page.first_widget 를 통해 접근할 수 있으며, 이후 위젯은 Widget.next 속성을 통해 접근할 수 있습니다.
주석과 마찬가지로 위젯도 페이지를 사용할 수 없게 되면 페이지와의 연결을 잃습니다. 자세한 내용은 여기 를 참조하세요. 이것은 특히 위젯을 업데이트할 때 관련이 있습니다: 원본 페이지 객체를 더 이상 사용할 수 없으면 실패합니다.
클래스 API
- class Widget¶
- button_states()¶
버전 1.18.15에서 새로 추가됨
버튼 필드가 가질 수 있는 On/Off(즉, 선택/클릭 여부) 상태의 이름을 반환합니다. ‘Off’ 상태는 일반적으로 그렇게 명명되지만, ‘On’ 상태는 기능적 맥락과 관련된 이름(예: ‘Yes’, ‘Female’ 등)이 자주 지정됩니다.
이 메서드는 이러한 경우
field_value의 가능한 값을 찾는 데 도움이 됩니다.- 반환값:
normal 및 pressed-down 모양의 버튼 위젯에 대한 ‘On’ 및 ‘Off’ 이름을 가진 딕셔너리. 다음 예제는 “selected” 값이 “Male”임을 보여줍니다:
>>> print(field.field_name, field.button_states()) Gender Second person {'down': ['Male', 'Off'], 'normal': ['Male', 'Off']}
- on_state()¶
버전 1.22.2에서 새로 추가됨
체크박스 및 라디오 버튼의 “ON” 상태 값을 반환합니다. 체크박스의 경우 이것은 항상 “Yes” 값입니다. 라디오 버튼의 경우 이것은 버튼을 선택/활성화하는 값입니다.
- 반환값:
버튼을 “selected”로 설정하는 값. 체크박스가 아니고 라디오 버튼이 아닌 필드의 경우 항상
None이 반환됩니다. 체크박스의 경우 반환값은True입니다. 라디오 버튼의 경우 다음 예제에서 값은 “Male”입니다:>>> print(widget.field_name, widget.button_states()) Gender Second person {'down': ['Male', 'Off'], 'normal': ['Male', 'Off']} >>> print(widget.on_state()) Male
To set check boxes or radio buttons to
Trueor “selected”, the recommended method is the following:>>> widget.field_value = widget.on_state() # set the field to "selected" >>> widget.field_value == widget.on_state() # confirm True
- update(sync_flags=False)¶
After any changes to a widget, this method must be used to reflect the changes in the PDF.
- 매개변수:
sync_flags (bool) – if
True, the widget’sWidget.field_flagsare copied to theParentobject (if present) and all widgets named in itsKidsarray. This provides a convenient way to – for example – set all instances of the widget to read-only, no matter on which page they may occur [1].
- next¶
페이지의 다음 폼 필드를 가리킵니다. 마지막 위젯은
None을 반환합니다.
- border_color¶
필드의 테두리 색상을 정의하는 최대 4개의 float 목록. 기본값은
None으로, 테두리 스타일과 테두리 너비가 무시됩니다.
- border_style¶
필드 테두리의 선 스타일을 정의하는 문자열.
Annot.border를 참조하세요. 기본값은 “s”(“Solid”) – 연속선입니다. 위젯을 생성할 때 첫 번째 문자(대문자 또는 소문자)만 고려됩니다.
- border_width¶
테두리 선의 너비를 정의하는 float. 기본값은 1입니다.
- border_dashes¶
테두리 선의 대시 속성을 정의하는 정수 목록/튜플. border_style == “D” 이고
border_color가 제공된 경우에만 의미가 있습니다.
- choice_values¶
리스트 박스 및 콤보 박스의 유효한 선택 항목을 정의하는 문자열의 Python 시퀀스. 이러한 위젯 유형의 경우 이 속성은 필수이며 최소 두 개의 항목을 포함해야 합니다. 다른 유형에서는 무시됩니다.
- field_name¶
A mandatory string defining the field’s name. If the name contains one or more colons “.” the field is considered to be a child of a parent field. If the parent field does not exist, it will be created automatically. If the (full) name already exists anywhere in the PDF, the widget will become a new child of the existing field.
All widgets with the same name – whether or not a colon is part of it and independent of their position in the document – will share the same field value and the same field flags.
- field_label¶
“대체” 필드 이름을 포함하는 선택적 문자열. 일반적으로 필드 사용에 대한 메모, 도움말 등에 사용됩니다. 기본값은 필드 이름입니다.
- field_value¶
필드의 값.
If the field type is PDF_WIDGET_TYPE_RADIOBUTTON a value must be provided when creating the widget; it represents the “selected” state of the button in its group. The first button of a new group will be set to “selected”. Subsequent insertions of buttons with this name will automatically be set to “not selected”.
- field_flags¶
필드의 많은 속성을 정의하는 정수. 이 속성을 변경할 때는 주의하세요. 필드 유형이 변경될 수 있습니다.
- field_type¶
필드 유형을 정의하는 필수 정수. 이것은 0부터 6까지의 범위 값입니다. 위젯을 업데이트할 때 변경할 수 없습니다.
- field_type_string¶
필드 유형을 설명하는(및 필드 유형에서 파생된) 문자열.
- fill_color¶
필드의 배경색을 정의하는 최대 4개의 float 목록.
- button_caption¶
버튼 유형 필드의 캡션 문자열.
- is_signed¶
서명 필드의 서명 상태를 나타내는 bool, 그렇지 않으면
None.
- rect¶
필드를 포함하는 사각형.
- text_color¶
텍스트 색상을 정의하는 1, 3 또는 4개의 float 목록. 기본값은 검은색(
[0, 0, 0])입니다.
- text_font¶
사용할 글꼴을 정의하는 문자열. 기본값 및 잘못된 값의 대체값은 “Helv” 입니다. 유효한 글꼴 참조 이름은 아래 표를 참조하세요.
- text_fontsize¶
텍스트
fontsize를 정의하는 float. 기본값은 0이며, PDF 뷰어 소프트웨어가 주석의 사각형과 텍스트 양에 적합한 크기를 동적으로 선택하도록 합니다.
- text_maxlen¶
텍스트 문자의 최대 개수를 정의하는 정수. PDF 뷰어는 더 긴 텍스트를 받아들이지 않습니다(받아들이지 않아야 합니다).
- text_type¶
허용 가능한 텍스트 유형(예: 숫자, 날짜, 시간 등)을 정의하는 정수. 현재는 참고용으로만 사용되며 위젯을 생성하거나 업데이트할 때 무시됩니다.
- script¶
버전 1.16.12에서 새로 추가됨
위젯과 연결된 동작에 대한 JavaScript 텍스트(유니코드) 또는
None. 이것은 버튼 유형 위젯에서 지원하는 유일한 스크립트 동작입니다.
- script_stroke¶
버전 1.16.12에서 새로 추가됨
사용자가 텍스트 필드나 콤보 박스에 키 입력을 하거나 스크롤 가능한 리스트 박스에서 선택을 수정할 때 실행할 JavaScript 텍스트(유니코드). 이 동작은 키 입력의 유효성을 확인하고 거부하거나 수정할 수 있습니다. 존재하지 않으면
None.
- script_format¶
버전 1.16.12에서 새로 추가됨
JavaScript text (unicode) to be performed before the field is formatted to display its current value. This action can modify the field’s value before formatting.
Noneif not present.
- script_change¶
버전 1.16.12에서 새로 추가됨
JavaScript text (unicode) to be performed when the field’s value is changed. This action can check the new value for validity.
Noneif not present.
- script_calc¶
버전 1.16.12에서 새로 추가됨
다른 필드의 값이 변경될 때 이 필드의 값을 다시 계산하기 위해 실행할 JavaScript 텍스트(유니코드). 존재하지 않으면
None.
- script_blur¶
버전 1.22.6에서 새로 추가됨
이 필드의 포커스를 잃을 때 실행할 JavaScript 텍스트(유니코드). 존재하지 않으면
None.
- script_focus¶
버전 1.22.6에서 새로 추가됨
이 필드에 포커스를 맞출 때 실행할 JavaScript 텍스트(유니코드). 존재하지 않으면
None.
참고
위의 스크립트 중 하나를 추가 하거나 변경 하려면,
위젯 속성에 적절한 JavaScript 소스 코드를 넣으세요. 스크립트를 제거 하려면 해당 속성을
None으로 설정하세요.버튼 필드는
script만 지원합니다.
다른 스크립트 항목은 자동으로
None으로 설정됩니다.다양한 필드 유형에 대한 Adobe의 표준 스크립트에 대한 많은 정보가 포함된 이 매뉴얼 을 살펴보는 것이 좋습니다. 예를 들어, 날짜를 나타내는 텍스트 필드를 추가하려면 다음 스크립트를 저장할 수 있습니다. 이것들은 패턴 호환 날짜 형식을 보장하고 지원하는 뷰어에서 날짜 선택기를 표시합니다:
widget.script_format = 'AFDate_FormatEx("mm/dd/yyyy");' widget.script_stroke = 'AFDate_KeystrokeEx("mm/dd/yyyy");'
위젯용 표준 글꼴¶
위젯은 자체 리소스 객체 /DR 를 사용합니다. 위젯 리소스 객체는 최소한 /Font 객체를 포함해야 합니다. 위젯 글꼴은 페이지 글꼴과 독립적입니다. 현재 다음 고정 참조 이름을 사용하여 14개의 PDF 기본 글꼴을 지원하거나, 이미 존재하는 필드 글꼴의 이름을 사용합니다. 새 위젯이나 변경된 위젯에 대한 텍스트 글꼴을 지정할 때 첫 번째 테이블 열에서 하나를 선택하거나 (대소문자 지원), 이미 존재하는 폼 글꼴 중 하나를 선택 하세요. 후자의 경우 철자가 정확히 일치해야 합니다.
이미 존재하는 필드 글꼴을 확인하려면 Document.FormFonts 목록을 검사하세요.
참조 |
Base14 글꼴 이름 |
|---|---|
CoBI |
Courier-BoldOblique |
CoBo |
Courier-Bold |
CoIt |
Courier-Oblique |
Cour |
Courier |
HeBI |
Helvetica-BoldOblique |
HeBo |
Helvetica-Bold |
HeIt |
Helvetica-Oblique |
Helv |
Helvetica (기본값) |
Symb |
Symbol |
TiBI |
Times-BoldItalic |
TiBo |
Times-Bold |
TiIt |
Times-Italic |
TiRo |
Times-Roman |
ZaDb |
ZapfDingbats |
일반적으로 모든 위젯에 대해 어떤 글꼴이든 자유롭게 사용할 수 있습니다. 그러나 체크박스의 경우 ZaDb (“ZapfDingbats”) 및 fontsize 0을 사용하는 것을 권장합니다: 일반적인 뷰어는 클릭할 때 필드의 사각형에 올바른 크기의 체크 표시를 넣습니다.
지원되는 위젯 유형¶
PyMuPDF supports the creation and update of most widget types.
텍스트 (
PDF_WIDGET_TYPE_TEXT)푸시 버튼 (
PDF_WIDGET_TYPE_BUTTON)체크박스 (
PDF_WIDGET_TYPE_CHECKBOX)콤보 박스 (
PDF_WIDGET_TYPE_COMBOBOX)리스트 박스 (
PDF_WIDGET_TYPE_LISTBOX)radio button (
PDF_WIDGET_TYPE_RADIOBUTTON): PyMuPDF supports the creation and update of Radio Button Groups (RBGs). Adding a radio button widget will create a Radio Button Group if the field name is new. If the field name already exists, the RBG will be extended [2].signature (
PDF_WIDGET_TYPE_SIGNATURE) read only – no update or creation of signatures and no signing support.
The Relationship between Form Fields and Widgets¶
A form field is a logical object in the document’s form field tree. It may have one or more widgets, which are the visual appearances of that field on one or more pages. A widget is therefore the page-bound instance of a form field.
The connection between a widget and its form field is established through the widget’s /Parent entry, which references the form field. Conversely, the form field’s /Kids array contains references to all widgets that visually represent that field.
Form fields themselves are not tied to any page; they exist solely in the document’s AcroForm hierarchy. Widgets, however, are page annotations and are always associated with a specific page.
A single form field may be represented by multiple widgets. For example, a field may have one widget on page 1 and another on page 2 (or even multiple widgets on the same page). In this case, both widgets share the same form field as their parent. Changing the value of one widget automatically updates the value shown by all other widgets of that field.
Form Field Hierarchy¶
Form fields support hierarchical naming. A form field may have child fields, forming a logical structure. The hierarchy is defined by the /Parent entry of a child field, which references its parent field. The parent field’s /Kids array contains references to all its child fields.
This hierarchy is reflected in the field’s name. For example, a field named “Address.Street” has a parent field “Address” and a child field “Street”. The parent may have additional children such as “Address.City” or “Address.ZipCode”.
Automatic Hierarchy Creation via Dotted Names¶
Using dots (“.”) in a widget’s field_name automatically creates or updates the corresponding form field hierarchy. For example:
Creating a widget named “Person.Name” creates or updates the form field “Person” and adds the widget as a child of “Person”.
Creating a widget named “Person.Address” adds another child field under “Person”.
Creating a widget named “Person.MaritalStatus” adds yet another child field.
In all cases, the widget becomes the visual representation of the terminal field in the hierarchy.
This mechanism allows complex information structures to be expressed naturally within a PDF form.
각주
