Add and Remove Pages from a LEADDocument - C# .NET

This tutorial shows how to add pages to a LEADDocument and remove pages from it in a C# .NET application using the LEADTOOLS SDK.

Overview  
Summary This tutorial covers how to modify the DocumentPages of a LEADDocument in a C# .NET Console application.
Completion Time 30 minutes
Visual Studio Project Download tutorial project (1 KB)
Platform C# .NET Console Application
IDE Visual Studio 2019, 2022
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Add and Remove Pages from a LEADDocument - C# .NET tutorial.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If you do not have that project, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project. References can be added via NuGet packages.

This tutorial requires the following NuGet package:

For a complete list of which DLL files are required for your application, refer to Files to be Included With Your Application.

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

Adding LEADTOOLS NuGet references and setting a license are covered in more detail in the Add References and Set a License tutorial.

Create the LEADDocument Code

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

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

C#
// Using block at the top  
using System; 
using Leadtools; 
using Leadtools.Document; 
using Leadtools.Document.Converter; 

Add the following global variable to the Program class.

C#
static LEADDocument document = DocumentFactory.Create(new CreateDocumentOptions() { UseCache = false }); 

Using DocumentFactory.Create() will create a virtual document that allows for the modification of the Pages property of the LEADDocument. In contrast, creating the LEADDocument instance using DocumentFactory.LoadFromFile() method will result in a read-only instance.

Add two methods inside Program.cs named InsertPageFromFile(string fileName, int pageNumber) and RemovePageFromFile(int pageNumber). Call both methods inside Main() under SetLicense().

Add the code below to add the following functionality:

C#
static void Main(string[] args) 
{ 
   try 
   { 
      string filename = @"PATH TO PDF FILE"; 
      string pageFile = @"PATH TO PAGE TO BE ADDED"; 
      string outputFile = @"PATH TO PDF OUTPUT"; 
      int insertPageNumber = 0; 
      int removePageNumber = 1; 
 
      if (!SetLicense()) 
         Console.WriteLine("Error setting license"); 
      else 
         Console.WriteLine("License file set successfully"); 
 
      LEADDocument loadedDocument = DocumentFactory.LoadFromFile(filename, new LoadDocumentOptions { UseCache = false }); 
      for (int i = 0; i < loadedDocument.Pages.Count; i++) 
      { 
         document.Pages.Add(loadedDocument.Pages[i]); 
      } 
 
      if (document != null) 
      { 
         // Insert and remove pages 
         InsertPageFromFile(pageFile, insertPageNumber); 
         RemovePageFromFile(removePageNumber); 
 
         // Save modified result 
         DocumentConverter docConverter = new DocumentConverter(); 
         docConverter.SetDocumentWriterInstance(new Leadtools.Document.Writer.DocumentWriter()); 
         var jobData = new DocumentConverterJobData 
         { 
            Document = document, 
            OutputDocumentFileName = outputFile, 
            DocumentFormat = Leadtools.Document.Writer.DocumentFormat.Pdf 
         }; 
         var job = docConverter.Jobs.CreateJob(jobData); 
         docConverter.Jobs.RunJob(job); 
         if (job.Errors.Count != 0) 
            Console.WriteLine(String.Format("Modified document saved to {0}", outputFile)); 
         else foreach (var error in job.Errors) 
               Console.WriteLine($"There was an error:{error.Error}"); 
      } 
   } 
   catch (Exception ex) 
   { 
      Console.WriteLine(ex.Message); 
   } 
} 

Note

A virtual document is a LEADDocument object that exists in memory that is used to construct documents consisting of pages from various document files. Once you are ready to make the virtual document a physical document file, or "finalize" it, you can either set the LEADDocument in the DocumentViewer, or use the DocumentConverter class.

Add the Insert Page Code

Inside the InsertPageFromFile() method, add the code below to load a "child" document and add the first page to the virtual document at the specified position.

C#
static void InsertPageFromFile(string fileName, int pageNumber) 
{ 
   // Check if pageNumber is valid 
   if (pageNumber < 0 || pageNumber > document.Pages.Count) 
      return; 
   LEADDocument childDocument = DocumentFactory.LoadFromFile(fileName, new LoadDocumentOptions { UseCache = false }); 
   document.Pages.Insert(pageNumber, childDocument.Pages[0]); 
 
   Console.WriteLine(String.Format("Image {0} inserted as page {1} to loaded document", fileName, pageNumber));  
} 

Add the Remove Page Code

Add the code below to the RemovePageFromFile() method to remove the page inside the virtual document at the specified position.

C#
static void RemovePageFromFile(int pageNumber) 
{ 
   // Check if pageNumber is valid 
   if (document.Pages.Count < 2 || pageNumber > document.Pages.Count) 
      return; 
   document.Pages.RemoveAt(pageNumber); 
    
   Console.WriteLine(String.Format("Page {0} removed from loaded document", pageNumber)); 
} 

Handling Streams

If your project requires reading and writing a document via memory stream, then it can be done as follows:

C#
        public void DocumentFactoryLoadFromStreamExample() 
        { 
            // Get a stream to anything, in this case a file  
            // Note that the stream must be seekable  
            var fileName = Path.Combine(LEAD_VARS.ImagesDir, "Leadtools.pdf"); 
            using (var stream = File.OpenRead(fileName)) 
            { 
                // We must keep the stream alive as long as the document is alive  
                var options = new LoadDocumentOptions(); 
                using (var document = DocumentFactory.LoadFromStream(stream, options)) 
                { 
                    Console.WriteLine(document.DocumentId); 
                } 
            } 
        } 
        static class LEAD_VARS 
        { 
            public const string ImagesDir = @"C:\LEADTOOLS22\Resources\Images"; 
        } 

Run the Project

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

If the steps were followed correctly, the application loads a document, inserts a page from a different file into the specified position, removes a page at the specified position, and saves the modified virtual document as a PDF.

Wrap-up

This tutorial showed how to manipulate pages in a LEADDocument. It also covered how to use the LEADDocument and DocumentConverter classes.

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.