PDF: Редактирование интерактивных PDF полей документа в WPF
В этом разделе
Класс
WpfPdfAnnotationTool позволяет редактировать интерактивные поля на PDF странице в WPF просмотрщике изображений. Класс редактирует интерактивные поля в двух режимах: 'Markup' и 'Edit'.
В режиме 'Markup' класс
WpfPdfAnnotationTool:
- Позволяет 'просматривать' PDF аннотации, 'изменять' PDF markup-аннотации и 'заполнять' интерактивные PDF поля.
- Вызывает события и обрабатывает сгенерированные события (Activate, MouseDown, Keystoke и т.д.) для аннотаций и интерактивных полей.
- Позволяет копировать и вставлять PDF markup-аннотации.
- Использует WpfPdfMarkupAnnotationView.MarkupTransformer в качестве контроллера взаимодействия для markup-аннотаций и WpfPdfAnnotationView.ViewTransformer в качестве контроллера взаимодействия для не markup-аннотаций и интерактивных полей.
В режиме 'Edit' класс
WpfPdfAnnotationTool:
- Позволяет 'просматривать' и 'редактировать' PDF аннотации и интерактивные PDF поля.
- НЕ вызывает события и не обрабатывает сгенерированные события (Activate, MouseDown, Keystoke и т. д.) для аннотаций и интерактивных полей.
- Позволяет копировать и вставлять любые аннотации и интерактивные поля.
- Позволяет выбрать несколько аннотаций и интерактивных полей, выбранные аннотации можно перемещать как группу.
- Показывает все (не скрытые и скрытые) аннотации и интерактивные поля.
- Может использоваться специальное выделение полей.
- Использует WpfPdfAnnotationView.EditTransformer в качестве контроллера взаимодействия.
Вот C#/VB.NET код, который демонстрирует, как создать визуальный инструмент для отображения и взаимодействия с аннотациями и полями интерактивной PDF формы:
/// <summary>
/// Creates the PDF annotation tool with JavaScript support.
/// </summary>
/// <param name="viewer">The image viewer.</param>
public static Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationTool CreatePdfAnnotationToolWithJavaScriptSupport(
Vintasoft.Imaging.Wpf.UI.WpfImageViewer viewer)
{
// create PDF JavaScript application
Vintasoft.Imaging.Pdf.Wpf.UI.JavaScript.WpfPdfJsApp jsApp =
new Vintasoft.Imaging.Pdf.Wpf.UI.JavaScript.WpfPdfJsApp();
// add PDF documents, which are associated with images in viewer,
// to the document set of PDF JavaScript application
jsApp.RegisterImageViewer(viewer);
// create PdfJavaScriptActionExecutor for PDF JavaScript application
jsApp.ActionExecutor = new Vintasoft.Imaging.Pdf.JavaScript.PdfJavaScriptActionExecutor(
jsApp, new Vintasoft.Imaging.Pdf.JavaScriptApi.PdfJsConsole());
// create PdfAnnotationTool
Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationTool annotationTool =
new Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationTool(jsApp, true);
annotationTool.InteractionMode = Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationInteractionMode.Markup;
// create an application action executor
Vintasoft.Imaging.Pdf.PdfActionCompositeExecutor applicationActionExecutor =
new Vintasoft.Imaging.Pdf.PdfActionCompositeExecutor();
// add executor for PdfJavaScriptAction to the application action executor
applicationActionExecutor.Items.Add(jsApp.ActionExecutor);
// add executor for PdfGotoAction to the application action executor
applicationActionExecutor.Items.Add(new Vintasoft.Imaging.Pdf.Wpf.UI.WpfPdfGotoActionExecutor(viewer));
// add executor for PdfNamedAction to the application action executor
applicationActionExecutor.Items.Add(new Vintasoft.Imaging.Pdf.Wpf.UI.WpfPdfNamedActionExecutor(viewer));
// add executor for PdfResetFormAction to the application action executor
applicationActionExecutor.Items.Add(
new Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationToolResetFormActionExecutor(annotationTool));
// add executor for PdfAnnotationHideAction to the application action executor
applicationActionExecutor.Items.Add(
new Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationToolAnnotationHideActionExecutor(annotationTool));
// add executor for PdfUriAction to the application action executor,
// executor is located in WpfPdfDemosCommonCode
//applicationActionExecutor.Items.Add(new PdfUriActionExecutor());
// add executor for PdfLaunchAction to the application action executor,
// executor is located in WpfPdfDemosCommonCode
//applicationActionExecutor.Items.Add(new PdfLaunchActionExecutor());
// add executor for PdfSubmitFormAction to the application action executor,
// executor is located in WpfPdfDemosCommonCode
//applicationActionExecutor.Items.Add(new PdfSubmitActionExecutor(viewer));
// add the default executor (for PdfResetFormAction and PdfAnnotationHideAction)
// to the application action executor
applicationActionExecutor.Items.Add(new Vintasoft.Imaging.Pdf.PdfActionExecutor());
// set the application action executor as action executor of PDF annotation tool
annotationTool.ActionExecutor = applicationActionExecutor;
// create a document-level actions executor
Vintasoft.Imaging.Pdf.PdfDocumentLevelActionsExecutor documentLevelActionsExecutor =
new Vintasoft.Imaging.Pdf.PdfDocumentLevelActionsExecutor(jsApp);
// set the application action executor as action executor of the document-level actions executor
documentLevelActionsExecutor.ActionExecutor = applicationActionExecutor;
return annotationTool;
}
''' <summary>
''' Creates the PDF annotation tool with JavaScript support.
''' </summary>
''' <param name="viewer">The image viewer.</param>
Public Shared Function CreatePdfAnnotationToolWithJavaScriptSupport(viewer As Vintasoft.Imaging.Wpf.UI.WpfImageViewer) As Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationTool
' create PDF JavaScript application
Dim jsApp As New Vintasoft.Imaging.Pdf.Wpf.UI.JavaScript.WpfPdfJsApp()
' add PDF documents, which are associated with images in viewer,
' to the document set of PDF JavaScript application
jsApp.RegisterImageViewer(viewer)
' create PdfJavaScriptActionExecutor for PDF JavaScript application
jsApp.ActionExecutor = New Vintasoft.Imaging.Pdf.JavaScript.PdfJavaScriptActionExecutor(jsApp, New Vintasoft.Imaging.Pdf.JavaScriptApi.PdfJsConsole())
' create PdfAnnotationTool
Dim annotationTool As New Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationTool(jsApp, True)
annotationTool.InteractionMode = Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationInteractionMode.Markup
' create an application action executor
Dim applicationActionExecutor As New Vintasoft.Imaging.Pdf.PdfActionCompositeExecutor()
' add executor for PdfJavaScriptAction to the application action executor
applicationActionExecutor.Items.Add(jsApp.ActionExecutor)
' add executor for PdfGotoAction to the application action executor
applicationActionExecutor.Items.Add(New Vintasoft.Imaging.Pdf.Wpf.UI.WpfPdfGotoActionExecutor(viewer))
' add executor for PdfNamedAction to the application action executor
applicationActionExecutor.Items.Add(New Vintasoft.Imaging.Pdf.Wpf.UI.WpfPdfNamedActionExecutor(viewer))
' add executor for PdfResetFormAction to the application action executor
applicationActionExecutor.Items.Add(New Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationToolResetFormActionExecutor(annotationTool))
' add executor for PdfAnnotationHideAction to the application action executor
applicationActionExecutor.Items.Add(New Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationToolAnnotationHideActionExecutor(annotationTool))
' add executor for PdfUriAction to the application action executor,
' executor is located in WpfPdfDemosCommonCode
'applicationActionExecutor.Items.Add(new PdfUriActionExecutor());
' add executor for PdfLaunchAction to the application action executor,
' executor is located in WpfPdfDemosCommonCode
'applicationActionExecutor.Items.Add(new PdfLaunchActionExecutor());
' add executor for PdfSubmitFormAction to the application action executor,
' executor is located in WpfPdfDemosCommonCode
'applicationActionExecutor.Items.Add(new PdfSubmitActionExecutor(viewer));
' add the default executor (for PdfResetFormAction and PdfAnnotationHideAction)
' to the application action executor
applicationActionExecutor.Items.Add(New Vintasoft.Imaging.Pdf.PdfActionExecutor())
' set the application action executor as action executor of PDF annotation tool
annotationTool.ActionExecutor = applicationActionExecutor
' create a document-level actions executor
Dim documentLevelActionsExecutor As New Vintasoft.Imaging.Pdf.PdfDocumentLevelActionsExecutor(jsApp)
' set the application action executor as action executor of the document-level actions executor
documentLevelActionsExecutor.ActionExecutor = applicationActionExecutor
Return annotationTool
End Function
Вот C#/VB.NET код, который демонстрирует, как начать создание интерактивного поля PDF документа:
/// <summary>
/// Adds and builds a button form field.
/// </summary>
/// <param name="annotationTool">The PDF annotation tool, which will build a field.</param>
public static void AddAndBuildButtonField(
Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationTool annotationTool)
{
Vintasoft.Imaging.Pdf.Tree.PdfPage focusedPage = annotationTool.FocusedPage;
if (focusedPage == null)
throw new System.InvalidOperationException();
// create a Button form field
Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormPushButtonField field =
new Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormPushButtonField(
focusedPage.Document,
GetFieldName(focusedPage.Document, null, "Button{0}"),
new System.Drawing.RectangleF(0, 0, 150, 22));
// set the field appearance generator
Vintasoft.Imaging.Pdf.Tree.InteractiveForms.AppearanceGenerators.PdfButton3DBorderFieldAppearanceGenerator appearanceGenerator =
new Vintasoft.Imaging.Pdf.Tree.InteractiveForms.AppearanceGenerators.PdfButton3DBorderFieldAppearanceGenerator();
field.Annotation.AppearanceGenerator = appearanceGenerator;
appearanceGenerator.NormalCaption = "JavaScript 'Hello!'";
appearanceGenerator.FontSize = 14;
// if tool mode does not allow to build annotation
if (annotationTool.InteractionMode != Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationInteractionMode.Edit)
// change the tool mode
annotationTool.InteractionMode = Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationInteractionMode.Edit;
// set JavaScript action to Activate trigger event
field.Annotation.ActivateAction =
new Vintasoft.Imaging.Pdf.Tree.PdfJavaScriptAction(focusedPage.Document, "app.alert('Hello!', 3);");
// add and build annotation
annotationTool.AddAndBuildFormField(field);
}
/// <summary>
/// Returns the name of new field.
/// </summary>
/// <param name="document">PDF document.</param>
/// <param name="parentField">The parent interactive form field.</param>
/// <param name="fieldNameFormat">The format of field name.</param>
/// <returns>The name of new field.</returns>
private static string GetFieldName(
Vintasoft.Imaging.Pdf.PdfDocument document,
Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormField parentField,
string fieldNameFormat)
{
string format = fieldNameFormat;
if (parentField != null)
format = string.Format("{0}.{1}", parentField.FullyQualifiedName, fieldNameFormat);
if (document.InteractiveForm == null)
return string.Format(fieldNameFormat, 1);
int i = 1;
while (document.InteractiveForm.FindField(string.Format(format, i)) != null)
i++;
return string.Format(fieldNameFormat, i);
}
''' <summary>
''' Adds and builds a button form field.
''' </summary>
''' <param name="annotationTool">The PDF annotation tool, which will build a field.</param>
Public Shared Sub AddAndBuildButtonField(annotationTool As Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationTool)
Dim focusedPage As Vintasoft.Imaging.Pdf.Tree.PdfPage = annotationTool.FocusedPage
If focusedPage Is Nothing Then
Throw New System.InvalidOperationException()
End If
' create a Button form field
Dim field As New Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormPushButtonField(focusedPage.Document, GetFieldName(focusedPage.Document, Nothing, "Button{0}"), New System.Drawing.RectangleF(0, 0, 150, 22))
' set the field appearance generator
Dim appearanceGenerator As New Vintasoft.Imaging.Pdf.Tree.InteractiveForms.AppearanceGenerators.PdfButton3DBorderFieldAppearanceGenerator()
field.Annotation.AppearanceGenerator = appearanceGenerator
appearanceGenerator.NormalCaption = "JavaScript 'Hello!'"
appearanceGenerator.FontSize = 14
' if tool mode does not allow to build annotation
If annotationTool.InteractionMode <> Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationInteractionMode.Edit Then
' change the tool mode
annotationTool.InteractionMode = Vintasoft.Imaging.Pdf.Wpf.UI.Annotations.WpfPdfAnnotationInteractionMode.Edit
End If
' set JavaScript action to Activate trigger event
field.Annotation.ActivateAction = New Vintasoft.Imaging.Pdf.Tree.PdfJavaScriptAction(focusedPage.Document, "app.alert('Hello!', 3);")
' add and build annotation
annotationTool.AddAndBuildFormField(field)
End Sub
''' <summary>
''' Returns the name of new field.
''' </summary>
''' <param name="document">PDF document.</param>
''' <param name="parentField">The parent interactive form field.</param>
''' <param name="fieldNameFormat">The format of field name.</param>
''' <returns>The name of new field.</returns>
Private Shared Function GetFieldName(document As Vintasoft.Imaging.Pdf.PdfDocument, parentField As Vintasoft.Imaging.Pdf.Tree.InteractiveForms.PdfInteractiveFormField, fieldNameFormat As String) As String
Dim format As String = fieldNameFormat
If parentField IsNot Nothing Then
format = String.Format("{0}.{1}", parentField.FullyQualifiedName, fieldNameFormat)
End If
If document.InteractiveForm Is Nothing Then
Return String.Format(fieldNameFormat, 1)
End If
Dim i As Integer = 1
While document.InteractiveForm.FindField(String.Format(format, i)) IsNot Nothing
i += 1
End While
Return String.Format(fieldNameFormat, i)
End Function