HTML to PDF Converter ASP.NET Core samples · .NET 10 and .NET 11

ExpertPdf Html To Pdf Converter for .NET - Pdf Merge - C# / ASP.NET Sample

This sample shows how to use ExpertPdf Library for .NET to merge 2 different pdf documents into a new pdf document.

Here are the 2 individual pdf documents:
File 1
File 2

Click on the "Create PDF" button below to see the merge result.

C# code of this sample

Pages/PdfMerge.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ExpertPdf.HtmlToPdf.PdfDocument;

namespace ExpertPdf.Samples.Pages
{
    public class PdfMergeModel : PageModel
    {
        public void OnGet()
        {
        }

        public IActionResult OnPost()
        {
            // the 2 initial files
            string file1 = Startup.ServerPath + @"\wwwroot\files\doc1.pdf";
            string file2 = Startup.ServerPath + @"\wwwroot\files\doc2.pdf";

            // load the 2 pdf documents
            Document doc1 = new Document(file1);
            Document doc2 = new Document(file2);

            // create a new pdf document
            Document doc = new Document();

            // add the pages of those 2 documents to the new document
            doc.AppendDocument(doc1);
            doc.AppendDocument(doc2);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();
            doc1.Close();
            doc2.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Sample.pdf";
            return fileResult;
        }
    }
}