Export Annotations to a Document using the Document Converter - WinForms C# .NET 6

This tutorial shows how to add annotations onto the file loaded in a Document Viewer control then save it and export the annotations to the output in a C# WinForms application using the LEADTOOLS SDK.

Note

The tutorial will show how to output the annotations both as an overlay (burned) unto a rasterized image output and as an embed in an output PDF.

Overview  
Summary This tutorial covers exporting annotations from the Document Viewer using the Document Converter class in a C# WinForms application
Completion Time 30 minutes
Visual Studio Project Download tutorial project (7 KB)
Platform C# WinForms Application
IDE Visual Studio 2022
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Before working on the Export Annotations to a Document using the Document Converter - WinForms C# tutorial, get familiar with the basic steps of creating a Document Converter project by reviewing the Add References and Set a License and Save Documents with Document Converter tutorials.

Create the Project and Add the LEADTOOLS References

Start with a copy of the project created in the Save Documents with Document Converter tutorial. If you don't have that project, follow the steps in that tutorial to create it.

Ensure the project has the necessary LEADTOOLS references mentioned in the original tutorial.

If NuGet references are used, this tutorial requires the following NuGet package:

If local DLL references are used, the following DLLs are needed. The DLLs are located at <INSTALL_DIR>\LEADTOOLS22\Bin\net:

For a complete list of which Codec DLLs are required for specific formats, refer to File Format Support.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Note

How to properly add LEADTOOLS NuGet and local references is covered in the Add References and Set a License tutorial.

Initialize Automated Annotations in the DocumentViewer

With the project created, the references added, and the license set, coding can begin.

In Solution Explorer, open Program.cs and add the following statements to the using block at the top of the file.

C#
using Leadtools.Annotations.Engine; 
using Leadtools.Annotations.Rendering; 
using Leadtools.Annotations.WinForms; 

In the InitDocumentViewer() method, change createOptions.UseAnnotations value to true and initialize the AutomationManager and AutomationManagerHelper.

C#
var createOptions = new DocumentViewerCreateOptions(); 
// Set the UI part where the Document Viewer is displayed  
createOptions.ViewContainer = this.Controls.Find("docViewerPanel", false)[0]; 
// Set the UI part where the Thumbnails are displayed  
createOptions.ThumbnailsContainer = this.Controls.Find("thumbPanel", false)[0]; 
// Enable using annotations 
createOptions.UseAnnotations = true; 
 
// Now create the viewer  
_documentViewer = DocumentViewerFactory.CreateDocumentViewer(createOptions); 
// Initialize Annotation Manager and Helper 
var automationManager = _documentViewer.Annotations.AutomationManager; 
var automationManagerHelper = new AutomationManagerHelper(automationManager); 

Add the Load Annotations Code

Use the code below to add a Load Annotations button to the interface in the InitUI() method"

C#
var loadAnnButton = new Button(); 
loadAnnButton.Name = "loadAnnButton"; 
loadAnnButton.Text = "&Load Annotations"; 
loadAnnButton.Width = loadButton.Width * 2; 
loadAnnButton.Location = new System.Drawing.Point(saveAsPDFButton.Location.X + saveAsPDFButton.Width, saveAsPDFButton.Location.Y); 
loadAnnButton.Click += (sender, e) => LoadAnnotations(); 
topPanel.Controls.Add(loadAnnButton); 

Use the code below for the LoadAnnotations() method:

C#
private void LoadAnnotations() 
{ 
   if (_documentViewer.Document != null) 
   { 
      OpenFileDialog openAnnXMLDlg = new OpenFileDialog(); 
      openAnnXMLDlg.Filter = "LEAD Annotations XML|*.xml"; 
      if (openAnnXMLDlg.ShowDialog() == DialogResult.OK) 
      { 
         AnnCodecs annCodecs = new AnnCodecs(); 
         AnnContainer[] annContainers = annCodecs.LoadAll(openAnnXMLDlg.FileName); 
                
         _documentViewer.BeginUpdate(); 
         foreach (AnnContainer loadedContainer in annContainers) 
         { 
            if (loadedContainer != null && loadedContainer.PageNumber <= _documentViewer.Document.Pages.Count) 
            {  
               // Load Containers from XML file to the corresponding page 
               _documentViewer.Annotations.Automation.Containers[loadedContainer.PageNumber - 1] = loadedContainer; 
 
               // Let the Document Viewer know that the annotations container has been modified for the relevant pages 
               if (_documentViewer.Annotations.IsContainerModified(loadedContainer.PageNumber) != true) 
                  _documentViewer.Annotations.SetContainerModified(loadedContainer.PageNumber, true); 
            } 
         } 
         _documentViewer.EndUpdate(); 
      } 
   } 
   else 
      MessageBox.Show("Please Load Document First"); 
} 

Initialize the Document Converter

Modify the code for the InitDocumentConverter() so that the document converter uses an instance of the AnnWinFormsRenderingEngine() class and loads the necessary resources.

