diff --git a/Document-Processing-toc.html b/Document-Processing-toc.html index 6a84ad4307..4dc903c603 100644 --- a/Document-Processing-toc.html +++ b/Document-Processing-toc.html @@ -2452,6 +2452,14 @@
  • Document Load Events
  • +
  • + Document Handling + +
  • Navigations
  • @@ -2527,6 +2536,7 @@
  • Keyboard Shortcuts
  • Gesture Events
  • Liquid Glass UI
  • +
  • Digital Signature
  • @@ -3043,6 +3053,29 @@
  • +
  • + .NET MAUI + +
  • diff --git a/Document-Processing/PDF/PDF-Viewer/maui/Digital-Signature.md b/Document-Processing/PDF/PDF-Viewer/maui/Digital-Signature.md new file mode 100644 index 0000000000..bf5146468f --- /dev/null +++ b/Document-Processing/PDF/PDF-Viewer/maui/Digital-Signature.md @@ -0,0 +1,502 @@ +--- +layout: post +title: Digital Signature in .NET MAUI PDF Viewer | Syncfusion +description: Learn how to validate, inspect, and apply digital signatures in the Syncfusion® .NET MAUI PDF Viewer (SfPdfViewer). +platform: document-processing +control: SfPdfViewer +documentation: ug +keywords: .net maui pdf viewer, digital signature, pdf signature validation, certificate signing, pdf signing, signature panel +--- + +# Digital Signature in .NET MAUI PDF Viewer + +The digital signature feature in the .NET MAUI PDF Viewer allows users to validate, inspect, and digitally sign PDF documents directly within the viewer. It supports certificate-based signing, signature validation, signature navigation, certificate inspection, and custom signing workflows. + +## Features + +The PDF Viewer supports the following digital signature capabilities: + +* Digital signature validation +* Signature field detection +* Signed and unsigned signature identification +* Certificate inspection +* Programmatic signing +* UI-based signing +* Multi-signature support +* Signature navigation +* Custom signing provider integration + +## Enable Digital Signature Support + +Use the `DigitalSignatureSettings` property to configure digital signature functionality in the PDF Viewer. The `DigitalSignatureSettings` class provides settings that control validation, signing, signature panel behavior, and custom signing providers. The `EnableValidation` API Enables automatic signature validation during document load and after signing operations. The `EnableSigning` allows users to digitally sign unsigned signature fields. + +{% tabs %} +{% highlight c# %} +pdfViewer.DigitalSignatureSettings.EnableValidation = true; +pdfViewer.DigitalSignatureSettings.EnableSigning = true; +{% endhighlight %} +{% endtabs %} + +### Show Signature Panel + +The `IsSignaturePanelVisible` API is used to control the visibility of the signature panel, which displays both signed and unsigned signature fields. + +* When set to `true`, the signature panel is displayed. +* When set to `false`, the signature panel is hidden. + +By default, the `IsSignaturePanelVisible` property is set to `false`. + +{% tabs %} +{% highlight c# %} +pdfViewer.DigitalSignatureSettings.IsSignaturePanelVisible = true; +{% endhighlight %} +{% endtabs %} + +### Show Validation Banner + +Displays the overall document signature status. + +{% tabs %} +{% highlight c# %} +pdfViewer.DigitalSignatureSettings.IsValidationBannerVisible = true; +{% endhighlight %} +{% endtabs %} + +### Configure Signature Field Tap Action + +The SignatureFieldTapAction property determines the action performed when a user taps an unsigned signature field. +When `EnableSigning` is set to true, tapping an unsigned signature field opens the digital signing dialog, allowing the user to digitally sign the document using a certificate. +If `SignatureFieldTapAction` is set to `SignatureFieldTapAction.ESignature`, tapping an unsigned signature field initiates the electronic signature workflow, allowing the user to add an e-signature instead of opening the digital signing dialog. + +By default, the SignatureFieldTapAction property is set to `SignatureFieldTapAction.Auto`. + +{% tabs %} +{% highlight c# %} +pdfViewer.DigitalSignatureSettings.SignatureFieldTapAction = SignatureFieldTapAction.ESignature; +{% endhighlight %} +{% endtabs %} + +Available values: + +| Value | Description | +|---------|-------------| +| Auto | Opens the digital signing dialog when EnableSigning is enabled. Otherwise, uses the default signature field interaction. | +| ESignature | Initiates the electronic signature workflow when an unsigned signature field is tapped. | + +### Configure Custom Signing Provider + +Use a custom signing provider to integrate cloud signing services, HSM devices, smart cards, or enterprise PKI systems. + +{% tabs %} +{% highlight c# %} +pdfViewer.DigitalSignatureSettings.SigningProvider = new CustomSignatureProvider(); +{% endhighlight %} +{% endtabs %} + +## Validate Digital Signatures + +Use the ValidateSignaturesAsync method to validate all digital signatures present in the loaded PDF document. This method validates each signed signature field and returns the validation result for every signature in the document. + +Validation results include: +* Signature validity +* Trust status +* Certificate information + +{% tabs %} +{% highlight c# %} +IReadOnlyList results = await pdfViewer.ValidateSignaturesAsync(); +{% endhighlight %} +{% endtabs %} + +## Signature Validation Workflow + +When digital signature validation is enabled using the `EnableValidation` property, the PDF Viewer automatically validates all signed signature fields in the loaded document and updates the associated validation UI elements. + +The validation workflow consists of the following steps: +1. The PDF document is loaded. +2. Signature fields are detected. +3. Signed signature fields are validated. +4. Validation status is computed. +5. The signature panel is populated. +6. The validation banner is updated. +The overall document status is determined as follows: +* Invalid if any signature is invalid. +* Unknown if any signature cannot be trusted. +* Valid if all signatures are valid. + +## Digital Signature Panel + +The Signature Panel displays all digital signatures in the document. + +### Configure Signature Panel +Use the SignaturePanelSettings property to customize the information and actions displayed in the digital signature panel. +The following APIs are available: +`ShowSignedSignatures` controls whether signed signature fields are displayed in the signature panel. When set to false, signed signature fields are hidden. +`ShowUnsignedSignatures` controls whether unsigned signature fields are displayed in the signature panel. When set to false, unsigned signature fields are hidden. +`EnableNavigation` controls whether users can navigate to signature fields from the signature panel. When set to false, navigation through signature panel interactions is disabled. +`ShowCertificateDetailsAction` controls whether the certificate details button is displayed for signed signature fields in the signature panel. + +{% tabs %} +{% highlight c# %} +pdfViewer.DigitalSignatureSettings.SignaturePanelSettings + .ShowSignedSignatures = true; + +pdfViewer.DigitalSignatureSettings.SignaturePanelSettings + .ShowUnsignedSignatures = true; + +pdfViewer.DigitalSignatureSettings.SignaturePanelSettings + .EnableNavigation = true; + +pdfViewer.DigitalSignatureSettings.SignaturePanelSettings + .ShowCertificateDetailsAction = true; +{% endhighlight %} +{% endtabs %} + +### Signature Panel Contents + +Signed signatures include: + +* Signer name +* Signed date +* Validation status +* Certificate details action + +Unsigned signatures include: + +* Signature field name +* Navigation support + +## Digitally Sign a Document + +Digital signatures can be applied through the built-in signing dialog or programmatically. + +### Sign using built-in signing dialog + +You can digitally sign a PDF document using the built-in signing dialog available in the PDF Viewer. When a user taps an unsigned signature field, the signing dialog opens and allows the user to review the signing information before applying the digital signature. To enable the signing workflow, provide the necessary certificate details before the dialog is shown. + +**Configure Signing Information** + +Handle the `DigitalSignatureModalViewAppearing` event and provide the required certificate and signer information using the SigningOptions object. + +{% tabs %} +{% highlight c# %} +pdfViewer.DigitalSignatureModalViewAppearing += OnDigitalSignatureModalViewAppearing; + +private async void OnDigitalSignatureModalViewAppearing(object? sender,DigitalSignatureModalViewAppearingEventArgs e) +{ + Stream? certificateStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("DigitalSignature.Assets.certificate.pfx"); + e.Options.CertificateStream =certificateStream; + e.Options.CertificatePassword = "password"; + e.Options.SignerName = "John Doe"; + e.Options.Reason = "Approved"; + e.Options.LocationInfo = "New York"; + e.Options.ContactInfo = "john@example.com"; +} +{% endhighlight %} +{% endtabs %} + +N> To display the built-in digital signing dialog, both CertificateStream and CertificatePassword must be provided in the DigitalSignatureModalViewAppearing event. + +I> The built-in signing workflow requires a certificate stream in PKCS#12 format (.pfx or .p12) along with the corresponding certificate password. +I> Formats such as .cer, .crt, and .pem cannot be used for signing because they do not contain the private key required to create a digital signature. +I> Use .pfx or .p12 files that contain both the certificate and its associated private key. + +The following image represents how to sign digital signature using the built-in dialog on the desktop. +![Digital signature Demo](Images\DigitalSignatureDemo.gif) + + +### Sign programmatically + +To sign a document programmatically, create a SigningOptions instance and pass it to the SignAsync method. + +### Sign Using Certificate + +Provide a certificate through the CertificateStream property of the `SigningOptions` class to digitally sign the document. You can also specify additional signature information such as the signer name, reason, location, and contact information. + +{% tabs %} +{% highlight c# %} +SigningOptions options = new SigningOptions() +{ + SignatureField = signatureField, + SignerName = "John Doe", + Reason = "Document Approval", + LocationInfo = "New York", + ContactInfo = "john@example.com", + CertificateStream = certificateStream, + CertificatePassword = "password" +}; + +await pdfViewer.SignAsync(options); +{% endhighlight %} +{% endtabs %} + +## Signature Appearance + +Use the `SignatureAppearanceSettings` class to customize the visual appearance of a digital signature applied to a PDF document. + +{% tabs %} +{% highlight c# %} +options.Appearance = new SignatureAppearanceSettings() +{ + Mode = SignatureAppearanceMode.Text, + ShowSignerName = true, + ShowDate = true, + ShowReason = true, + ShowLocation = true, + ShowLabels = true +}; +{% endhighlight %} +{% endtabs %} + +## Signature Appearance Modes + +The Mode property determines how the digital signature is displayed in the signed document. + +### Text Appearance + +Displays signer information as text without any graphical signature content. + +{% tabs %} +{% highlight c# %} +appearance.Mode = SignatureAppearanceMode.Text; +{% endhighlight %} +{% endtabs %} + +### Draw Appearance + +Displays handwritten signature strokes captured from user input. + +{% tabs %} +{% highlight c# %} +appearance.Mode = SignatureAppearanceMode.Draw; +appearance.SignaturePoints = signaturePoints; +{% endhighlight %} +{% endtabs %} + +### Image Appearance + +Displays a signature image as the visual representation of the digital signature. + +{% tabs %} +{% highlight c# %} +appearance.Mode = SignatureAppearanceMode.Image; +appearance.ImageBytes = imageBytes; +{% endhighlight %} +{% endtabs %} + +### None + +Displays only digital signing information without any graphical signature content. + +{% tabs %} +{% highlight c# %} +appearance.Mode = SignatureAppearanceMode.None; +{% endhighlight %} +{% endtabs %} + + +## Certificate Inspection + +Users can inspect the signer certificate information through the built-in certificate details dialog. This dialog provides details about the certificate used to digitally sign the document, allowing users to verify the signer's identity and certificate validity. + +Certificate details include: + +* Subject Name +* Issuer Name +* Serial Number +* Thumbprint +* Signature Algorithm +* Digest Algorithm +* Valid From +* Valid To + +## Signature Validation Event + +The SignatureValidated event occurs after a digital signature has been validated. This event provides access to the validated signature field and its corresponding validation result, allowing you to inspect the validation status and perform custom logic based on the result. + +{% tabs %} +{% highlight c# %} +pdfViewer.SignatureValidated += PdfViewer_SignatureValidated; + +private void PdfViewer_SignatureValidated( + object? sender, + SignatureValidatedEventArgs e) +{ + var signature = e.SignatureField; + var result = e.Result; +} +{% endhighlight %} +{% endtabs %} + +## Document Signed Event + +The DocumentSigned event occurs after a document has been successfully signed. This event provides access to the signature field that was signed, allowing you to perform post-signing operations such as updating the UI, saving the document, or displaying a confirmation message. + +{% tabs %} +{% highlight c# %} +pdfViewer.DocumentSigned += PdfViewer_DocumentSigned; + +private void PdfViewer_DocumentSigned( + object? sender, + DocumentSignedEventArgs e) +{ + SignatureFormField signedField = + e.SignatureField; +} +{% endhighlight %} +{% endtabs %} + +## Signing Failed Event + +The SigningFailed event occurs when a digital signing operation fails. This event provides information about the failure, including the error type and error message, allowing you to handle signing errors and provide appropriate feedback to users. + +{% tabs %} +{% highlight c# %} +pdfViewer.SigningFailed += PdfViewer_SigningFailed; + +private void PdfViewer_SigningFailed( + object? sender, + SigningFailedEventArgs e) +{ + var errorType = e.ErrorType; + var message = e.ErrorMessage; +} +{% endhighlight %} +{% endtabs %} + +### Common Signing Errors + +The following table lists the common errors that can occur during a digital signing operation and their descriptions. + +| Error | Description | +|---------|-------------| +| InvalidTarget | The specified signature field is invalid or cannot be signed. | +| FieldAlreadySigned | The signature field already contains a digital signature. | +| InvalidCertificate | The certificate could not be loaded or is invalid. | +| MissingCertificateOrProvider | No certificate or custom signing provider was supplied for the signing operation. | +| ProviderSigningFailed | The custom signing provider failed to complete the signing operation. | +| InvalidAppearance | The specified signature appearance settings are invalid.| +| Cancelled | The signing operation was cancelled by the user.| + +## Digital Signature Dialog Events + +The .NET MAUI PDF Viewer provides events that allow you to customize the behavior of the digital signature dialog before it is displayed and before it is closed. + +### DigitalSignatureModalViewAppearing + +The `DigitalSignatureModalViewAppearing` event occurs before the digital signature dialog is displayed. Use this event to customize signing options or prevent the dialog from being shown. + +{% tabs %} +{% highlight c# %} +pdfViewer.DigitalSignatureModalViewAppearing += PdfViewer_DigitalSignatureModalViewAppearing; + +private void PdfViewer_DigitalSignatureModalViewAppearing( + object? sender, + DigitalSignatureModalViewAppearingEventArgs e) +{ + // Customize signing options. + Stream? certificateStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("DigitalSignature.Assets.certificate.pfx"); + e.Options.CertificateStream =certificateStream; + e.Options.CertificatePassword = "password"; + e.Options.SignerName = "David"; + e.Options.Reason = "Approved"; + e.Options.LocationInfo = "India"; + e.Options.ContactInfo = "david@example.com"; +} +{% endhighlight %} +{% endtabs %} + +### Cancel Dialog Display + +Set the `Cancel` property to true in the `DigitalSignatureModalViewAppearing` event to prevent the digital signature dialog from being displayed. + +{% tabs %} +{% highlight c# %} +private void PdfViewer_DigitalSignatureModalViewAppearing( + object? sender, + DigitalSignatureModalViewAppearingEventArgs e) +{ + e.Cancel = true; +} +{% endhighlight %} +{% endtabs %} + +### DigitalSignatureModalViewDisappearing + +The `DigitalSignatureModalViewDisappearing` event occurs before the digital signature dialog closes. Use this event to perform any required cleanup or post-processing tasks before the dialog is dismissed. + +{% tabs %} +{% highlight c# %} +pdfViewer.DigitalSignatureModalViewDisappearing += + PdfViewer_DigitalSignatureModalViewDisappearing; + +private void PdfViewer_DigitalSignatureModalViewDisappearing( + object? sender, + EventArgs e) +{ +} +{% endhighlight %} +{% endtabs %} + +## Custom Signing Provider + +Implement the `ISignatureProvider` interface to integrate custom signing solutions such as cloud-based signing services, Hardware Security Modules (HSMs), smart cards, or enterprise Public Key Infrastructure (PKI) systems. A custom signing provider enables signing operations to be performed using certificates and keys that are managed outside the local device. + +{% tabs %} +{% highlight c# %} +Stream? certificateStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("DigitalSignature.Assets.certificate.pfx"); + +pdfViewer.DigitalSignatureSettings.SigningProvider =new CustomSignatureProvider( + certificateStream, + "password123"); + +public class CustomSignatureProvider : ISignatureProvider +{ + private readonly X509Certificate2 signingCertificate; + + public CustomSignatureProvider(Stream? signingPfxStream,string signingPassword) + { + MemoryStream signingMs = new(); + signingPfxStream?.CopyTo(signingMs); + signingCertificate = X509CertificateLoader.LoadPkcs12(signingMs.ToArray(),signingPassword,X509KeyStorageFlags.Exportable); + } + + public IReadOnlyList Certificates => new[]{signingCertificate}; + + public Task SignHashAsync(byte[] data,CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (signingCertificate.GetRSAPrivateKey() is RSA rsa) + { + return Task.FromResult( + rsa.SignData( + data, + HashAlgorithmName.SHA256, + RSASignaturePadding.Pkcs1)); + } + + throw new InvalidOperationException("Certificate does not contain an RSA private key."); + } +} +{% endhighlight %} +{% endtabs %} + +## Multi-Signature Support + +The .NET MAUI PDF Viewer supports PDF documents that contain multiple digital signatures. Each signature is managed independently, allowing users to validate, inspect, and navigate between signatures without affecting existing signed content. + +The following multi-signature capabilities are supported: + +* Independent validation of each digital signature. +* Navigation between signature fields through the signature panel. +* Incremental document updates when additional signatures are applied. +* Preservation of existing signatures during subsequent signing operations. +* Synchronization of signature validation status across the document and signature panel. + +## See Also + +* [Form Filling](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/form-filling-overview) +* [Electronic Signature](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/signature) +* [Annotations Overview](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/annotations-overview) +* [Save a Document](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/save-a-document) \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Viewer/maui/Document-Modified.md b/Document-Processing/PDF/PDF-Viewer/maui/Document-Modified.md new file mode 100644 index 0000000000..6d4eabae34 --- /dev/null +++ b/Document-Processing/PDF/PDF-Viewer/maui/Document-Modified.md @@ -0,0 +1,78 @@ +--- +layout: post +title: Track Document Changes in .NET MAUI PDF Viewer | Syncfusion +description: Learn how to track document modifications and check whether a PDF contains unsaved changes in the Syncfusion® .NET MAUI PDF Viewer (SfPdfViewer). +platform: document-processing +control: SfPdfViewer +documentation: ug +keywords: .net maui pdf viewer, document modified, isdocumentmodified, track pdf changes, save modified pdf, maui pdf viewer +--- + +# Track Document Changes in .NET MAUI PDF Viewer + +The [SfPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html) provides the `IsDocumentModified` property to help determine whether the currently loaded PDF document contains unsaved changes. + +This property is useful when you want to save documents only when modifications have been made, enable or disable save commands dynamically, or notify users about unsaved changes before closing or navigating away from a document. + +The `IsDocumentModified` property is automatically updated whenever supported document modifications are performed in the PDF Viewer. + +## Document modified state + +The `IsDocumentModified` property becomes `true` when users perform supported document modifications, such as: + +* Adding, editing, or deleting annotations +* Changing form field values +* Applying redactions +* Adding signatures + +The property returns `false` when: + +* A document is initially loaded. +* All modifications are reverted to the original state through undo operations. + +The following example demonstrates how to determine whether the loaded document contains unsaved changes. + +{% tabs %} +{% highlight c# %} +bool isModified = PdfViewer.IsDocumentModified; +{% endhighlight %} +{% endtabs %} + +## Save only when the document is modified + +You can use the `IsDocumentModified` property to avoid unnecessary save operations and save the document only when it contains changes. + +{% tabs %} +{% highlight c# %} +if (PdfViewer.IsDocumentModified) +{ + PdfViewer.SaveDocument(SaveStream); +} +{% endhighlight %} +{% endtabs %} + +## Observe document modification state changes + +You can monitor changes to the `IsDocumentModified` property by subscribing to the `PropertyChanged` event of the `SfPdfViewer`. + +This is useful for updating the user interface, enabling or disabling save commands, or displaying indicators when the document modification state changes. + +{% tabs %} +{% highlight c# %} +PdfViewer.PropertyChanged += (sender, args) => +{ + if (args.PropertyName == nameof(PdfViewer.IsDocumentModified)) + { + bool isModified = PdfViewer.IsDocumentModified; + } +}; +{% endhighlight %} +{% endtabs %} + + +## See Also + +- [Open a Document](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/open-a-document) +- [Open a Password Protected Document](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/open-a-password-protected-document) +- [Getting Started](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/getting-started) +- [Save a Document](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/save-a-document) \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Viewer/maui/Images/DigitalSignatureDemo.gif b/Document-Processing/PDF/PDF-Viewer/maui/Images/DigitalSignatureDemo.gif new file mode 100644 index 0000000000..90f5748e4a Binary files /dev/null and b/Document-Processing/PDF/PDF-Viewer/maui/Images/DigitalSignatureDemo.gif differ diff --git a/Document-Processing/PDF/PDF-Viewer/maui/Images/PageThumbnailDemo.gif b/Document-Processing/PDF/PDF-Viewer/maui/Images/PageThumbnailDemo.gif new file mode 100644 index 0000000000..d3bb7cbc2f Binary files /dev/null and b/Document-Processing/PDF/PDF-Viewer/maui/Images/PageThumbnailDemo.gif differ diff --git a/Document-Processing/PDF/PDF-Viewer/maui/Open-a-Document.md b/Document-Processing/PDF/PDF-Viewer/maui/Open-a-Document.md index 35ee8e4b45..805cbbb8d0 100644 --- a/Document-Processing/PDF/PDF-Viewer/maui/Open-a-Document.md +++ b/Document-Processing/PDF/PDF-Viewer/maui/Open-a-Document.md @@ -71,20 +71,6 @@ PdfViewer.DocumentSource = await response.Content.ReadAsByteArrayAsync(); {% endhighlight %} {% endtabs %} -## Unload a document - -The [SfPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html) allows you to unload and clear the resources occupied by the PDF document loaded using the [UnloadDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html#Syncfusion_Maui_PdfViewer_SfPdfViewer_UnloadDocument) method, as shown below. - -N> 1. While changing or opening different documents on the same page, the previously loaded document will be unloaded automatically by the [SfPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html). -N> 2. And, if you are using multiple pages in your application, then make sure to unload the document from the [SfPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html) while leaving the page that has it to release the memory and resources consumed by the PDF document that is loaded. The unloading of documents can be done by calling the [UnloadDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html#Syncfusion_Maui_PdfViewer_SfPdfViewer_UnloadDocument) method. - -{% tabs %} -{% highlight c# %} -//Unload the document from the PDF viewer. -PdfViewer.UnloadDocument(); -{% endhighlight %} -{% endtabs %} - ## Opening a unsupported annotations The .NET MAUI PDF Viewer it is possible to view the unsupported annotations like 3D, rich media and sound annotations in a non-interactive manner. To achieve this, provide the [flattenOptions](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.FlattenOptions.html) (an optional parameter) as [Unsupported](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.FlattenOptions.html#Syncfusion_Maui_PdfViewer_FlattenOptions_Unsupported) in the [LoadDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html#Syncfusion_Maui_PdfViewer_SfPdfViewer_LoadDocument_System_IO_Stream_System_String_System_Nullable_Syncfusion_Maui_PdfViewer_FlattenOptions__) methods. See the following code example: @@ -103,21 +89,6 @@ The .NET MAUI PDF Viewer it is possible to view the unsupported annotations like N> * All the [LoadDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html#Syncfusion_Maui_PdfViewer_SfPdfViewer_LoadDocument_System_IO_Stream_System_String_System_Nullable_Syncfusion_Maui_PdfViewer_FlattenOptions__) methods accept the flatten options parameter. N> * Refer to this [section](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/migration#upcoming-features) for the upcoming annotation features in the [SfPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html). -## Optimizing document loading on Android - -When your application handles large images, complex graphics, or memory-intensive operations, the default heap size may not be sufficient, leading to performance issues or crashes. Enabling a larger heap allows the app to allocate more memory, ensuring smooth performance and preventing out-of-memory errors in such scenarios. You can enable this by adding the following highlighted attribute in your AndroidManifest.xml under the tag. - -{% tabs %} -{% highlight xml hl_lines="4" %} - - - - https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui. - -{% endhighlight %} -{% endtabs %} - ## Check other PDF opening options * [Open a document from local storage](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/open-a-document-from-local-storage) diff --git a/Document-Processing/PDF/PDF-Viewer/maui/Optimizing-Document-Loading.md b/Document-Processing/PDF/PDF-Viewer/maui/Optimizing-Document-Loading.md new file mode 100644 index 0000000000..4a736f1c53 --- /dev/null +++ b/Document-Processing/PDF/PDF-Viewer/maui/Optimizing-Document-Loading.md @@ -0,0 +1,30 @@ +--- +layout: post +title: Optimize PDF Loading on Android in .NET MAUI PDF Viewer | Syncfusion +description: Learn how to optimize document loading performance in the Syncfusion® .NET MAUI PDF Viewer (SfPdfViewer) by enabling a larger heap size on Android. +platform: document-processing +control: SfPdfViewer +documentation: ug +keywords: .net maui pdf viewer, android pdf viewer, maui pdf viewer performance, optimize pdf loading, large pdf documents, android large heap, sfpdfviewer memory optimization +--- + +# Optimizing document loading on Android in .NET MAUI PDF Viewer Control + +When your application handles large images, complex graphics, or memory-intensive operations, the default heap size may not be sufficient, leading to performance issues or crashes. Enabling a larger heap allows the app to allocate more memory, ensuring smooth performance and preventing out-of-memory errors in such scenarios. You can enable this by adding the following highlighted attribute in your AndroidManifest.xml under the tag. + +{% tabs %} +{% highlight xml hl_lines="4" %} + + + + https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui. + +{% endhighlight %} +{% endtabs %} + +## See Also + +- [Open from Local Storage](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/open-a-document-from-local-storage) +- [Open a Password-Protected Document](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/open-a-password-protected-document) +- [Document Load Notifications](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/documentloadnotifications) \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Viewer/maui/Page-Thumbnails.md b/Document-Processing/PDF/PDF-Viewer/maui/Page-Thumbnails.md new file mode 100644 index 0000000000..0e731232b8 --- /dev/null +++ b/Document-Processing/PDF/PDF-Viewer/maui/Page-Thumbnails.md @@ -0,0 +1,75 @@ +--- +layout: post +title: Page Thumbnail in .NET MAUI PDF Viewer | Syncfusion +description: Learn how to preview and navigate PDF pages using the page thumbnail view in the Syncfusion® .NET MAUI PDF Viewer. +platform: document-processing +control: SfPdfViewer +documentation: ug +keywords: .net maui pdf viewer, .net maui page thumbnail, pdf thumbnail preview, maui pdf navigation, pdf page preview +--- + +# Page Thumbnail in .NET MAUI PDF Viewer + +The page thumbnail view in the .NET MAUI PDF Viewer displays preview images of PDF pages, allowing users to quickly identify and navigate to a specific page. The thumbnail corresponding to the currently displayed page is automatically highlighted, making navigation easier in large documents. + +## Show or Hide the Thumbnail View + +The built-in thumbnail view can be displayed by setting the `IsThumbnailViewVisible` property to `true`. By default, the thumbnail view is hidden. + +> **Note:** The thumbnail view is available after a PDF document is loaded. + +{% tabs %} + +{% highlight XAML %} + + + +{% endhighlight %} + +{% highlight c# %} + +pdfViewer.IsThumbnailViewVisible = true; + +{% endhighlight %} + +{% endtabs %} + +To hide the thumbnail view programmatically: + +{% highlight c# %} + +pdfViewer.IsThumbnailViewVisible = false; + +{% endhighlight %} + +Users can also close the thumbnail pane using the built-in close button. + +## Navigate Using Thumbnails + +Selecting a thumbnail automatically navigates to the corresponding page in the PDF document. + +The thumbnail view provides the following behaviors: + +- Displays preview images for all pages in the document. +- Highlights the thumbnail of the currently visible page. +- Automatically updates the highlighted thumbnail during page navigation. +- Scrolls the thumbnail list to keep the selected page thumbnail in view. + +## Platform Behavior + +The page thumbnail view adapts its presentation based on the device form factor: + +- On desktop and tablet devices, a thumbnail pane is displayed alongside the PDF document. +- On mobile devices, thumbnails are shown in a touch-friendly layout optimized for smaller screens. + +## Demo + +![Thumbnail Page Navigation Demo](Images\PageThumbnailDemo.gif) + +## See Also + +- [Page Navigation](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/page-navigation) +- [Document Outline](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/document-outline) +- [Zooming](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/magnification) diff --git a/Document-Processing/PDF/PDF-Viewer/maui/Unload-Document.md b/Document-Processing/PDF/PDF-Viewer/maui/Unload-Document.md new file mode 100644 index 0000000000..2241cab502 --- /dev/null +++ b/Document-Processing/PDF/PDF-Viewer/maui/Unload-Document.md @@ -0,0 +1,37 @@ +--- +layout: post +title: Unload a PDF Document in .NET MAUI PDF Viewer | Syncfusion +description: Learn how to unload a PDF document and release associated resources in the Syncfusion® .NET MAUI PDF Viewer (SfPdfViewer) control. +platform: document-processing +control: SfPdfViewer +documentation: ug +keywords: .net maui pdf viewer, unload pdf document, pdf viewer memory management, sfpdfviewer unload document, release pdf resources, maui pdf viewer +--- + +# Unload a document in .NET MAUI PDF Viewer + +The `SfPdfViewer` allows you to unload the currently loaded PDF document and release the memory and resources associated with it by using the `UnloadDocument` method. + +When switching between documents on the same page, the previously loaded document is automatically unloaded by the PDF Viewer before loading the new document. + +> **Note** +> +> 1. When opening or loading a different document in the same `SfPdfViewer` instance, the previously loaded document is unloaded automatically. +> +> 2. If your application contains multiple pages with a PDF Viewer, it is recommended to call the `UnloadDocument` method before leaving the page. This helps release the memory and resources consumed by the loaded PDF document, improving overall application performance. + +The following code example shows how to unload a document from the PDF Viewer: + +{% tabs %} +{% highlight c# %} +// Unload the document from the PDF Viewer. +PdfViewer.UnloadDocument(); +{% endhighlight %} +{% endtabs %} + +## See Also +- [Open from URL](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/open-a-document-from-url) +- [Open from Base64](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/open-a-document-from-base64string) +- [Open from Local Storage](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/open-a-document-from-local-storage) +- [Open a Password-Protected Document](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/open-a-password-protected-document) +- [Document Load Notifications](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/documentloadnotifications) \ No newline at end of file diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/claude-service.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/claude-service.md new file mode 100644 index 0000000000..f5d921dbf5 --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/claude-service.md @@ -0,0 +1,175 @@ +--- +layout: post +title: Claude AI for AI-Powered Components | Syncfusion® +description: Learn how to implement a custom AI service using the Claude API with Syncfusion® AI-Powered Components. +platform: maui +control: SmartComponents +documentation: ug +--- + +# Claude AI Integration with .NET MAUI Smart Components + +The Syncfusion .NET MAUI AI-powered components can enhance applications with intelligent capabilities. You can integrate Anthropic `Claude AI` using the `IChatInferenceService` interface, which acts as a bridge between the editor and your custom AI service. + +## Setting Up Claude + +1. **Create an Anthropic Account** + Visit [Anthropic Console](https://console.anthropic.com), sign up, and complete the verification process. +2. **Obtain an API Key** + Navigate to [API Keys](https://console.anthropic.com/settings/keys) and click "Create Key." +3. **Review Model Specifications** + Refer to [Claude Models Documentation](https://docs.anthropic.com/claude/docs/models-overview) for details on available models. + +## Define Request and Response Models + +Create a file named `ClaudeModels.cs` in the Services folder and add: + +{% tabs %} +{% highlight c# tabtitle="ClaudeModels.cs" %} + +public class ClaudeChatRequest +{ + public string? Model { get; set; } + public int Max_tokens { get; set; } + public List? Messages { get; set; } + public List? Stop_sequences { get; set; } +} + +public class ClaudeMessage +{ + public string? Role { get; set; } + public string? Content { get; set; } +} + +public class ClaudeChatResponse +{ + public List? Content { get; set; } +} + +public class ClaudeContentBlock +{ + public string? Text { get; set; } + public string? Type { get; set; } +} + +{% endhighlight %} +{% endtabs %} + +## Create a Claude AI Service + +This service handles communication with the Claude API, including authentication and response parsing. + +1. Create a `Services` folder in your project. +2. Add a new file named `ClaudeAIService.cs` in the `Services` folder. +3. Implement the service as shown below: + +{% tabs %} +{% highlight c# tabtitle="ClaudeAIService.cs" %} + +using System.Net; +using System.Text; +using System.Text.Json; +using Microsoft.Extensions.AI; + +public class ClaudeAIService +{ + private readonly string _apiKey = ""; // API key + private readonly string _modelName = "claude-3-5-sonnet-20241022"; // Example model + private readonly string _endpoint = "https://api.anthropic.com/v1/messages"; + private static readonly HttpClient HttpClient = new(new SocketsHttpHandler + { + PooledConnectionLifetime = TimeSpan.FromMinutes(30), + EnableMultipleHttp2Connections = true + }) + { + DefaultRequestVersion = HttpVersion.Version20 // Fallback to HTTP/2 for compatibility + }; + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + public ClaudeAIService() + { + if (!HttpClient.DefaultRequestHeaders.Contains("x-api-key")) + { + HttpClient.DefaultRequestHeaders.Clear(); + HttpClient.DefaultRequestHeaders.Add("x-api-key", _apiKey); + HttpClient.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01"); // Check latest version in Claude API docs + } + } + + public async Task CompleteAsync(List chatMessages) + { + var requestBody = new ClaudeChatRequest + { + Model = _modelName, + Max_tokens = 2000, // Maximum tokens in response + Messages = chatMessages.Select(m => new ClaudeMessage + { + Role = m.Role == ChatRole.User ? "user" : "assistant", + Content = m.Text + }).ToList() + }; + + var content = new StringContent(JsonSerializer.Serialize(requestBody, JsonOptions), Encoding.UTF8, "application/json"); + + var response = await HttpClient.PostAsync(_endpoint, content); + response.EnsureSuccessStatusCode(); + var responseString = await response.Content.ReadAsStringAsync(); + var responseObject = JsonSerializer.Deserialize(responseString, JsonOptions); + return responseObject?.Content?.FirstOrDefault(x=>x.Type=="text")?.Text ?? "No response from Claude model."; + } +} + +{% endhighlight %} +{% endtabs %} + +## Implement IChatInferenceService + +Create `ClaudeInferenceService.cs`: + +{% tabs %} +{% highlight c# tabtitle="ClaudeInferenceService.cs" %} + +using Syncfusion.Maui.SmartComponents; + +public class ClaudeInferenceService : IChatInferenceService +{ + private readonly ClaudeAIService _claudeService; + + public ClaudeInferenceService(ClaudeAIService claudeService) + { + _claudeService = claudeService; + } + + public async Task GenerateResponseAsync(List chatMessages) + { + return await _claudeService.CompleteAsync(chatMessages); + } +} + +{% endhighlight %} +{% endtabs %} + +## Register Services in MAUI + +Update `MauiProgram.cs`: + +{% tabs %} +{% highlight c# tabtitle="MauiProgram.cs" hl_lines="9 10" %} + +using Syncfusion.Maui.Core.Hosting; +using Syncfusion.Maui.SmartComponents; + +var builder = MauiApp.CreateBuilder(); +builder + .UseMauiApp() + .ConfigureSyncfusionCore(); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + + +{% endhighlight %} +{% endtabs %} diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/configure-ai-service.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/configure-ai-service.md new file mode 100644 index 0000000000..e57dc1b56a --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/configure-ai-service.md @@ -0,0 +1,159 @@ +--- +layout: post +title: Configure Chat Client with AI-Powered Components | Syncfusion® +description: Learn how to implement a configure chat client with Syncfusion® AI-Powered Components. +platform: maui +control: SmartComponents +documentation: ug +--- + +# Configure Chat Client With Smart Components + +The Smart Components uses a chat inference service resolved from dependency injection to generate contextual suggestions. Register a compatible chat client and an inference adapter in `MauiProgram.cs`. + +## Azure OpenAI + +For **Azure OpenAI**, first [deploy an Azure OpenAI Service resource and model](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/create-resource), then values for `azureOpenAIKey`, `azureOpenAIEndpoint` and `azureOpenAIModel` will all be provided to you. + +* Install the following NuGet packages to your project: + +{% tabs %} + +{% highlight c# tabtitle="Package Manager" %} + +Install-Package Microsoft.Extensions.AI +Install-Package Microsoft.Extensions.AI.OpenAI +Install-Package Azure.AI.OpenAI + +{% endhighlight %} + +{% endtabs %} + +* To configure the AI service, add the following settings to the **MauiProgram.cs** file in your application. + +{% tabs %} +{% highlight C# tabtitle="MauiProgram" hl_lines="5 21" %} + +using Azure.AI.OpenAI; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging; +using System.ClientModel; +using Syncfusion.Maui.SmartComponents.Hosting; + +var builder = MauiApp.CreateBuilder(); + +.... + +string azureOpenAIKey = "AZURE_OPENAI_KEY"; +string azureOpenAIEndpoint = "AZURE_OPENAI_ENDPOINT"; +string azureOpenAIModel = "AZURE_OPENAI_MODEL"; +AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient( + new Uri(azureOpenAIEndpoint), + new ApiKeyCredential(azureOpenAIKey) +); +IChatClient azureOpenAIChatClient = azureOpenAIClient.GetChatClient(azureOpenAIModel).AsIChatClient(); +builder.Services.AddChatClient(azureOpenAIChatClient); + +builder.ConfigureSyncfusionAIServices(); + +{% endhighlight %} +{% endtabs %} + +## OpenAI + +For **OpenAI**, create an API key and place it at `openAIApiKey`. The value for `openAIModel` is the model you wish. + +* Install the following NuGet packages to your project: + +{% tabs %} + +{% highlight c# tabtitle="Package Manager" %} + +Install-Package Microsoft.Extensions.AI +Install-Package Microsoft.Extensions.AI.OpenAI + +{% endhighlight %} + +{% endtabs %} + +* To configure the AI service, add the following settings to the **MauiProgram.cs** file in your app. + +{% tabs %} +{% highlight C# tabtitle="MauiProgram" hl_lines="3 23" %} + +using Microsoft.Extensions.AI; +using OpenAI; +using Syncfusion.Maui.SmartComponents.Hosting; + +var builder = MauiApp.CreateBuilder(); + +.... + +string openAIApikey = "API-KEY"; +string openAIModel = "gpt-5-mini"; // example + +var openAIClient = new OpenAIClient( + new ApiKeyCredential(openAIApikey), + new OpenAIClientOptions + { + // Default OpenAI endpoint; include /v1 if your SDK expects it + Endpoint = new Uri("https://api.openai.com/v1/") + }); + +IChatClient openAIChatClient = openAIClient.GetChatClient(openAIModel).AsIChatClient(); +builder.Services.AddChatClient(openAIClient); + +builder.ConfigureSyncfusionAIServices(); + +{% endhighlight %} +{% endtabs %} + +## Ollama + +To use Ollama for running self hosted models: + +1. **Download and install Ollama** + Visit [Ollama's official website](https://ollama.com) and install the application appropriate for your operating system. + +2. **Install the desired model from the Ollama library** + You can browse and install models from the [Ollama Library](https://ollama.com/library) (e.g., `llama2:13b`, `mistral:7b`, etc.). + +3. **Configure your application** + + - Provide the `Endpoint` URL where the model is hosted (e.g., `http://localhost:11434`). + - Set `ModelName` to the specific model you installed (e.g., `llama2:13b`). + +* Install the following NuGet packages to your project: + +{% tabs %} + +{% highlight c# tabtitle="Package Manager" %} + +Install-Package Microsoft.Extensions.AI +Install-Package OllamaSharp + +{% endhighlight %} + +{% endtabs %} + +* Add the following settings to the **MauiProgram.cs** file in your application. + +{% tabs %} +{% highlight C# tabtitle="MauiProgram" hl_lines="3 13" %} + +using Microsoft.Extensions.AI; +using OllamaSharp; +using Syncfusion.Maui.SmartComponents.Hosting; + +var builder = MauiApp.CreateBuilder(); + +.... + +string ModelName = "MODEL_NAME"; +IChatClient chatClient = new OllamaApiClient("http://localhost:11434", ModelName); +builder.Services.AddChatClient(chatClient); + +builder.ConfigureSyncfusionAIServices(); + +{% endhighlight %} +{% endtabs %} diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/custom-ai-service.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/custom-ai-service.md new file mode 100644 index 0000000000..adc73a4f68 --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/custom-ai-service.md @@ -0,0 +1,96 @@ +--- +layout: post +title: Custom AI for AI-Powered Components | Syncfusion® +description: Learn how to use IChatInferenceService to integrate custom AI services with Syncfusion® .NET MAUI AI-Powered Components. +platform: maui +control: SmartComponents +documentation: ug +--- + +# Custom AI Service Integration with .NET MAUI Smart Components + +The Syncfusion .NET MAUI Smart Components can leverage AI to provide intelligent assistance during user interaction. By default, it works with providers like `OpenAI` or `Azure OpenAI` or `Ollama`, but you can also integrate your own AI service using the `IChatInferenceService` interface. This interface ensures smooth communication between the smart components and your custom AI logic. + +## IChatInferenceService Interface + +The `IChatInferenceService` interface defines how the Smart Components interacts with an AI service. It sends user input and context messages and expects an AI-generated response. + +{% tabs %} +{% highlight xaml tabtitle="C#" %} + +using Syncfusion.Maui.SmartComponents; + +Public interface IChatInferenceService +{ + Task GenerateResponseAsync(List chatMessages); +} + +{% endhighlight %} +{% endtabs %} + +- **Purpose**: Provides a standard way to connect any AI service. +- **Parameter**: The `chatMessages` contains the user’s text and previous context. +- **Benefit**: Lets you switch AI providers without changing the editor code. + +## Custom AI Service Implementation + +Here’s a simple example of a mock AI service that implements `IChatInferenceService`. You can replace the logic with your own AI integration: + +{% tabs %} +{% highlight xaml tabtitle="C#" %} + +using Microsoft.Extensions.AI; +using Syncfusion.Maui.SmartComponents; + +public class MockAIService : IChatInferenceService +{ + public Task GenerateResponseAsync(List chatMessages); + { + // Add the request logic for the Custom AI service. + } +} + +{% endhighlight %} +{% endtabs %} + +## Registering the Custom AI Service + +Register the custom AI service in **MauiProgram.cs**: + +{% tabs %} +{% highlight xaml tabtitle="C#" %} + +using Syncfusion.Maui.Core.Hosting; +using Syncfusion.Maui.SmartComponents; + +var builder = MauiApp.CreateBuilder() +.... + +builder.Services.AddSingleton(); + +{% endhighlight %} +{% endtabs %} + +## How to test Custom AI Integration + +1. Implement and register your custom AI service. +2. Add SfSmartTextEditor to your page. +3. Run the app and start typing. +4. Check if suggestions appear based on your AI logic. +5. Use SuggestionDisplayMode to choose Inline or Popup display. + +## Implemented AI Services + +Here are examples of AI services integrated using the `IChatInferenceService` interface. These are only examples; you can use `IChatInferenceService` to create your own service. + +| Service | Documentation | +|---------|---------------| +| Claude | [Claude Integration](https://help.syncfusion.com/maui/common/claude-service) | +| DeepSeek | [DeepSeek Integration](https://help.syncfusion.com/maui/common/deepseek-service) | +| Groq | [Groq Integration](https://help.syncfusion.com/maui/common/groq-service) | +| Gemini | [Gemini Integration](https://help.syncfusion.com/maui/common/gemini-service) | + +## Troubleshooting + +If the custom AI service does not work as expected, try the following: +- **No Suggestions Displayed**: Ensure the `IChatInferenceService` implementation is registered in **MauiProgram.cs** and returns valid responses. Check for errors in the `GenerateResponseAsync` method. \ No newline at end of file diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/deepseek-service.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/deepseek-service.md new file mode 100644 index 0000000000..99c0d205c7 --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/deepseek-service.md @@ -0,0 +1,170 @@ +--- +layout: post +title: DeepSeek AI for AI-Powered Components | Syncfusion® +description: Learn how to integrate the DeepSeek AI services with Syncfusion® AI-Powered Components. +platform: maui +control: SmartComponents +documentation: ug +--- + +# DeepSeek AI Integration with .NET MAUI Smart Components + +The Syncfusion .NET MAUI AI-powered components can enhance applications with intelligent capabilities. You can integrate DeepSeek using the `IChatInferenceService` interface, which standardizes communication between the editor and your custom AI service. + +## Setting Up DeepSeek + +1. **Obtain a DeepSeek API Key** + Create an account at [DeepSeek Platform](https://platform.deepseek.com), sign in, and navigate to [API Keys](https://platform.deepseek.com/api_keys) to generate an API key. +2. **Review Model Specifications** + Refer to [DeepSeek Models Documentation](https://api-docs.deepseek.com/quick_start/pricing/) for details on available models (e.g., `deepseek-chat`). + +## Define Request and Response Models + +Create a file named `DeepSeekModels.cs` in the Services folder and add: + +{% tabs %} +{% highlight c# tabtitle="DeepSeekModels.cs" %} + +public class DeepSeekMessage +{ + public string? Role { get; set; } + public string? Content { get; set; } +} + +public class DeepSeekChatRequest +{ + public string? Model { get; set; } + public float Temperature { get; set; } + public List? Messages { get; set; } +} + +public class DeepSeekChatResponse +{ + public List? Choices { get; set; } +} + +public class DeepSeekChoice +{ + public DeepSeekMessage? Message { get; set; } +} + +{% endhighlight %} +{% endtabs %} + +## Create a DeepSeek AI Service + +This service manages requests to the `DeepSeek` Chat Completions endpoint and returns the generated text. + +1. Create a `Services` folder in your project. +2. Add a new file named `DeepSeekAIService.cs` in the `Services` folder. +3. Implement the service as shown below: + +{% tabs %} +{% highlight c# tabtitle="DeepSeekAIService.cs" %} + +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Configuration; +using System.Net; +using System.Text; +using System.Text.Json; + +public class DeepSeekAIService +{ + private readonly string _apiKey = ""; // API key + private readonly string _modelName = "deepseek-chat"; // Example model + private readonly string _endpoint = "https://api.deepseek.com/v1/chat/completions"; + private static readonly HttpClient HttpClient = new(new SocketsHttpHandler + { + PooledConnectionLifetime = TimeSpan.FromMinutes(30), + EnableMultipleHttp2Connections = true + }) + { + DefaultRequestVersion = HttpVersion.Version20 // Fallback to HTTP/2 for compatibility + }; + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + public DeepSeekAIService() + { + if (!HttpClient.DefaultRequestHeaders.Contains("Authorization")) + { + HttpClient.DefaultRequestHeaders.Clear(); + HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}"); + } + } + + public async Task CompleteAsync(List chatMessages) + { + var requestBody = new DeepSeekChatRequest + { + Model = _modelName, + Messages = chatMessages.Select(m => new DeepSeekMessage + { + Role = m.Role == ChatRole.User ? "user" : "system", // Align with DeepSeek API roles + Content = m.Text + }).ToList() + }; + + var content = new StringContent(JsonSerializer.Serialize(requestBody, JsonOptions), Encoding.UTF8, "application/json"); + + var response = await HttpClient.PostAsync(_endpoint, content); + response.EnsureSuccessStatusCode(); + var responseString = await response.Content.ReadAsStringAsync(); + var responseObject = JsonSerializer.Deserialize(responseString, JsonOptions); + return responseObject?.Choices?.FirstOrDefault()?.Message?.Content ?? "No response from DeepSeek."; + } +} + +{% endhighlight %} +{% endtabs %} + +## Implement IChatInferenceService + +Create `DeepSeekInferenceService.cs`: + +{% tabs %} +{% highlight c# tabtitle="DeepSeekInferenceService.cs" %} + +using Syncfusion.Maui.SmartComponents; + +public class DeepSeekInferenceService : IChatInferenceService +{ + private readonly DeepSeekAIService _deepSeekService; + + public DeepSeekInferenceService(DeepSeekAIService deepSeekService) + { + _deepSeekService = deepSeekService; + } + + public async Task GenerateResponseAsync(List chatMessages) + { + return await _deepSeekService.CompleteAsync(chatMessages); + } +} + +{% endhighlight %} +{% endtabs %} + +## Register Services in MAUI + +Update `MauiProgram.cs`: + +{% tabs %} +{% highlight c# tabtitle="MauiProgram.cs" hl_lines="9 10" %} + +using Syncfusion.Maui.Core.Hosting; +using Syncfusion.Maui.SmartComponents; + +var builder = MauiApp.CreateBuilder(); +builder + .UseMauiApp() + .ConfigureSyncfusionCore(); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + + +{% endhighlight %} +{% endtabs %} diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/document-summarizer.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/document-summarizer.md new file mode 100644 index 0000000000..0a5a1aee61 --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/document-summarizer.md @@ -0,0 +1,445 @@ +--- +layout: post +title: Document Summaries and Q&A in .NET MAUI Smart PDF Viewer | Syncfusion +description: Explore how to generate concise document summaries and ask AI-assisted questions using SfSmartPdfViewer in your .NET MAUI applications. +platform: document-processing +control: SfSmartPdfViewer +documentation: ug +keywords: .net maui smart pdf viewer, ai summarization, document summarizer maui, ai assist view maui, question answering pdf maui +--- + +# Document Summaries and Q&A in .NET MAUI Smart PDF Viewer + +The [`AssistViewSettings`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html) of [`SfSmartPdfViewer`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html) enables AI-assisted interaction with PDF documents, including summarization and question answering. + +The AI Assist View feature of the Smart PDF Viewer is a panel that displays AI-generated content such as summaries and Q&A responses. It provides users with the ability to generate a summary of the PDF document and ask questions about its content. Users can activate the AI assistant by selecting the **AI Assist** button in the viewer toolbar (or from the **AI Tools** menu). The assistant responds to user queries and offers AI-generated suggestions to guide exploration of the document. + +![Document Summarization in .NET MAUI PDFViewer](images/document-summarizer.gif) + +N> The AI service must be configured before using the AI Assist feature. Refer to [Getting Started](./getting-started) to learn how to register a chat client in `MauiProgram.cs`. + +## Component usage + +Initialize the Smart PDF Viewer with the `AssistViewSettings` to enable the document summarization and Q&A features. The `IsAssistViewVisible` property shows or hides the Assist View panel. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +using Syncfusion.Maui.SmartPdfViewer; +. . . + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + IsAssistViewVisible = true, + AssistViewSettings = new AssistViewSettings() +}; +pdfViewer.SetBinding(SfSmartPdfViewer.DocumentSourceProperty, "PdfDocumentStream"); +this.Content = pdfViewer; + +{% endhighlight %} +{% endtabs %} + +## SfSmartPdfViewer properties + +### IsAssistViewVisible + +The [`IsAssistViewVisible`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html#Syncfusion_Maui_SmartPdfViewer_SfSmartPdfViewer_IsAssistViewVisible) property (type: `bool`, default: `false`) gets or sets a value indicating whether the AI Assist View panel is visible in the Smart PDF Viewer. When set to `true`, the Assist View panel is displayed, allowing users to interact with AI-powered document assistance features such as document summaries, question answering, and contextual document analysis. When set to `false`, the Assist View panel is hidden from the user interface. The Assist View feature remains enabled and can be shown again by setting this property to `true`. This property controls only the visibility of the Assist View panel and does not disable the underlying Assist View functionality or settings. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +// Toggle the Assist View panel visibility at runtime. +pdfViewer.IsAssistViewVisible = !pdfViewer.IsAssistViewVisible; + +{% endhighlight %} +{% endtabs %} + +## AssistViewSettings properties + +### IsEnabled + +The [`IsEnabled`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html#Syncfusion_Maui_SmartPdfViewer_AssistViewSettings_IsEnabled) property (type: `bool`) controls whether the Assist View and its features are available in the PDF viewer. When set to `false`, the Assist View UI and related AI interactions are disabled. The default value is `true`. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + AssistViewSettings = new AssistViewSettings + { + IsEnabled = false + } +}; + +{% endhighlight %} +{% endtabs %} + +### ShowPromptSuggestions + +[`ShowPromptSuggestions`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html#Syncfusion_Maui_SmartPdfViewer_AssistViewSettings_ShowPromptSuggestions) (type: `bool`) determines whether the Assist view displays a list of suggested prompts that users can tap to initiate AI queries. The default value is `true`. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% endtabs %} + +### Prompt + +The [`Prompt`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html#Syncfusion_Maui_SmartPdfViewer_AssistViewSettings_Prompt) property (type: `string`) defines a query that guides the AI assistant within the Assist view panel. It can be updated at runtime, for example, from a button click event. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +private void ChangePrompt(object sender, EventArgs e) +{ + pdfViewer.AssistViewSettings.Prompt = "Explain this document."; +} + +{% endhighlight %} +{% endtabs %} + +### PromptChanged + +[`PromptChanged`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html#Syncfusion_Maui_SmartPdfViewer_AssistViewSettings_PromptChanged) (type: `EventHandler`) is raised whenever the user modifies the prompt text. The event receives the updated prompt as a `string` argument, so the application can log the new prompt or trigger additional actions in response. + +{% tabs %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +pdfViewer.AssistViewSettings.PromptChanged += OnPromptChanged; + +private void OnPromptChanged(object? sender, string newPrompt) +{ + Console.WriteLine($"Prompt changed: {newPrompt}"); +} + +{% endhighlight %} +{% endtabs %} + +### Placeholder + +The [`Placeholder`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html#Syncfusion_Maui_SmartPdfViewer_AssistViewSettings_Placeholder) property (type: `string`) sets the placeholder text shown in the Assist view input field when it is empty. The default value is `Type your prompt for assistance...`. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% endtabs %} + +### MinimumDocumentLength + +[`MinimumDocumentLength`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html#Syncfusion_Maui_SmartPdfViewer_AssistViewSettings_MinimumDocumentLength) (type: `int`) specifies the minimum number of characters the user must enter in the prompt input before AI processing is enabled. If the input is shorter than this threshold, an error message is shown and AI features are disabled. The default value is `100`. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% endtabs %} + +### StreamResponse + +[`StreamResponse`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html#Syncfusion_Maui_SmartPdfViewer_AssistViewSettings_StreamResponse) (type: `bool`) streams AI responses to the user in real time. When enabled, users see the output as it is generated instead of waiting for the full response. The default value is `true`. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% endtabs %} + +### MaxRetryAttempts + +[`MaxRetryAttempts`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html#Syncfusion_Maui_SmartPdfViewer_AssistViewSettings_MaxRetryAttempts) (type: `int`) sets the maximum number of retry attempts for AI processing. If the assistant encounters an error, it retries the operation up to the specified number of times before showing an error message. The default value is `3`. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% endtabs %} + +### Timeout + +The [`Timeout`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html#Syncfusion_Maui_SmartPdfViewer_AssistViewSettings_Timeout) property (type: `int`) defines the maximum duration, in seconds, that the AI assistant will wait for a response before timing out. If the response is not received within this period, the operation is aborted and an error is shown. The default value is `30`. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% endtabs %} + +## InitialPromptSettings + +The `InitialPromptSettings` class configures the initial behavior of the Assist view in the `SfSmartPdfViewer`. It guides the AI assistant by providing a predefined prompt, suggested queries, and a page range for summarization. + +### Prompt + +`Prompt` (type: `string`) sets the initial query shown in the input field when the Assist view opens. This directs the AI assistant to perform a specific task immediately. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + + + + + +{% endhighlight %} +{% endtabs %} + +N> In XAML, nested property-element syntax (for example, `syncfusion:AssistViewSettings.InitialPromptSettings`) is required to nest a settings class inside another settings class. + +### SuggestedPrompts + +`SuggestedPrompts` (type: `string[]`) provides a list of predefined prompts that guide the user and help the AI understand the document context. The default prompts include "Can you provide a summary of this document?", "What are the topics discussed in this document?", and "Could you list the key points from this document?". + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +pdfViewer.AssistViewSettings.InitialPromptSettings.SuggestedPrompts = new string[] +{ + "What is the main purpose of this document?", + "Generate a quick overview for a meeting briefing.", + "Is there any legal or compliance information here?" +}; + +{% endhighlight %} +{% endtabs %} + +N> Since `SuggestedPrompts` is an array, it is easier to set it from code-behind, as shown in the C# tab, rather than in XAML. + +### PageStart + +[`PageStart`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.InitialPromptSettings.html#Syncfusion_Maui_SmartPdfViewer_InitialPromptSettings_PageStart) (type: `int`) defines the starting page number (1-based) for the document overview. Use it together with `PageEnd` to focus AI analysis on a specific page range. The default starts at page `1`. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + + + + + +{% endhighlight %} +{% endtabs %} + +### PageEnd + +[`PageEnd`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.InitialPromptSettings.html#Syncfusion_Maui_SmartPdfViewer_InitialPromptSettings_PageEnd) (type: `int`) defines the ending page number for the document overview. Use it together with `PageStart` to limit the scope of AI processing and manage performance. The default value is `10`. + +{% tabs %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +pdfViewer.AssistViewSettings.InitialPromptSettings.PageEnd = 5; + +{% endhighlight %} +{% endtabs %} + +## Retrieving the Assist View prompts + +The `GetPrompts` method of the [SfSmartPdfViewer](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html) class returns the list of prompts available in the Assist View, as `IReadOnlyList` objects. If the Assist View is not yet populated, an empty list is returned. + +{% tabs %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +private void OnGetPromptsClicked(object sender, EventArgs e) +{ + IReadOnlyList prompts = pdfViewer.GetPrompts(); +} + +{% endhighlight %} +{% endtabs %} + +## Customizing Assist View with PdfViewerAssistViewTemplates + +The [`PdfViewerAssistViewTemplates`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.PdfViewerAssistViewTemplates.html) class customizes the Assist view UI. It provides the [`BannerTemplate`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.PdfViewerAssistViewTemplates.html#Syncfusion_Maui_SmartPdfViewer_PdfViewerAssistViewTemplates_BannerTemplate) property, a `DataTemplate` that replaces the default banner displayed at the top of the AI Assist View panel. This can be used for branding, instructions, or welcome messages to enhance user engagement. When no template is provided, the built-in banner is displayed. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + + + + + + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +DataTemplate bannerTemplate = new DataTemplate(() => +{ + Label label = new Label + { + Text = "Welcome to Syncfusion's AI-powered PDF Summarizer!", + FontSize = 14, + TextColor = Color.FromArgb("#5D3FD3") + }; + Grid grid = new Grid { Padding = 10, BackgroundColor = Color.FromArgb("#F7F2FB") }; + grid.Add(label); + return grid; +}); + +pdfViewer.AssistViewSettings.PdfViewerAssistViewTemplates.BannerTemplate = bannerTemplate; + +{% endhighlight %} +{% endtabs %} + +## Integration notes + +To apply these settings, assign them through the `AssistViewSettings` property of `SfSmartPdfViewer`. The following example combines the `AssistViewSettings`, `InitialPromptSettings`, and `PdfViewerAssistViewTemplates` in a single page. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + + + + + + + + + + + + + + + +{% endhighlight %} +{% endtabs %} + +## Error handling + +If the AI request fails (for example, due to authentication failure, rate limiting, model unavailability, or a network error), the Smart PDF Viewer shows an **AI Failure Warning** dialog with the reason, and offers options to retry or cancel. Retries are governed by the `MaxRetryAttempts` and `Timeout` properties of the `AssistViewSettings` class. + +## See also + +* [.NET MAUI Smart PDF Viewer Overview](./overview) +* [Getting Started with .NET MAUI Smart PDF Viewer](./getting-started) +* [Smart Redaction in .NET MAUI Smart PDF Viewer](./smart-redaction) +* [Smart Fill in .NET MAUI Smart PDF Viewer](./smart-fill) +* [Localization in .NET MAUI Smart PDF Viewer](./localization) \ No newline at end of file diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/gemini-service.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/gemini-service.md new file mode 100644 index 0000000000..e6dd3c82a0 --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/gemini-service.md @@ -0,0 +1,187 @@ +--- +layout: post +title: Gemini AI for AI-Powered Components | Syncfusion® +description: Learn how to implement a custom AI service using Google's Gemini API with Syncfusion® AI-Powered Components. +platform: maui +control: SmartComponents +documentation: ug +--- + +# Gemini AI Integration with .NET MAUI Smart Components + +The Syncfusion .NET MAUI AI-powered components can enhance applications with intelligent capabilities. By default, it works with providers like OpenAI or Azure OpenAI, but you can integrate `Google Gemini AI` using the `IChatInferenceService` interface. This guide explains how to implement and register Gemini AI for the Smart Text Editor in a .NET MAUI app. + +## Setting Up Gemini + +1. **Get a Gemini API Key** + Visit [Google AI Studio](https://ai.google.dev/gemini-api/docs/api-key), sign in, and generate an API key. +2. **Review Model Details** + Refer to [Gemini Models Documentation](https://ai.google.dev/gemini-api/docs/models) for details on available models. + +## Define Request and Response Models + +Create a file named `GeminiModels.cs` in the Services folder and add: + +{% tabs %} +{% highlight c# tabtitle="GeminiModels.cs" %} + + +public class Part { public string Text { get; set; } } +public class Content { public Part[] Parts { get; init; } = Array.Empty(); } +public class Candidate { public Content Content { get; init; } = new(); } +public class GeminiResponseObject { public Candidate[] Candidates { get; init; } = Array.Empty(); } + +public class ResponseContent +{ + public List Parts { get; init; } + public string Role { get; init; } + public ResponseContent(string text, string role) + { + Parts = new List { new Part { Text = text } }; + Role = role; + } +} + +public class GenerationConfig +{ + public int MaxOutputTokens { get; init; } = 2048; + public List StopSequences { get; init; } = new(); +} + +public class SafetySetting +{ + public string Category { get; init; } = string.Empty; + public string Threshold { get; init; } = string.Empty; +} + +public class GeminiChatParameters +{ + public List Contents { get; init; } = new(); + public GenerationConfig GenerationConfig { get; init; } = new(); + public List SafetySettings { get; init; } = new(); +} + +{% endhighlight %} +{% endtabs %} + +## Create a Gemini AI Service + +Create a service class to handle `Gemini API` calls, including authentication, request/response handling, and safety settings. + +1. Create a `Services` folder in your MAUI project. +2. Add a new file named `GeminiService.cs` in the Services folder. +3. Implement the service as shown below: + +{% tabs %} +{% highlight c# tabtitle="GeminiService.cs" %} + +using System.Net; +using System.Text; +using System.Text.Json; +using Microsoft.Extensions.AI; + +public class GeminiService +{ + private readonly string _apiKey = ""; + private readonly string _modelName = "gemini-2.0-flash"; // Example model + private readonly string _endpoint = "https://generativelanguage.googleapis.com/v1beta/models/"; + private static readonly HttpClient HttpClient = new(new SocketsHttpHandler + { + PooledConnectionLifetime = TimeSpan.FromMinutes(30), + EnableMultipleHttp2Connections = true + }) + { + DefaultRequestVersion = HttpVersion.Version20 + }; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + public GeminiService() + { + HttpClient.DefaultRequestHeaders.Clear(); + HttpClient.DefaultRequestHeaders.Add("x-goog-api-key", _apiKey); + } + + public async Task CompleteAsync(List chatMessages) + { + var requestUri = $"{_endpoint}{_modelName}:generateContent"; + var parameters = BuildGeminiChatParameters(chatMessages); + var payload = new StringContent(JsonSerializer.Serialize(parameters, JsonOptions), Encoding.UTF8, "application/json"); + + using var response = await HttpClient.PostAsync(requestUri, payload); + response.EnsureSuccessStatusCode(); + var json = await response.Content.ReadAsStringAsync(); + var result = JsonSerializer.Deserialize(json, JsonOptions); + return result?.Candidates?.FirstOrDefault()?.Content?.Parts?.FirstOrDefault()?.Text ?? "No response from model."; + } + + private GeminiChatParameters BuildGeminiChatParameters(List messages) + { + var contents = messages.Select(m => new ResponseContent(m.Text, m.Role == ChatRole.User ? "user" : "model")).ToList(); + return new GeminiChatParameters + { + Contents = contents, + GenerationConfig = new GenerationConfig + { + MaxOutputTokens = 2000, + StopSequences = new List { "END_INSERTION", "NEED_INFO", "END_RESPONSE" } + } + }; + } +} + +{% endhighlight %} +{% endtabs %} + +## Implement IChatInferenceService + +Create `GeminiInferenceService.cs`: + +{% tabs %} +{% highlight c# tabtitle="GeminiInferenceService.cs" %} + + +using Syncfusion.Maui.SmartComponents; + +public class GeminiInferenceService : IChatInferenceService +{ + private readonly GeminiService _geminiService; + + public GeminiInferenceService(GeminiService geminiService) + { + _geminiService = geminiService; + } + + public async Task GenerateResponseAsync(List chatMessages) + { + return await _geminiService.CompleteAsync(chatMessages); + } +} + +{% endhighlight %} +{% endtabs %} + +## Register Services in MAUI + +Update `MauiProgram.cs`: + +{% tabs %} +{% highlight c# tabtitle="MauiProgram.cs" hl_lines="9 10" %} + +using Syncfusion.Maui.Core.Hosting; +using Syncfusion.Maui.SmartComponents; + +var builder = MauiApp.CreateBuilder(); +builder + .UseMauiApp() + .ConfigureSyncfusionCore(); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + + +{% endhighlight %} +{% endtabs %} diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/getting-started.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/getting-started.md new file mode 100644 index 0000000000..259c77833a --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/getting-started.md @@ -0,0 +1,598 @@ +--- +layout: post +title: Getting Started with .NET MAUI Smart PDF Viewer | Syncfusion +description: Get started with Syncfusion .NET MAUI Smart PDF Viewer by installing packages, configuring AI services, and loading a PDF document. +platform: document-processing +control: SfSmartPdfViewer +documentation: ug +keywords: .net maui smart pdf viewer, maui smart pdf viewer getting started, ai pdf viewer maui, smart redaction maui, smart fill maui +--- + +# Getting Started with .NET MAUI Smart PDF Viewer + +This section guides you through setting up and configuring the Smart PDF Viewer in your .NET MAUI application. Follow the steps below to add the Smart PDF Viewer to your project, configure the AI service, and load a PDF document. + +{% tabcontents %} +{% tabcontent Visual Studio %} + +## Prerequisites + +Before proceeding, ensure the following are in place: + +1. Install [.NET 9 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/9.0) or later. +2. Set up a .NET MAUI environment with Visual Studio 2022 (v17.3 or later). + +## Step 1: Create a New MAUI Project + +1. Go to **File > New > Project** and choose the **.NET MAUI App** template. +2. Name the project and choose a location, then click **Next**. +3. Select the .NET Framework version and click **Create**. + +## Step 2: Install the Syncfusion® MAUI Smart PDF Viewer NuGet Package + +1. In **Solution Explorer**, right-click the project and choose **Manage NuGet Packages**. +2. Search for `Syncfusion.Maui.SmartPdfViewer` and install the latest version. +3. Ensure the dependencies ([Syncfusion.Maui.PdfViewer](https://www.nuget.org/packages/Syncfusion.Maui.PdfViewer), [Syncfusion.Maui.SmartComponents](https://www.nuget.org/packages/Syncfusion.Maui.SmartComponents), [Syncfusion.Maui.Core](https://www.nuget.org/packages/Syncfusion.Maui.Core)) are installed and the project is restored. + +Alternatively, you can utilize the following package manager command to achieve the same. + +{% tabs %} +{% highlight c# tabtitle="Package Manager" %} + +Install-Package Syncfusion.Maui.SmartPdfViewer -Version {{ site.releaseversion }} + +{% endhighlight %} +{% endtabs %} + +## Step 3: Register the Syncfusion® Core Handler + +[Syncfusion.Maui.Core](https://www.nuget.org/packages/Syncfusion.Maui.Core/) is automatically installed as a dependency when the `Syncfusion.Maui.SmartPdfViewer` NuGet is installed. + +1. Add the following namespace in your `MauiProgram.cs` file. + {% tabs %} + {% highlight c# tabtitle="MauiProgram.cs" %} + using Syncfusion.Maui.Core.Hosting; + {% endhighlight %} + {% endtabs %} + +2. Register the Syncfusion core handler in your `MauiProgram.cs` file to use Syncfusion controls. + {% tabs %} + {% highlight c# tabtitle="MauiProgram.cs" hl_lines="11" %} + + public static MauiApp CreateMauiApp() + { + var builder = MauiApp.CreateBuilder(); + builder + .UseMauiApp() + .ConfigureFonts(fonts => + { + fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); + }); + + builder.ConfigureSyncfusionCore(); + return builder.Build(); + } + + {% endhighlight %} + {% endtabs %} + +## Step 4: Configure the AI Service + +The AI-powered features of the Smart PDF Viewer (document summarization, smart redaction, and smart fill) require a chat client registered in the dependency injection container. This step is not required for basic PDF rendering. + +N> You can refer to [Configure Chat Client](https://help.syncfusion.com/maui/common/configure-ai-service) for services like `Azure`, `OpenAI`, and `Ollama`. You can also refer to the [Custom AI Service](https://help.syncfusion.com/maui/common/custom-ai-service) section to configure your own services, such as `Claude`, `Gemini`, `DeepSeek`, `Groq`, etc. If you are using a custom AI service, there is no need to register `ConfigureSyncfusionAIServices()` in `MauiProgram`. + +* Install the following NuGet packages to your project: + +{% tabs %} +{% highlight c# tabtitle="Package Manager" %} + +Install-Package Microsoft.Extensions.AI +Install-Package Microsoft.Extensions.AI.OpenAI +Install-Package Azure.AI.OpenAI + +{% endhighlight %} +{% endtabs %} + +* To configure the Azure OpenAI service, add the following settings to the `MauiProgram.cs` file. + +{% tabs %} +{% highlight c# tabtitle="MauiProgram.cs" hl_lines="2 15 21" %} + +using Azure.AI.OpenAI; +using Microsoft.Extensions.AI; +using Syncfusion.Maui.Core.Hosting; +using Syncfusion.Maui.SmartComponents.Hosting; +using System.ClientModel; + +public static class MauiProgram +{ + public static MauiApp CreateMauiApp() + { + var builder = MauiApp.CreateBuilder(); + builder + .UseMauiApp() + .ConfigureFonts(fonts => + { + fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); + }); + + builder.ConfigureSyncfusionCore(); + + // Azure OpenAI configuration values + string azureOpenAIKey = "AZURE_OPENAI_KEY"; + string azureOpenAIEndpoint = "AZURE_OPENAI_ENDPOINT"; + string azureOpenAIModel = "AZURE_OPENAI_MODEL"; + AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient( + new Uri(azureOpenAIEndpoint), + new ApiKeyCredential(azureOpenAIKey)); + IChatClient azureOpenAIChatClient = azureOpenAIClient.GetChatClient(azureOpenAIModel).AsIChatClient(); + + // Register the chat client used by the Smart PDF Viewer. + builder.Services.AddChatClient(azureOpenAIChatClient); + builder.ConfigureSyncfusionAIServices(); + + return builder.Build(); + } +} + +{% endhighlight %} +{% endtabs %} + +Here, + +* **azureOpenAIKey**: Azure OpenAI API key. +* **azureOpenAIEndpoint**: Azure OpenAI deployment endpoint URL. +* **azureOpenAIModel**: Azure OpenAI deployment name. + +For **Azure OpenAI**, first [deploy an Azure OpenAI Service resource and model](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/create-resource), then the values for `azureOpenAIKey`, `azureOpenAIEndpoint`, and `azureOpenAIModel` will all be provided to you. + +N> The chat client registered using `AddChatClient` is resolved by the Smart PDF Viewer through dependency injection. The same chat client can be shared across other AI-powered Smart Components in your application. + +## Step 5: Add the Smart PDF Viewer + +Open the `MainPage.xaml` file and follow the steps below. + +1. Add the following namespace in your `MainPage.xaml` file. + {% tabs %} + {% highlight xaml tabtitle="MainPage.xaml" %} + + xmlns:syncfusion="clr-namespace:Syncfusion.Maui.SmartPdfViewer;assembly=Syncfusion.Maui.SmartPdfViewer" + {% endhighlight %} + {% endtabs %} + +2. Add the [SfSmartPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html) control. + {% tabs %} + {% highlight xaml tabtitle="MainPage.xaml" %} + + + {% endhighlight %} + {% endtabs %} + +## Step 6: Load a PDF Document + +1. From the solution explorer of the project, add a new folder to the project named `Assets` and add the PDF document you need to load into the PDF viewer. Here, a PDF document named `PDF_Succinctly.pdf` is used. +2. In Visual Studio, right-click the added PDF document and set its `Build Action` as `Embedded Resource`. +3. In this example, the PDF document is loaded using MVVM binding. Create a new C# file named `PdfViewerViewModel.cs` and add the following code snippet. + + {% tabs %} + {% highlight c# tabtitle="PdfViewerViewModel.cs" %} + + using System.ComponentModel; + using System.Reflection; + + public class PdfViewerViewModel : INotifyPropertyChanged + { + private Stream pdfDocumentStream; + + /// + /// Occurs when a property value changes. + /// + public event PropertyChangedEventHandler? PropertyChanged; + + /// + /// Gets or sets the stream of the currently loaded PDF document. + /// + public Stream PdfDocumentStream + { + get + { + return pdfDocumentStream; + } + set + { + pdfDocumentStream = value; + OnPropertyChanged(nameof(PdfDocumentStream)); + } + } + + /// + /// Initializes a new instance of the class. + /// + public PdfViewerViewModel() + { + // Load the embedded PDF document stream. + // Replace 'SmartPdfViewerExample' with your project's default namespace in the resource path. Verify that the namespace matches your project name. + pdfDocumentStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SmartPdfViewerExample.Assets.PDF_Succinctly.pdf"); + } + + /// + /// Raises the event for the specified property name. + /// + /// The name of the property that changed. + public void OnPropertyChanged(string name) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); + } + } + + {% endhighlight %} + {% endtabs %} + +4. Open the `MainPage.xaml` file again and add the namespace `SmartPdfViewerExample` and name it as `local`. + {% tabs %} + {% highlight xaml tabtitle="MainPage.xaml" %} + + xmlns:local="clr-namespace:SmartPdfViewerExample" + {% endhighlight %} + {% endtabs %} + +5. Set an instance of the `PdfViewerViewModel` class as the `BindingContext`. Bind the Smart PDF viewer's [DocumentSource](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html#Syncfusion_Maui_PdfViewer_SfPdfViewer_DocumentSource) to the `PdfDocumentStream` property of the `PdfViewerViewModel` class. + {% tabs %} + {% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + + {% endhighlight %} + {% endtabs %} + +N> * While changing or opening different documents on the same page, the previously loaded document will be unloaded automatically by the [SfSmartPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html). +N> * If you are using multiple pages in your application, then make sure to unload the document from the [SfSmartPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html) while leaving the page that has it to release the memory and resources consumed by the PDF document that is loaded. The unloading of documents can be done by calling the [UnloadDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html#Syncfusion_Maui_PdfViewer_SfPdfViewer_UnloadDocument) method. +N> * The [SfSmartPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html) also implements `IDisposable`. Call the `Dispose` method when the viewer is no longer needed (for example, when leaving the page) to dispose the Smart PDF Viewer and its associated resources and dependencies, including the AI panels and settings event handlers. Calling `Dispose` more than once has no effect. + + {% tabs %} + {% highlight c# tabtitle="MainPage.xaml.cs" %} + + protected override void OnDisappearing() + { + pdfViewer.Dispose(); + base.OnDisappearing(); + } + + {% endhighlight %} + {% endtabs %} + +## Step 7: Enable the AI-Powered Features + +The Smart PDF Viewer exposes three settings classes to enable and configure the AI features. Add them in your `MainPage.xaml` file as needed. + +### Document summarization + +Use the [AssistViewSettings](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.SmartPdfViewer.AssistViewSettings.html) class to configure the AI Assist panel used for document summarization and Q&A. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +using Syncfusion.Maui.SmartPdfViewer; + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + IsAIAssistViewVisible = true, + AssistViewSettings = new AssistViewSettings + { + Prompt = "Summarize this document.", + Placeholder = "Enter your query...", + ShowPromptSuggestions = true + } +}; + +{% endhighlight %} +{% endtabs %} + +Here, + +* **IsAIAssistViewVisible**: Shows or hides the AI Assist View panel. +* **Prompt**: The prompt used to guide AI-generated responses. +* **Placeholder**: The placeholder text displayed in the Assist View input area. +* **ShowPromptSuggestions**: Shows or hides prompt suggestions in the Assist View panel. + +### Smart redaction + +Use the [SmartRedactSettings](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.SmartPdfViewer.SmartRedactSettings.html) class to enable AI-assisted redaction of sensitive information. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + Person Names + Organization Names + Email Addresses + Phone Numbers + Credit Card Numbers + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +using Syncfusion.Maui.SmartPdfViewer; + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + IsSmartRedactViewVisible = true, + SmartRedactSettings = new SmartRedactSettings + { + IsEnabled = true, + RedactPatterns = new string[] + { + "Person Names", + "Organization Names", + "Email Addresses", + "Phone Numbers", + "Credit Card Numbers" + } + } +}; + +{% endhighlight %} +{% endtabs %} + +Here, + +* **IsSmartRedactViewVisible**: Shows or hides the Smart Redaction panel. +* **IsEnabled**: Enables or disables the Smart Redaction feature. +* **RedactPatterns**: The collection of patterns used to identify sensitive information, such as names, phone numbers, email addresses, identification numbers, and financial information. Custom patterns can be added to detect organization-specific confidential content. + +### Smart fill + +Use the [SmartFillSettings](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.SmartPdfViewer.SmartFillSettings.html) class to enable AI-assisted form filling. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +using Syncfusion.Maui.SmartPdfViewer; + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + SmartFillSettings = new SmartFillSettings + { + IsEnabled = true + } +}; + +{% endhighlight %} +{% endtabs %} + +Here, + +* **IsEnabled**: Enables or disables the Smart Fill feature, which intelligently populates form fields based on context. + +## Step 8: Register the Syncfusion license + +Register your Syncfusion license key in the `MauiProgram.cs` file before using the Smart PDF Viewer. For more details, see [Licensing](https://help.syncfusion.com/maui/licensing/overview). + +{% tabs %} +{% highlight c# tabtitle="MauiProgram.cs" %} + +public static MauiApp CreateMauiApp() +{ + ... + builder.ConfigureSyncfusionCore(); + Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + return builder.Build(); +} + +{% endhighlight %} +{% endtabs %} + +## Step 9: Running the Application + +1. Select the target framework, device, or emulator. +2. Press `F5` to run the application. +3. The PDF document will be loaded in the Smart PDF Viewer, and the AI-powered features can be accessed from the built-in toolbar and the AI Assist, Smart Redaction, and Smart Fill panels. + +N> To run the AI features on **Android**, an additional semantic-search model setup (`model.ONNX` and `vocab.txt`) may be required. Refer to the platform-specific notes in the [Smart Components documentation](https://help.syncfusion.com/maui/common/configure-ai-service) for details on copying the local embeddings model to the app data directory at startup. + +{% endtabcontent %} +{% tabcontent JetBrains Rider %} + +## Prerequisites + +Before proceeding, ensure the following are set up: + +1. Ensure you have the latest version of JetBrains Rider. +2. Install [.NET 9 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/9.0) or later. +3. Make sure the MAUI workloads are installed and configured as described [here](https://www.jetbrains.com/help/rider/MAUI.html#before-you-start). + +## Step 1: Create a new .NET MAUI Project + +1. Go to **File > New Solution,** Select .NET (C#) and choose the **.NET MAUI App** template. +2. Enter the Project Name, Solution Name, and Location. +3. Select the .NET framework version and click Create. + +## Step 2: Install the Syncfusion® MAUI Smart PDF Viewer NuGet Package + +1. In **Solution Explorer,** right-click the project and choose **Manage NuGet Packages**. +2. Search for `Syncfusion.Maui.SmartPdfViewer` and install the latest version. +3. Ensure the necessary dependencies are installed correctly, and the project is restored. If not, open the Terminal in Rider and manually run: `dotnet restore` + +Alternatively, you can utilize the following dotnet CLI command to achieve the same. + +{% tabs %} +{% highlight c# tabtitle=".NET CLI" %} + +dotnet add package Syncfusion.Maui.SmartPdfViewer + +{% endhighlight %} +{% endtabs %} + +## Step 3: Register the handler + +The [Syncfusion.Maui.Core](https://www.nuget.org/packages/Syncfusion.Maui.Core/) NuGet is a dependent package for all Syncfusion® controls of .NET MAUI. In the **MauiProgram.cs** file, register the handler for Syncfusion® core. + +{% tabs %} +{% highlight C# tabtitle="MauiProgram.cs" hl_lines="1 10" %} + +using Syncfusion.Maui.Core.Hosting; +namespace GettingStarted +{ + public static class MauiProgram + { + public static MauiApp CreateMauiApp() + { + var builder = MauiApp.CreateBuilder(); + + builder.ConfigureSyncfusionCore(); + builder + .UseMauiApp() + .ConfigureFonts(fonts => + { + fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); + }); + + return builder.Build(); + } + } +} + +{% endhighlight %} +{% endtabs %} + +## Step 4: Configure the AI Service + +To configure the AI services, you must register a chat client and call the `ConfigureSyncfusionAIServices()` method in the `MauiProgram.cs` file. + +{% tabs %} +{% highlight c# tabtitle="MauiProgram.cs" hl_lines="6 26 27" %} + +using Azure.AI.OpenAI; +using Microsoft.Extensions.AI; +using Syncfusion.Maui.Core.Hosting; +using Syncfusion.Maui.SmartComponents.Hosting; +using System.ClientModel; + +namespace GettingStarted +{ + public class MauiProgram + { + public static MauiApp CreateMauiApp() + { + var builder = MauiApp.CreateBuilder(); + builder + .UseMauiApp() + .ConfigureFonts(fonts => + { + fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); + }); + + string azureOpenAIKey = "AZURE_OPENAI_KEY"; + string azureOpenAIEndpoint = "AZURE_OPENAI_ENDPOINT"; + string azureOpenAIModel = "AZURE_OPENAI_MODEL"; + + // Configure Azure AI service for the Smart PDF Viewer. + AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient(new Uri(azureOpenAIEndpoint), new ApiKeyCredential(azureOpenAIKey)); + IChatClient azureOpenAIChatClient = azureOpenAIClient.GetChatClient(azureOpenAIModel).AsIChatClient(); + + builder.Services.AddChatClient(azureOpenAIChatClient); + builder.ConfigureSyncfusionAIServices(); + + return builder.Build(); + } + } +} +{% endhighlight %} +{% endtabs %} + +N> +- You can refer to [Configure Chat Client](https://help.syncfusion.com/maui/common/configure-ai-service) for services like `Azure`, `OpenAI`, and `Ollama`. +- You can also refer to the [Custom AI Service](https://help.syncfusion.com/maui/common/custom-ai-service) section to configure your own services, such as `Claude`, `Gemini`, `DeepSeek`, `Groq`, etc. +- If you are using a custom AI service, there is no need to register `ConfigureSyncfusionAIServices()` in `MauiProgram`. + +## Step 5: Add the Smart PDF Viewer control + +1. To initialize the control, import the `Syncfusion.Maui.SmartPdfViewer` namespace into your code. +2. Initialize [SfSmartPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html). + +{% tabs %} +{% highlight xaml tabtitle="XAML" hl_lines="3 5" %} + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="C#" hl_lines="1 9 10" %} + +using Syncfusion.Maui.SmartPdfViewer; +. . . + +public partial class MainPage : ContentPage +{ + public MainPage() + { + InitializeComponent(); + SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer(); + this.Content = pdfViewer; + } +} + +{% endhighlight %} +{% endtabs %} + +3. Bind the [DocumentSource](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html#Syncfusion_Maui_PdfViewer_SfPdfViewer_DocumentSource) property to load a PDF document from a stream, and enable the AI features as shown in the Visual Studio tab above ([Step 6](#step-6-load-a-pdf-document) and [Step 7](#step-7-enable-the-ai-powered-features)). + +## Step 6: Running the Application + +1. Select the target framework, device, or emulator. +2. Run the application. The PDF document will be loaded in the Smart PDF Viewer, and the AI-powered features can be accessed from the built-in toolbar and the AI Assist, Smart Redaction, and Smart Fill panels. + +{% endtabcontent %} +{% endtabcontents %} + +## See also + +* [.NET MAUI Smart PDF Viewer Overview](./overview) +* [Document Summaries in .NET MAUI Smart PDF Viewer](./document-summarizer) +* [Smart Redaction in .NET MAUI Smart PDF Viewer](./smart-redaction) +* [Smart Fill in .NET MAUI Smart PDF Viewer](./smart-fill) +* [Localization in .NET MAUI Smart PDF Viewer](./localization) +* [.NET MAUI PDF Viewer Overview](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/overview) +* [Configure Chat Client with AI-Powered Components](https://help.syncfusion.com/maui/common/configure-ai-service) +* [Custom AI Service](https://help.syncfusion.com/maui/common/custom-ai-service) diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/images/document-summarizer.gif b/Document-Processing/PDF/Smart-PDF-Viewer/maui/images/document-summarizer.gif new file mode 100644 index 0000000000..5a3f92cf91 Binary files /dev/null and b/Document-Processing/PDF/Smart-PDF-Viewer/maui/images/document-summarizer.gif differ diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/images/smart-fill.gif b/Document-Processing/PDF/Smart-PDF-Viewer/maui/images/smart-fill.gif new file mode 100644 index 0000000000..b810fa058f Binary files /dev/null and b/Document-Processing/PDF/Smart-PDF-Viewer/maui/images/smart-fill.gif differ diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/images/smart-redaction.gif b/Document-Processing/PDF/Smart-PDF-Viewer/maui/images/smart-redaction.gif new file mode 100644 index 0000000000..f6559390e4 Binary files /dev/null and b/Document-Processing/PDF/Smart-PDF-Viewer/maui/images/smart-redaction.gif differ diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/localization.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/localization.md new file mode 100644 index 0000000000..4ccc7012b5 --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/localization.md @@ -0,0 +1,283 @@ +--- +layout: post +title: Localization in .NET MAUI Smart PDF Viewer | Syncfusion +description: Learn how to localize the static text in the Syncfusion® .NET MAUI Smart PDF Viewer (SfSmartPdfViewer) control to other languages. +platform: document-processing +control: SfSmartPdfViewer +documentation: ug +keywords: .net maui smart pdf viewer, localization maui, localize smart pdf viewer, maui resx localization +--- + +# Localization in .NET MAUI Smart PDF Viewer + +Localization is the process of translating the application resources into a different language for specific cultures. [SfSmartPdfViewer](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html) is set up by default with the language code `en-US`. However, by including a resource file (.resx) in the application with the language code, the static text used in the [SfSmartPdfViewer](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html) can be localized to a different language. + +The Smart PDF Viewer uses the `SfSmartPdfViewerResources` accessor, which falls back to the built-in English strings whenever a localized value is not found. + +## Change the current user interface culture + +Set the [CurrentUICulture](https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.currentuiculture?view=net-9.0) property in the `App.xaml.cs` file to the desired user interface culture. Refer to the following code sample to change the current culture to `French`. + +{% tabs %} +{% highlight C# tabtitle="App.xaml.cs" hl_lines="10" %} + +using System.Globalization; + +namespace SmartPdfViewerLocalization; + +public partial class App : Application +{ + public App() + { + InitializeComponent(); + CultureInfo.CurrentUICulture = new CultureInfo("fr-FR"); + MainPage = new AppShell(); + } +} + +{% endhighlight %} +{% endtabs %} + +## Create and add the resource file to the application + +Follow the given steps to create and add the resource file to the application. + +1. Right-click on the `Resources` folder in the application. + +2. Click the `Add` option and then select `New Item`. + +3. In the `Add New Item` wizard, select the `Resource File` option and name the file in the format `..resx`. For example, name the file as `SfSmartPdfViewer.fr.resx` for the `French` culture. + +4. Click the `Add` option to add the resource file to the Resources folder. + +5. Change the `Build Action` of the resource file to `Embedded Resource`. + +6. Double-click the resource file to add the name and value details in the Resource Designer. Use the names listed in the [default names and values](#default-names-and-values) section below. + +7. Set the `ResourceManager` as shown in the following code example, which looks up the resource file with the specified root name. + +{% tabs %} +{% highlight C# tabtitle="App.xaml.cs" hl_lines="13 14" %} + +using System.Resources; +using System.Globalization; +using Syncfusion.Maui.SmartPdfViewer; + +namespace SmartPdfViewerLocalization; + +public partial class App : Application +{ + public App() + { + InitializeComponent(); + CultureInfo.CurrentUICulture = new CultureInfo("fr-FR"); + SfSmartPdfViewerResources.ResourceManager = new ResourceManager("SmartPdfViewerLocalization.Resources.SfSmartPdfViewer", + Application.Current.GetType().Assembly); + MainPage = new AppShell(); + } +} + +{% endhighlight %} +{% endtabs %} + +N> When localizing multiple Syncfusion MAUI controls in a .NET MAUI application, it's important to understand that these controls support only a single [ResourceManager](https://learn.microsoft.com/en-us/dotnet/api/system.resources.resourcemanager?view=net-9.0) instance for localization. If you assign different [ResourceManager](https://learn.microsoft.com/en-us/dotnet/api/system.resources.resourcemanager?view=net-9.0) instances for separate resource (.resx) files, the last-assigned ResourceManager will override the others. This can result in incomplete or incorrect localization across your controls. To ensure consistent and accurate localization, consolidate all localization keys (name-value pairs) into a single resource (.resx) file and assign the [ResourceManager](https://learn.microsoft.com/en-us/dotnet/api/system.resources.resourcemanager?view=net-9.0) using that unified resource file, as shown below: +N> +N>```csharp +N> using Syncfusion.Maui.Core.Localization; +N> +N> // Assign the ResourceManager using the unified .resx file +N> LocalizationResourceAccessor.ResourceManager = new ResourceManager("Localization.Resources.SyncfusionControls", Application.Current.GetType().Assembly); +N> // Replace the above string with your resource file's actual namespace and name. +N> ``` + +N> The Smart PDF Viewer inherits the core PDF Viewer features from [SfPdfViewer](https://help.syncfusion.com/cr/document-processing/Syncfusion.Maui.PdfViewer.SfPdfViewer.html). To localize the core PDF Viewer text (toolbars, annotations, forms, and so on), include the `SfPdfViewer` resource keys in the same resource file, as described in the [PDF Viewer localization](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/localization) documentation. The Smart PDF Viewer also reuses some core viewer keys — for example, `Ok` and `Cancel` displayed in the redaction confirmation and AI failure warning dialogs are resolved through the `SfPdfViewer` resources. + +## Default names and values + +The following table contains the default name and value details used in the `SfSmartPdfViewer` in the `en-US` culture. + +N> The default values listed below are the hard-coded fallback strings in the `SfSmartPdfViewerResources` accessor. When a localized value is found in the assigned resource file, it overrides the default value. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameValue
    AIAssistAI Assist
    AssistViewHeaderTextCan I help you?
    AIAssistanceDescriptionHow can I help you with this document?
    AIAssistanceTitleAI Assistance
    AIServiceNotAvailableContentNo AI service has been configured for Smart PDF Viewer.
    AIServiceNotAvailableTitleAI Service Not Available
    AIToolsAI Tools
    AIModelNotReadyContentThe AI model is still preparing the document. Please try again in a few moments.
    AIModelNotReadyTitleAI Not Ready
    AuthenticationFailedContentThe credentials were not provided, incorrect, or invalid. Please verify your AI configuration.
    AuthenticationFailedTitleAuthentication Failed
    ConnectionErrorContentThe connection to the AI service has been lost. Please check your network connection and try again.
    ConnectionErrorTitleConnection Error
    DisclaimerContentAI-generated content may contain inaccuracies.
    NoInformationErrorContentNo sensitive information was found in the document.
    NoInformationErrorContentHeaderNo Data Found
    NoPatternSelectedContentPlease select at least one pattern.
    NoPatternSelectedTitlePattern Required
    ModelNotAvailableContentThe configured AI model is unavailable or does not exist.
    ModelNotAvailableTitleModel Not Available
    RateLimitExceededContentThe AI service rate limit has been exceeded. Please try again later.
    RateLimitExceededTitleRate Limit Exceeded
    RedactRedact
    RedactDisclaimerAI-detected information may not be accurate. Please verify results before use.
    RedactOptionsHeaderSelect the pattern
    ScanScan
    RedactViewHeaderSelect the patterns
    SmartFillSmart Fill
    SmartRedactionSmart Redaction
    TimeOutErrorContentYour search request took longer than expected and exceeded the maximum allowed time.
    TimeOutErrorTitleRequest Timeout
    UnsupportedFileErrorContentThis file doesn't support generative AI features because it's blank or doesn't contain enough text. Please try a different file.
    UnSupportedFileErrorTitleUnsupported File
    + +## Localizing the redaction patterns + +The default redaction pattern names (Person Names, Organization Names, Email Addresses, Phone Numbers, Addresses, Dates, Account Numbers, and Credit Card Numbers) shown in the Smart Redaction panel are provided through the [`RedactPatterns`](./smart-redaction#redactpatterns) property. To present these patterns in a different language, assign the localized pattern names to the `SmartRedactSettings.RedactPatterns` property. + +{% tabs %} +{% highlight C# tabtitle="MainPage.xaml.cs" %} + +using System.Globalization; +using Syncfusion.Maui.SmartPdfViewer; +. . . + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + SmartRedactSettings = new SmartRedactSettings + { + RedactPatterns = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "fr" + ? new string[] { "Noms de personnes", "Noms d'organisations", "Adresses e-mail", "Numéros de téléphone", "Adresses", "Dates", "Numéros de compte", "Numéros de carte de crédit" } + : new string[] + { + "Person Names", + "Organization Names", + "Email Addresses", + "Phone Numbers", + "Addresses", + "Dates", + "Account Numbers", + "Credit Card Numbers" + } + } +}; + +{% endhighlight %} +{% endtabs %} + +N> Custom redaction patterns supplied via `RedactPatterns` are sent to the AI service as-is for detection. Verify that the configured AI model understands the localized pattern names. + +## See also + +* [.NET MAUI Smart PDF Viewer Overview](./overview) +* [Getting Started with .NET MAUI Smart PDF Viewer](./getting-started) +* [Document Summaries in .NET MAUI Smart PDF Viewer](./document-summarizer) +* [Smart Redaction in .NET MAUI Smart PDF Viewer](./smart-redaction) +* [Smart Fill in .NET MAUI Smart PDF Viewer](./smart-fill) +* [Localization in .NET MAUI PDF Viewer](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/localization) \ No newline at end of file diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/overview.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/overview.md new file mode 100644 index 0000000000..efaf4f1e48 --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/overview.md @@ -0,0 +1,84 @@ +--- +layout: post +title: About Syncfusion .NET MAUI Smart PDF Viewer Component | Syncfusion +description: Learn about the AI-powered Syncfusion .NET MAUI Smart PDF Viewer, including document summarization with Q&A, smart redaction, and smart fill. +platform: document-processing +control: SfSmartPdfViewer +documentation: ug +keywords: .net maui smart pdf viewer, maui smart pdf viewer, ai pdf viewer maui, smart redaction maui, smart fill maui, document summarizer maui +--- + +# About Syncfusion .NET MAUI Smart PDF Viewer Component + +The **[.NET MAUI Smart PDF Viewer](https://www.syncfusion.com/maui-controls/maui-pdf-viewer)** is an AI-powered component in Syncfusion's .NET MAUI suite. Built on top of the [SfPdfViewer](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/overview) control, it enhances document interaction with built-in AI capabilities while retaining all the core PDF viewing features — magnification, page navigation, annotations, form filling, text search, and more — on Android, iOS, macOS, and Windows from a single code base. To get started, see [Getting Started](./getting-started). + +Key capabilities include [**Document Summarization with Q&A**](#document-summarization), [**Smart Redaction**](#smart-redaction), and [**Smart Fill**](#smart-fill). These features enable efficient and secure document workflows. + +## Document Summarization + +* Analyzes PDF content and produces concise summaries using AI. +* Supports natural-language Q&A with user-entered and AI-suggested questions. +* Accelerates understanding without reading the entire document. +* Applicable to legal contracts, research papers, business reports, and other lengthy documents. + +## Smart Redaction + +* Detects and removes sensitive or confidential information. +* Identifies patterns such as personal identifiers and financial data. +* Ensures consistent redaction across documents. +* Supports privacy and compliance requirements while reducing manual effort. + +## Smart Fill + +* Intelligently populates form fields based on context. +* Understands the structure and expected input of PDF forms. +* Reduces manual data entry and improves accuracy. + +## Core PDF Viewing Features + +Because the Smart PDF Viewer inherits from the .NET MAUI [SfPdfViewer](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/overview), it also includes the complete set of core viewing features: + +* **Open documents** from streams, local storage, URLs, Base64 strings, or password-protected files. +* **Annotations**: Add, edit, import, and export highlights, shapes, ink, stamps, sticky notes, free text, and more. +* **Form filling**: Fill, edit, import, and export PDF form fields including text boxes, checkboxes, and signatures. +* **Text search and selection**: Search for text and navigate all occurrences in a document. +* **Save documents**: Save modified documents to a file stream, with optional annotation flattening. +* **Built-in toolbars and page navigation**: Include bookmarks, thumbnails, and customizable toolbar items. +* **Redaction and electronic signatures**: Permanently remove sensitive content, and add handwritten, typed, or image-based signatures. + +For more details on these core features, refer to the [.NET MAUI PDF Viewer documentation](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/overview). + +## Benefits + +* **Efficiency**: Automates time-consuming tasks. +* **Accuracy**: Minimizes human error. +* **Scalability**: Suitable for enterprise-level document management. +* **Cross-platform**: Works on Android, iOS, macOS, and Windows from a single code base. +* **Security**: Enhances privacy protection. + +## In this section + +| Topic | Description | +|---|---| +| [Getting Started](./getting-started) | Install the package, register the handler, configure the AI service, and load your first PDF document. | +| [Document Summarizer](./document-summarizer) | Generate document summaries and ask AI-assisted questions with the Assist View. | +| [Smart Redaction](./smart-redaction) | Detect and redact sensitive information using AI-assisted pattern detection. | +| [Smart Fill](./smart-fill) | Automatically populate PDF form fields from clipboard or specified data. | +| [Localization](./localization) | Localize the static text of the Smart PDF Viewer to other languages. | + +## Integration + +* Powered by AI services such as [Syncfusion.Maui.SmartComponents](https://www.nuget.org/packages/Syncfusion.Maui.SmartComponents), Microsoft.Extensions.AI, [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/create-resource?pivots=web-portal), OpenAI, and Ollama. +* Features are optional and can be enabled independently as needed. +* Chat clients are registered once in `MauiProgram.cs` using `Microsoft.Extensions.AI`, and the Smart PDF Viewer resolves them through dependency injection. + +## See also + +* [Getting Started with .NET MAUI Smart PDF Viewer](./getting-started) +* [Document Summaries in .NET MAUI Smart PDF Viewer](./document-summarizer) +* [Smart Redaction in .NET MAUI Smart PDF Viewer](./smart-redaction) +* [Smart Fill in .NET MAUI Smart PDF Viewer](./smart-fill) +* [Localization in .NET MAUI Smart PDF Viewer](./localization) +* [.NET MAUI PDF Viewer Overview](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/overview) +* [Configure Chat Client with AI-Powered Components](https://help.syncfusion.com/maui/common/configure-ai-service) +* [Custom AI Service](https://help.syncfusion.com/maui/common/custom-ai-service) \ No newline at end of file diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/smart-fill.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/smart-fill.md new file mode 100644 index 0000000000..bf57924392 --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/smart-fill.md @@ -0,0 +1,138 @@ +--- +layout: post +title: Smart Fill in .NET MAUI Smart PDF Viewer | Syncfusion +description: Discover how Smart Fill enhances form filling in the Syncfusion .NET MAUI Smart PDF Viewer by automatically detecting and populating PDF form fields. +platform: document-processing +control: SfSmartPdfViewer +documentation: ug +keywords: .net maui smart pdf viewer, smart fill maui, ai form filling, automatic form fill, pdf forms maui +--- + +# Smart Fill in .NET MAUI Smart PDF Viewer + +Smart Fill accelerates completion of PDF forms by using AI to detect fields and populate them from clipboard content or specified data, reducing manual input and errors. The Smart Fill option is available only when the loaded PDF contains form fields and can be enabled or disabled via the [`IsEnabled`](#isenabled) property. Users can review and adjust the populated values before finalizing. + +Users can trigger Smart Fill by selecting the **Smart Fill** button from the **AI Tools** menu in the viewer toolbar. The feature analyzes the current clipboard content (or the data passed programmatically) and maps the extracted values to the corresponding form fields — including text boxes, combo boxes, radio buttons, and list boxes — in the loaded PDF document. + +![Smart Fill in .NET MAUI PDFViewer](images/smart-fill.gif) + +N> The AI service must be configured before using the Smart Fill feature. Refer to [Getting Started](./getting-started) to learn how to register a chat client in `MauiProgram.cs`. + +## Component usage + +Add the following code in the `MainPage.xaml` file to enable and try the Smart Fill feature in the Smart PDF Viewer. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +using Syncfusion.Maui.SmartPdfViewer; +. . . + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + SmartFillSettings = new SmartFillSettings() +}; +pdfViewer.SetBinding(SfSmartPdfViewer.DocumentSourceProperty, "PdfDocumentStream"); +this.Content = pdfViewer; + +{% endhighlight %} +{% endtabs %} + +## SmartFillSettings properties + +The [`SmartFillSettings`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SmartFillSettings.html) class configures the Smart Fill feature in the Smart PDF Viewer. It provides options for integrating AI-powered, context-aware form filling that automates the population of PDF form fields using clipboard or specified data. + +### IsEnabled + +The [`IsEnabled`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SmartFillSettings.html#Syncfusion_Maui_SmartPdfViewer_SmartFillSettings_IsEnabled) property (type: `bool`, default: `true`) gets or sets a value indicating whether Smart Fill is available in the PDF Viewer. When enabled, AI-assisted form filling features are available to users. It can be toggled dynamically based on user roles, document content, or application logic. + +* The Smart Fill button is active only when the loaded PDF document contains form fields. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + SmartFillSettings = new SmartFillSettings + { + IsEnabled = false + } +}; + +{% endhighlight %} +{% endtabs %} + +## Applying Smart Fill programmatically + +Besides the built-in toolbar button, Smart Fill can be invoked programmatically using the `ApplySmartFillAsync` method of the [SfSmartPdfViewer](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html) class. The operation can be cancelled while it is in progress by using the cancellation token. + +### Fill from the clipboard + +The `ApplySmartFillAsync(CancellationToken)` method returns a `Task` and initiates the Smart Fill process using the extracted form field names and the current clipboard data. When executed, this method uses AI to analyze the clipboard content and map the extracted values to the corresponding form fields in the loaded PDF document. The operation can be cancelled while it is in progress. + +{% tabs %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +private async void OnSmartFillClicked(object sender, EventArgs e) +{ + await pdfViewer.ApplySmartFillAsync(new CancellationToken()); +} + +{% endhighlight %} +{% endtabs %} + +N> The `Microsoft.Maui.ApplicationModel.DataTransfer.Clipboard` API reads the clipboard text. If the clipboard is empty, the operation is skipped. + +### Fill from specified data + +The `ApplySmartFillAsync(string, CancellationToken)` method returns a `Task` and initiates the Smart Fill process using the specified string data instead of clipboard content. The `data` parameter specifies the custom text input used by the AI to identify and populate the matching form fields in the loaded PDF document, and the `cancellationToken` parameter specifies a token that can be used to cancel the Smart Fill operation. The operation can be cancelled while it is in progress. + +{% tabs %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +private async void OnSmartFillClicked(object sender, EventArgs e) +{ + string data = "Name: John Doe\nEmail: john.doe@syncfusion.com\nPhone: +1 555 0100"; + await pdfViewer.ApplySmartFillAsync(data, new CancellationToken()); +} + +{% endhighlight %} +{% endtabs %} + +## Integration + +To integrate Smart Fill into a PDF viewer workflow, assign the [`SmartFillSettings`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SmartFillSettings.html) through the `SmartFillSettings` property of [`SfSmartPdfViewer`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html). Ensure that the PDF document contains form fields to use AI-powered filling. + +The Smart Fill button state is automatically updated when the document is loaded or unloaded — the button remains disabled until form fields are detected in the loaded document. + +## See also + +* [.NET MAUI Smart PDF Viewer Overview](./overview) +* [Getting Started with .NET MAUI Smart PDF Viewer](./getting-started) +* [Document Summaries in .NET MAUI Smart PDF Viewer](./document-summarizer) +* [Smart Redaction in .NET MAUI Smart PDF Viewer](./smart-redaction) +* [Form Filling Overview in .NET MAUI PDF Viewer](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/form-filling-overview) \ No newline at end of file diff --git a/Document-Processing/PDF/Smart-PDF-Viewer/maui/smart-redaction.md b/Document-Processing/PDF/Smart-PDF-Viewer/maui/smart-redaction.md new file mode 100644 index 0000000000..f8a08f4eab --- /dev/null +++ b/Document-Processing/PDF/Smart-PDF-Viewer/maui/smart-redaction.md @@ -0,0 +1,192 @@ +--- +layout: post +title: Smart Redaction in .NET MAUI Smart PDF Viewer | Syncfusion +description: Explore how to intelligently redact sensitive information using AI-powered Smart Redaction in your .NET MAUI applications. +platform: document-processing +control: SfSmartPdfViewer +documentation: ug +keywords: .net maui smart pdf viewer, smart redaction maui, ai redaction, pii detection, pdf redact maui +--- + +# Smart Redaction in .NET MAUI Smart PDF Viewer + +The [Smart PDF Viewer](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html) enables intelligent redaction of sensitive information in PDF documents with AI-assisted capabilities. The Smart Redaction feature detects and enables redaction of personally identifiable information (PII), financial data, and other confidential content. + +Smart Redaction allows selecting detection patterns (emails, names, phone numbers, and more) and automatically identifies matching content throughout the document. Users can activate the Smart Redaction feature by selecting the **Smart Redaction** button from the **AI Tools** menu in the viewer toolbar, choose the patterns to detect, run a **Scan**, review the detected items in the Redaction panel, and apply redaction selectively. + +![Smart Redaction in .NET MAUI PDFViewer](images/smart-redaction.gif) + +N> The AI service must be configured before using the Smart Redaction feature. Refer to [Getting Started](./getting-started) to learn how to register a chat client in `MauiProgram.cs`. + +## Component usage + +Add the following code to the `MainPage.xaml` file to enable and evaluate Smart Redaction in the Smart PDF Viewer. Ensure the [SfSmartPdfViewer](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html) control is referenced on the page. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +using Syncfusion.Maui.SmartPdfViewer; +. . . + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + IsSmartRedactViewVisible = true, + SmartRedactSettings = new SmartRedactSettings() +}; +pdfViewer.SetBinding(SfSmartPdfViewer.DocumentSourceProperty, "PdfDocumentStream"); +this.Content = pdfViewer; + +{% endhighlight %} +{% endtabs %} + +## SfSmartPdfViewer properties + +### IsSmartRedactViewVisible + +The [`IsSmartRedactViewVisible`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SfSmartPdfViewer.html#Syncfusion_Maui_SmartPdfViewer_SfSmartPdfViewer_IsSmartRedactViewVisible) property (type: `bool`, default: `false`) gets or sets a value indicating whether the Smart Redaction panel is visible in the Smart PDF Viewer. When set to `true`, the Smart Redaction panel is displayed and users can access AI-assisted redaction tools directly from the viewer interface. When set to `false`, the Smart Redaction panel is hidden from the user interface. The Smart Redaction functionality remains available and can be displayed again by setting this property to `true`. This property controls only the visibility of the panel and does not affect the Smart Redaction feature availability or configuration. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +// Toggle the Smart Redaction panel visibility at runtime. +pdfViewer.IsSmartRedactViewVisible = !pdfViewer.IsSmartRedactViewVisible; + +{% endhighlight %} +{% endtabs %} + +## SmartRedactSettings properties + +### IsEnabled + +The [`IsEnabled`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SmartRedactSettings.html#Syncfusion_Maui_SmartPdfViewer_SmartRedactSettings_IsEnabled) property (type: `bool`, default: `true`) gets or sets a value indicating whether Smart Redaction is available in the PDF Viewer. When disabled, users cannot access AI-assisted redaction features — the Smart Redaction entry is hidden from the **AI Tools** menu, and setting it to `false` also hides the Smart Redaction panel if it is open. Use this setting to restrict access based on context, role, or compliance requirements. + +{% tabs %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + + +{% endhighlight %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + SmartRedactSettings = new SmartRedactSettings + { + IsEnabled = false + } +}; + +{% endhighlight %} +{% endtabs %} + +### RedactPatterns + +The [`RedactPatterns`](https://help.syncfusion.com/cr/maui/Syncfusion.Maui.SmartPdfViewer.SmartRedactSettings.html#Syncfusion_Maui_SmartPdfViewer_SmartRedactSettings_RedactPatterns) property (type: `string[]`) gets or sets a collection of patterns used to identify sensitive information in PDF documents. Custom patterns can be added to detect organization-specific confidential content. Examples include names, phone numbers, email addresses, identification numbers, and financial information. By supplying redaction patterns, you can tailor the redaction process to match specific business, regulatory, or organizational needs. + +The default patterns include: + +* Person names +* Organization names +* Email addresses +* Phone numbers +* Addresses +* Dates +* Account numbers +* Credit card numbers + +{% tabs %} +{% highlight c# tabtitle="MainPage.xaml.cs" %} + +using Syncfusion.Maui.SmartPdfViewer; +. . . + +SfSmartPdfViewer pdfViewer = new SfSmartPdfViewer +{ + IsSmartRedactViewVisible = true, + SmartRedactSettings = new SmartRedactSettings + { + IsEnabled = true, + RedactPatterns = new string[] + { + "Company Name", + "Amount", + "Languages" + } + } +}; + +{% endhighlight %} +{% highlight xaml tabtitle="MainPage.xaml" %} + + + + + + Company Name + Amount + Languages + + + + + +{% endhighlight %} +{% endtabs %} + +N> Since `RedactPatterns` is a `string[]`, it is easier to set it from code-behind, as shown in the C# tab, rather than in XAML. + +## How Smart Redaction works + +1. **Select patterns** – Choose the sensitive-information patterns to detect in the document. The detected patterns are listed with checkboxes in the Redaction panel. +2. **Scan** – Run a scan to let the AI identify matching content throughout the document. The detected items are shown in the panel. +3. **Review** – Verify the list of detected items. The AI-detected information may not be fully accurate, so each item should be reviewed before applying redaction. +4. **Apply redaction** – Apply redaction to the selected items. A confirmation dialog appears before applying redaction to confirm that the process is permanent and irreversible. + +If no sensitive information is found, a **No Data Found** message is displayed. + +## Important redaction behaviors and limitations + +Smart Redaction is irreversible. After applying redaction, the original content cannot be recovered. Undo and redo are not supported for redaction, and the underlying text, images, and metadata are permanently removed. Review all detected content before applying redaction. + +N> For details about redaction in the .NET MAUI PDF Viewer, refer to the [Redaction documentation](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/redaction). + +## Security and compliance considerations + +Smart Redaction ensures complete removal of sensitive content from the PDF document, and redacted content cannot be recovered through text selection, search, or other methods. Maintain backup copies of original documents when required by policy, and test redaction patterns on sample documents before using them in production environments. + +## AI detection accuracy and manual review requirements + +Smart Redaction uses AI to detect sensitive information, and detection may not be 100% accurate. Verify all detected items before applying permanent redaction, and test custom redaction patterns thoroughly before use. + +## See also + +* [.NET MAUI Smart PDF Viewer Overview](./overview) +* [Getting Started with .NET MAUI Smart PDF Viewer](./getting-started) +* [Document Summaries in .NET MAUI Smart PDF Viewer](./document-summarizer) +* [Smart Fill in .NET MAUI Smart PDF Viewer](./smart-fill) +* [Redaction in .NET MAUI PDF Viewer](https://help.syncfusion.com/document-processing/pdf/pdf-viewer/maui/redaction) \ No newline at end of file