PDF Creator ASP.NET Core samples · .NET 10 and .NET 11

Merge and Split PDF

Merges two PDF files into one (as files and as streams), then splits the result: extracts the first page and a range of pages into new PDF files.

C# code of this sample

Pages/MergeSplitDemo.cshtml.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

using ExpertPdf.PdfCreator;

namespace ExpertPdf.PdfCreator.Samples.Pages
{
    public class MergeSplitDemoModel : PageModel
    {
        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string FirstPdf { get => _FirstPdf; set => _FirstPdf = Helper.HostedSampleFile(value); }
        private string _FirstPdf = Path.Combine(Helper.FilesFolder, "htmltopdf.pdf");

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string SecondPdf { get => _SecondPdf; set => _SecondPdf = Helper.HostedSampleFile(value); }
        private string _SecondPdf = Path.Combine(Helper.FilesFolder, "sample.pdf");

        [BindProperty]
        public bool MergeStreams { get; set; } = false;

        [BindProperty]
        public int Result { get; set; } = 0;

        public static readonly string[] ResultNames = { "The merged document", "The first page", "Pages 2 to 4" };

        public string Message { get; set; }

        public void OnGet()
        {
        }

        public IActionResult OnPost()
        {
            try
            {
                return File(CreatePdf(), "application/pdf", "MergeSplit.pdf");
            }
            catch (Exception ex)
            {
                Message = "The PDF document was not created. " + ex.Message;
                return Page();
            }
        }

        private byte[] CreatePdf()
        {
            // LicensingManager.LicenseKey = "your license key";

            string firstPdf = FirstPdf.Trim();
            string secondPdf = SecondPdf.Trim();
            byte[] merged;

            if (!MergeStreams)
            {
                // merge files into a file (a temporary file here)
                string mergedFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".pdf");
                MergePdf.Merge(new string[] { firstPdf, secondPdf }, mergedFile);
                merged = System.IO.File.ReadAllBytes(mergedFile);
                System.IO.File.Delete(mergedFile);
            }
            else
            {
                // merge streams into a stream, for example PDF documents kept in memory
                using (FileStream first = System.IO.File.OpenRead(firstPdf))
                using (FileStream second = System.IO.File.OpenRead(secondPdf))
                using (MemoryStream output = new MemoryStream())
                {
                    MergePdf.Merge(new Stream[] { first, second }, output);
                    merged = output.ToArray();
                }
            }

            if (Result == 0)
                return merged;

            // split the merged document: the page indexes are 0 based, the second number is the count of pages to extract
            Document mergedDocument = new Document(new MemoryStream(merged));
            Document part = Result == 1
                ? SplitPdf.ExtractPages(mergedDocument, 0, 1)
                : SplitPdf.ExtractPages(mergedDocument, 1, 3);
            byte[] pdf = part.Save();
            part.Close();
            mergedDocument.Close();
            return pdf;
        }
    }
}