Wednesday, January 24, 2018

How to mearge multiple PDF files with page number using PDFSharp using C# MVC

In this article how to mearge multiple PDF file using PDFSharp dll in c# MVC

first install this package from nuget "Install-Package PdfSharp -Version 1.32.3057"

string DirectoryPath = HttpContext.Server.MapPath("~/YourDirectoryName/");
 
// Get all PDF Files 
 
string[] pdfs = Directory.GetFiles(DirectoryPath);
 
// Pass all PDF files in function 
 
MergeMultiplePDFIntoSinglePDF(DirectoryPath + "YourMeargeFileName.pdf", pdfs);
 
// Add below function for generate single pdf file 
 
private void MergeMultiplePDFIntoSinglePDF(string outputFilePath, string[] pdfFiles)
{
 PdfDocument document = new PdfDocument();
 
 foreach (string pdfFile in pdfFiles)
 {
  PdfDocument inputPDFDocument = 
  PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import); 
 
  document.Version = inputPDFDocument.Version;
 
  foreach (PdfPage page in inputPDFDocument.Pages)
  { 
     document.AddPage(page);
  }
 }
 
 XFont font = new XFont("Verdana", 9);
 XBrush brush = XBrushes.Black;
 
 string noPages = document.Pages.Count.ToString();
 
 for (int i = 0; i < document.Pages.Count; ++i)
 {
  PdfPage page = document.Pages[i];
 
  // Make a layout rectangle.
  XRect layoutRectangle = new 
  XRect(240/*X*/, page.Height - font.Height - 10/*Y*/ 
  , page.Width/*Width*/, font.Height/*Height*/);
 
  using (XGraphics gfx = XGraphics.FromPdfPage(page))
  {
     gfx.DrawString("Page " + (i + 1).ToString() + " of " + 
     noPages, font, brush, layoutRectangle, XStringFormats.Center);
  }
 }
 
 document.Options.CompressContentStreams = true;
 document.Options.NoCompression = false;
 document.Save(outputFilePath);
}

1 comment :

  1. I know a commercial sdk that can handle a variety of PDF operations, including mearge multiple PDF in C#, extracting text and images from PDF, and PDF encryption, etc.

    ReplyDelete