C# Copy PDF pages

Sometimes we may have such a requirement, which is to copy PDF pages from one PDF document to another PDF document. Since PDF documents are not as easy to edit as word documents, copying is also relatively not that easy. Writing this article is mainly to share a simple and relatively easy to implement method - use C# to copy the pages of a PDF document, including text, pictures and backgrounds, to a specified location in another PDF document.

Below are the two PDF files I prepared:



 Goal: Copy the first page of the left PDF document to the position of the second page of the right PDF document.

 

C#

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
 
namespace Copy PDF pages to another PDF document
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an object of class PdfDocument doc1 and load the first PDF document
            PdfDocument doc1 = new PdfDocument();
            doc1.LoadFromFile("Fairytale.pdf");

            //Initialize an object of class PdfDocument doc2 and load the second PDF document
            PdfDocument doc2 = new PdfDocument();
            doc2.LoadFromFile("The practice of various desserts.pdf");

            // Get the first page of the first PDF document and its page size, and create a PDF template based on the first page
            PdfPageBase page = doc1.Pages[0];
            SizeF size = page.Size;
            PdfTemplate template = page.CreateTemplate();

            // Copy the first page of the first PDF document to the second PDF document /* Call the Insert(int index, SizeF size, PdfMargins margins) method, in the second PDF document,
Insert a new page of the same size as the first page into the specified position of the document (here is the second page),
Then apply the template created in step 3 to that page */
            doc2.Pages.Insert(1, size, new PdfMargins(0, 0));
            doc2.Pages[1].Canvas.DrawTemplate(template, new PointF(0, 0));

            // If you want to copy the first page to the last page of the second document, use the following code to add a new page to the end of the second document, and then apply the template to the page //doc2.Pages. Add(size, new PdfMargins( 0 , 0 ));
 
            // Save the file and reopen it
            doc2.SaveToFile("Copy.pdf");
            System.Diagnostics.Process.Start("复制.pdf");
        }
    }
}

 Test Results:



 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326182032&siteId=291194637