C#
private void InitDocumentConverter() 
{ 
   _documentConverter = new DocumentConverter(); 
   // Set OCR Engine 
   _ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD); 
   _ocrEngine.Startup(null, null, null, @"C:\LEADTOOLS22\Bin\Common\OcrLEADRuntime"); 
   _documentConverter.SetOcrEngineInstance(_ocrEngine, false); 
   // Set Document Writer 
   _documentConverter.SetDocumentWriterInstance(new DocumentWriter()); 
   // Set Annotations rendering engine 
   _documentConverter.SetAnnRenderingEngineInstance(new AnnWinFormsRenderingEngine()); 
   // Load Image Resources for annotations (e.g.: RubberStampAnnotations) 
   _documentConverter.AnnRenderingEngineInstance.Resources = Tools.LoadResources(); 
} 

Add the Export Annotations Code

Modify the code for the ConvertToImage() method to be as below. This will set the AnnotationsMode for the Converter to burn/overlay any annotations containers present to the image when saving to a raster image output.

C#
private void ConvertToImage(RasterImageFormat imageFormat) 
{ 
   if (_documentViewer.Document != null) 
   { 
      // Prepare document for saving 
      _documentViewer.PrepareToSave(); 
 
      SaveFileDialog saveAsImageDlg = new SaveFileDialog(); 
      saveAsImageDlg.InitialDirectory = @"C:\LEADTOOLS22\Resources\Images"; 
      saveAsImageDlg.Filter = $"{imageFormat}|*.{RasterCodecs.GetExtension(imageFormat)}"; 
      if (saveAsImageDlg.ShowDialog(this) != DialogResult.OK) 
         return; 
 
      DocumentConverterJobData jobData = DocumentConverterJobs.CreateJobData(_documentViewer.Document, saveAsImageDlg.FileName, imageFormat); 
      jobData.DocumentFormat = DocumentFormat.User; 
      jobData.InputDocumentFirstPageNumber = 1; 
      jobData.InputDocumentLastPageNumber = -1; 
      jobData.JobName = "Convert to Image Job"; 
                         
      // Set the Annotations Mode in the Document Converter job's data to overlay/burn the annotations to raster output 
      jobData.AnnotationsMode = DocumentConverterAnnotationsMode.Overlay; 
 
      DocumentConverterJob job = _documentConverter.Jobs.CreateJob(jobData); 
      _documentConverter.Jobs.RunJob(job); 
 
      if (job.Errors.Count > 0) 
         foreach (var error in job.Errors) 
            MessageBox.Show($"Error during conversion: {error.Error.Message}\n"); 
      else 
         MessageBox.Show($"Successfully Saved Document to {saveAsImageDlg.FileName}\n"); 
   } 
   else 
      MessageBox.Show("Please Load Document First"); 
} 

Modify the code for the ConvertToDocument() method to be as below. This will set the AnnotationsMode for the Converter to embed any PDF-supported annotation present when saving to a PDF document output.

C#
private void ConvertToDocument(DocumentFormat documentFormat) 
{ 
   if (_documentViewer.Document != null) 
   { 
      _documentViewer.PrepareToSave(); 
             
      SaveFileDialog saveAsDocDlg = new SaveFileDialog(); 
      saveAsDocDlg.InitialDirectory = @"C:\LEADTOOLS22\Resources\Images"; 
      saveAsDocDlg.Filter = $"{documentFormat}|*.{DocumentWriter.GetFormatFileExtension(documentFormat)}"; 
      if (saveAsDocDlg.ShowDialog(this) != DialogResult.OK) 
         return; 
 
      DocumentConverterJobData jobData = DocumentConverterJobs.CreateJobData(_documentViewer.Document, saveAsDocDlg.FileName, documentFormat); 
      jobData.AnnotationsMode = DocumentConverterAnnotationsMode.Embed; 
      jobData.JobName = "Convert to PDF Job"; 
 
      DocumentConverterJob job = _documentConverter.Jobs.CreateJob(jobData); 
      _documentConverter.Jobs.RunJob(job); 
 
      if (job.Errors.Count > 0) 
         foreach (var error in job.Errors) 
            MessageBox.Show($"Error during conversion: {error.Error.Message}\n"); 
      else 
         MessageBox.Show($"Successfully Saved Document to {saveAsDocDlg.FileName}\n"); 
   } 
   else 
      MessageBox.Show("Please Load Document First"); 
} 

Run the Project

Run the project by pressing F5, or by selecting Debug -> Start Debugging.

If the steps were followed correctly, the application will be able to load an annotations XML file to a document in the Document Viewer and then export the annotations when saving using the DocumentConverter class, either by overlaying/burning them to a raster image output, or by embedding them in a PDF document output.

A sample XML (Export-Annotations-to-Output-using-Document-Converter-File.xml) is provided with the project that contains annotations data. This file is in the same directory as the Program.cs C# source file.

This XML file can be used with the sample ocr1-4.tif image from: C:\LEADTOOLS22\Resources\Images

The following screenshots show the expected output from saving to Image and saving to Document formats:

Image Output:

Output Image With Annotations

Note that the annotations were overlayed as 1-bit in the image output. This is because the original image has 1-bit color depth. If overlaying the annotations in color is desired, jobData.RasterImageBitsPerPixel = 24 can be used to set the output color depth from the color converter.

Document Output:

Output Document With Annotations

Note that only annotations objects that are supported as PDF annotations are embedded in the output. For more details, see PDFAnnotationType

Wrap-up

This tutorial showed how to utilize the DocumentConverter class to export annotations when saving a LEADDocument.

See Also

Help Version 22.0.2024.3.20
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.

Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.