Merge pdf files using pdfsharp C# and build your own API endpoint.

  

 [Route("home/api/MergePDF"), HttpGet]

        public HttpResponseMessage MergePDF()

        {

            byte[] resultByte = null;

            var result = new HttpResponseMessage(HttpStatusCode.OK);

            try

            {

             resultByte = PDFLogic.PDFDOC();

             result.Content = new ByteArrayContent(resultByte);

             result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

            }

            catch (Exception ex)

            {

 

            }

            return result;

        }

 

       public static byte[] PDFDOC()

        {

            byte[] tempFile = new byte[] { };

 

            //File Path #1

            string file1Path = @"";

 

            //File Path #2

            string file2Path = @"";

            // Get some file names

            string[] files = { file1Path, file2Path};

 

            // Open the output document

            PdfDocument outputDocument = new PdfDocument();

 

            // Iterate files

            foreach (string file in files)

            {

 

                PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);

                // Iterate pages

                int count = inputDocument.PageCount;

                for (int idx = 0; idx < count; idx++)

                {

                    // Get the page from the external document...

                    PdfPage page = inputDocument.Pages[idx];

                    // ...and add it to the output document.

                    outputDocument.AddPage(page);

                }

            }

            // Save the document...

            using (MemoryStream stream = new MemoryStream())

            {

                outputDocument.Save(stream);

                return stream.ToArray();

            }

        }


1. Open Visual Studio clicks on to create a new project.




2.  Select Web as a type of project, then pick ASP.NET MVC.


3.  Give the project a name.


4. From the open windows, select MVC and tick the Web API checkbox.


5.Create a new logic folder to place our pdf merging code.



6. Create a new C# class.


7. Install the PdfSharp library

Install-Package PdfSharp -Version 1.50.5147




8.  C# API controller code


8. C# PDF merging process code











































Comments