Класс PdfInteractiveFormField
В этом разделе
Предоставляет информацию об интерактивном поле формы.
Объектная модель
Синтаксис
Ремарки
Интерактивное поле формы - это узел дерева интерактивной формы. Узел поля может быть конечным и не конечным (IsTerminalField):
- Конечное поле содержит значение поля, значение поля по умолчанию, свойства поля и аннотацию виджета (Annotation), которая описывает внешний вид поля интерактивной формы.
- Неконечное поле используется для создания группы полей интерактивной формы (Kids).
Интерактивные формы дополнительно поддерживают четыре специальных типа действий:
Поле интерактивной формы и аннотация могут включать свойство, которое указывает дополнительные действия (
AdditionalActions,
AdditionalActions), которые расширяют набор событий, которые могут инициировать выполнение действие. Это событие триггера может использоваться для создания алгоритмов проверки, вычисляемых полей и логики взаимодействия настраиваемых полей.
Пример
Вот пример, показывающий, как создать PDF документ с вычисляемым текстовым полем:
''' <summary>
''' Creates a PDF document with calculated interactive form field.
''' </summary>
''' <param name="filename">The filename.</param>
Public Shared Sub CreateDocumentWithCalculatedInteractiveFormField(filename As String)
' create PDF document
Using document As New Vintasoft.Imaging.Pdf.PdfDocument()
' create interactive form in PDF document
document.InteractiveForm = New Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfDocumentInteractiveForm(document)
' specify that the viewer application must construct appearance streams and
' appearance properties for all widget annotations
document.InteractiveForm.NeedAppearances = True
' font and font size
Dim fontSize As Single = 12
Dim font As Vintasoft.Imaging.Pdf.Tree.Fonts.PdfFont = document.FontManager.GetStandardFont(Vintasoft.Imaging.Pdf.Tree.Fonts.PdfStandardFontType.TimesRoman)
' create an empty page
Dim page As New Vintasoft.Imaging.Pdf.Tree.PdfPage(document, Vintasoft.Imaging.PaperSizeKind.A4)
' add page to the document
document.Pages.Add(page)
Dim width As Single = 60
Dim height As Single = 40
' create a rectangle that defines the object (first field) position on PDF page
Dim rect As New System.Drawing.RectangleF((page.Size.Width - width * 5) / 2, ((page.Size.Height - height) / 3) * 2, width, height)
' open PdfGraphics on page
Using graphics As Vintasoft.Imaging.Pdf.Drawing.PdfGraphics = page.GetGraphics()
' create calculator field: group of three fields
Dim calculator As New Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormField(document, "Calculator")
calculator.SetTextDefaultAppearance(font, fontSize * 1.5F, System.Drawing.Color.Black)
calculator.TextQuadding = Vintasoft.Imaging.Pdf.Tree.InteractiveForms.TextQuaddingType.Centered
' create the border style
Dim borderStyle As New Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationBorderStyle(document)
borderStyle.Style = Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationBorderStyleType.Inset
borderStyle.Width = 1
' create the appearance characteristics
Dim appearanceCharacteristics As New Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationAppearanceCharacteristics(document)
appearanceCharacteristics.BorderColor = System.Drawing.Color.Gray
' create the left text box
Dim textField As New Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormTextField(document, "Left", rect, "2")
textField.DefaultValue = textField.Value
textField.Annotation.BorderStyle = borderStyle
textField.Annotation.AppearanceCharacteristics = appearanceCharacteristics
' add the left text box to the calculator
calculator.Kids.Add(textField)
' update the rectangle that defines the object position on PDF page
rect.X += rect.Width
' draw the symbol '+' on the page
graphics.DrawString("+", font, fontSize * 1.5F, New Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Black), rect, Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Center, _
False)
' update the rectangle that defines the object position on PDF page
rect.X += rect.Width
' create the right text box
textField = New Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormTextField(document, "Right", rect, "3")
textField.DefaultValue = textField.Value
textField.Annotation.BorderStyle = borderStyle
textField.Annotation.AppearanceCharacteristics = appearanceCharacteristics
' add the right text box to the calculator
calculator.Kids.Add(textField)
' update the rectangle that defines the object position on PDF page
rect.X += rect.Width
' draw the symbol '=' on the page
graphics.DrawString("=", font, fontSize * 1.5F, New Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Black), rect, Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Center, _
False)
' create the calculator program written on JavaScript
Dim javaScriptCode As New System.Text.StringBuilder()
javaScriptCode.Append("var left = this.getField('Calculator.Left');")
javaScriptCode.Append("var right = this.getField('Calculator.Right');")
javaScriptCode.Append("var result = this.getField('Calculator.Result');")
javaScriptCode.Append("result.value = left.value + right.value;")
Dim calculatorProgram As New Vintasoft.Imaging.Pdf.Tree.PdfJavaScriptAction(document, javaScriptCode.ToString())
' update the rectangle that defines the object position on PDF page
rect.X += rect.Width
' create the result text box
textField = New Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormTextField(document, "Result", rect)
textField.IsReadOnly = True
textField.Annotation.BorderStyle = borderStyle
textField.Annotation.AppearanceCharacteristics = appearanceCharacteristics
' set a program that will calculate value of result field
textField.AdditionalActions = New Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormFieldAdditionalActions(document)
textField.AdditionalActions.Calculate = calculatorProgram
' specify that calcualtor program must be executed when page is opened
textField.Annotation.AdditionalActions.PageOpen = calculatorProgram
' add the result text box to the calculator
calculator.Kids.Add(textField)
' add result field to the calculated fields (calcualtion order)
' of the document interactive form fields
document.InteractiveForm.CalculationOrder = New Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormFieldList(document)
document.InteractiveForm.CalculationOrder.Add(textField)
' add field group to the document
document.InteractiveForm.Fields.Add(calculator)
' add annotations, associated with field group, to the page
page.Annotations = New Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationList(document)
page.Annotations.AddRange(calculator.GetAnnotations())
' update appearance of field group
calculator.UpdateAppearance()
End Using
' save the document
document.Save(filename)
End Using
End Sub
/// <summary>
/// Creates a PDF document with calculated interactive form field.
/// </summary>
/// <param name="filename">The filename.</param>
public static void CreateDocumentWithCalculatedInteractiveFormField(string filename)
{
// create PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument document = new Vintasoft.Imaging.Pdf.PdfDocument())
{
// create interactive form in PDF document
document.InteractiveForm =
new Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfDocumentInteractiveForm(document);
// specify that the viewer application must construct appearance streams and
// appearance properties for all widget annotations
document.InteractiveForm.NeedAppearances = true;
// font and font size
float fontSize = 12;
Vintasoft.Imaging.Pdf.Tree.Fonts.PdfFont font =
document.FontManager.GetStandardFont(Vintasoft.Imaging.Pdf.Tree.Fonts.PdfStandardFontType.TimesRoman);
// create an empty page
Vintasoft.Imaging.Pdf.Tree.PdfPage page = new Vintasoft.Imaging.Pdf.Tree.PdfPage(
document, Vintasoft.Imaging.PaperSizeKind.A4);
// add page to the document
document.Pages.Add(page);
float width = 60;
float height = 40;
// create a rectangle that defines the object (first field) position on PDF page
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(
(page.Size.Width - width * 5) / 2,
((page.Size.Height - height) / 3) * 2,
width, height);
// open PdfGraphics on page
using (Vintasoft.Imaging.Pdf.Drawing.PdfGraphics graphics = page.GetGraphics())
{
// create calculator field: group of three fields
Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormField calculator =
new Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormField(document, "Calculator");
calculator.SetTextDefaultAppearance(font, fontSize * 1.5f, System.Drawing.Color.Black);
calculator.TextQuadding = Vintasoft.Imaging.Pdf.Tree.InteractiveForms.TextQuaddingType.Centered;
// create the border style
Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationBorderStyle borderStyle =
new Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationBorderStyle(document);
borderStyle.Style = Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationBorderStyleType.Inset;
borderStyle.Width = 1;
// create the appearance characteristics
Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationAppearanceCharacteristics appearanceCharacteristics =
new Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationAppearanceCharacteristics(document);
appearanceCharacteristics.BorderColor = System.Drawing.Color.Gray;
// create the left text box
Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormTextField textField =
new Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormTextField(document, "Left", rect, "2");
textField.DefaultValue = textField.Value;
textField.Annotation.BorderStyle = borderStyle;
textField.Annotation.AppearanceCharacteristics = appearanceCharacteristics;
// add the left text box to the calculator
calculator.Kids.Add(textField);
// update the rectangle that defines the object position on PDF page
rect.X += rect.Width;
// draw the symbol '+' on the page
graphics.DrawString("+", font, fontSize * 1.5f,
new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Black), rect,
Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Center, false);
// update the rectangle that defines the object position on PDF page
rect.X += rect.Width;
// create the right text box
textField = new Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormTextField(document, "Right", rect, "3");
textField.DefaultValue = textField.Value;
textField.Annotation.BorderStyle = borderStyle;
textField.Annotation.AppearanceCharacteristics = appearanceCharacteristics;
// add the right text box to the calculator
calculator.Kids.Add(textField);
// update the rectangle that defines the object position on PDF page
rect.X += rect.Width;
// draw the symbol '=' on the page
graphics.DrawString("=", font, fontSize * 1.5f,
new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Black), rect,
Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Center, false);
// create the calculator program written on JavaScript
System.Text.StringBuilder javaScriptCode = new System.Text.StringBuilder();
javaScriptCode.Append("var left = this.getField('Calculator.Left');");
javaScriptCode.Append("var right = this.getField('Calculator.Right');");
javaScriptCode.Append("var result = this.getField('Calculator.Result');");
javaScriptCode.Append("result.value = left.value + right.value;");
Vintasoft.Imaging.Pdf.Tree.PdfJavaScriptAction calculatorProgram =
new Vintasoft.Imaging.Pdf.Tree.PdfJavaScriptAction(document, javaScriptCode.ToString());
// update the rectangle that defines the object position on PDF page
rect.X += rect.Width;
// create the result text box
textField = new Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormTextField(document, "Result", rect);
textField.IsReadOnly = true;
textField.Annotation.BorderStyle = borderStyle;
textField.Annotation.AppearanceCharacteristics = appearanceCharacteristics;
// set a program that will calculate value of result field
textField.AdditionalActions =
new Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormFieldAdditionalActions(document);
textField.AdditionalActions.Calculate = calculatorProgram;
// specify that calcualtor program must be executed when page is opened
textField.Annotation.AdditionalActions.PageOpen = calculatorProgram;
// add the result text box to the calculator
calculator.Kids.Add(textField);
// add result field to the calculated fields (calcualtion order)
// of the document interactive form fields
document.InteractiveForm.CalculationOrder =
new Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormFieldList(document);
document.InteractiveForm.CalculationOrder.Add(textField);
// add field group to the document
document.InteractiveForm.Fields.Add(calculator);
// add annotations, associated with field group, to the page
page.Annotations = new Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationList(document);
page.Annotations.AddRange(calculator.GetAnnotations());
// update appearance of field group
calculator.UpdateAppearance();
}
// save the document
document.Save(filename);
}
}
Иерархия наследования
Требования
Целевые платформы: .NET 8; .NET 7; .NET 6; .NET Framework 4.8, 4.7, 4.6, 4.5, 4.0, 3.5
Смотрите также