How to merge different files into a single PDF document using C#/VB.NET?
Syncfusion® PDF is a feature-rich and high-performance .NET PDF library used to create, read, and edit PDF documents programmatically without Adobe dependencies. This library also offers functionality to merge, split, stamp, add forms, compress, and secure PDF files.
Using this library, you can merge documents of different file formats into a single PDF document. This sample merges an image file, a PDF document, a Word document, and an Excel file into a single PDF document.
Steps to merge files of different file formats into a PDF document programmatically in C#:
- Create a new C# console application project.
Caption
- Install the following NuGet packages as references to your .NET Framework application from NuGet.org:
- The Syncfusion.Pdf.WinForms NuGet to package for working with PDF files.
- The Syncfusion.DocIO.WinForms and Syncfusion.DocToPdfConverter.WinForms packages for working with Word documents and converting them into PDF documents.
- The Syncfusion.XlsIO.WinForms and Syncfusion.ExcelToPdfConverter.WinForms packages for working with Excel documents and converting them into PDF documents.
- The files of different file formats can be merged into a single PDF document only after converting each file to a PDF document.
- Include the following namespaces in the Program.cs file.
C#
using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.DocToPDFConverter; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Parsing; using Syncfusion.XlsIO; using Syncfusion.ExcelToPdfConverter; using System; using System.Drawing; using System.IO;
VB.NET
Imports Syncfusion.DocIO Imports Syncfusion.DocIO.DLS Imports Syncfusion.DocToPDFConverter Imports Syncfusion.Pdf Imports Syncfusion.Pdf.Graphics Imports Syncfusion.Pdf.Parsing Imports Syncfusion.XlsIO Imports Syncfusion.ExcelToPdfConverter Imports System.Drawing Imports System.IO
- Include the following code snippet in the main method of Program.cs file, to merge the documents of different file formats into a single PDF and add watermark to the merged PDF document.
C#
// Get the path of documents into DirectoryInfo
DirectoryInfo directoryInfo = new DirectoryInfo("../../Documents/");
// Create a new PDF document
PdfDocument document = new PdfDocument();
// Initialize MemoryStream
MemoryStream stream = new MemoryStream();
// Convert the documents to PDF
foreach (FileInfo fileInfo in directoryInfo.GetFiles())
{
// Import pages from PDF document and store them into the stream
if (fileInfo.Extension == ".pdf")
stream = ImportPagesFromPDF(fileInfo.FullName);
// Convert the Excel document into PDF and store it in the stream
if (fileInfo.Extension == ".xls" || fileInfo.Extension == ".xlsx")
stream = ConvertExcelToPDF(fileInfo.FullName);
// Convert the Word document into PDF and store it in the stream
if (fileInfo.Extension == ".doc" || fileInfo.Extension == ".docx")
stream = ConvertWordToPDF(fileInfo.FullName);
// Convert the image file into PDF and store it in the stream
if (fileInfo.Extension == ".jpg" || fileInfo.Extension == ".png" || fileInfo.Extension == ".jpeg")
stream = ImageToPDF(fileInfo.FullName);
// Load the stream into PdfLoadedDocument
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(stream);
// Add the watermark
AddWatermark(loadedDocument, document);
}
// Save the PDF document
document.Save("MergedPDF.pdf");
// Close the instance of PdfDocument
document.Close(true);
VB.NET
' Get the path of documents into DirectoryInfo
Dim directoryInfo As DirectoryInfo = New DirectoryInfo("../../Documents/")
' Create a new PDF document
Dim document As PdfDocument = New PdfDocument
' Initialize MemoryStream
Dim stream As MemoryStream = New MemoryStream
' Convert the documents to PDF
For Each fileInfo As FileInfo In directoryInfo.GetFiles
' Import pages from PDF document and store them into the stream
If (fileInfo.Extension = ".pdf") Then
stream = ImportPagesFromPDF(fileInfo.FullName)
End If
' Convert the Excel document into PDF and store it in the stream
If ((fileInfo.Extension = ".xls") OrElse (fileInfo.Extension = ".xlsx")) Then
stream = ConvertExcelToPDF(fileInfo.FullName)
End If
' Convert the Word document into PDF and store it in the stream
If ((fileInfo.Extension = ".doc") OrElse (fileInfo.Extension = ".docx")) Then
stream = ConvertWordToPDF(fileInfo.FullName)
End If
' Convert the image file into PDF and store it in the stream
If ((fileInfo.Extension = ".jpg") OrElse ((fileInfo.Extension = ".png") OrElse (fileInfo.Extension = ".jpeg"))) Then
stream = ImageToPDF(fileInfo.FullName)
End If
' Load the stream into PdfLoadedDocument
Dim loadedDocument As PdfLoadedDocument = New PdfLoadedDocument(stream)
' Add the watermark
AddWatermark(loadedDocument, document)
Next
' Save the PDF document
document.Save("MergedPDF.pdf")
' Close the instance of PdfDocument
document.Close(True)
- The code snippet given above has static methods declared for the conversion of files of different file formats to PDF documents and the addition of a watermark.
- Define the ImportPagesFromPDF static method with the following code snippet to import pages from one PDF document into another PDF document.
C#
// Load the PDF document into PdfLoadedDocument
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(filePath);
// Create a new PDF document
PdfDocument document = new PdfDocument();
// Import all the pages in PdfLoadedDocument into PdfDocument
document.ImportPageRange(loadedDocument, 0, loadedDocument.Pages.Count - 1);
// Save the PDF document as a stream
MemoryStream stream = new MemoryStream();
document.Save(stream);
// Close the instances of PdfLoadedDocument and PdfDocument
loadedDocument.Close(true);
document.Close(true);
// Return the stream
return stream;
VB.NET
' Load the PDF document into PdfLoadedDocument
Dim loadedDocument As PdfLoadedDocument = New PdfLoadedDocument(filePath)
' Create a new PDF document
Dim document As PdfDocument = New PdfDocument
' Import all the pages in PdfLoadedDocument into PdfDocument
document.ImportPageRange(loadedDocument, 0, loadedDocument.Pages.Count - 1)
' Save the PDF document as a stream
Dim stream As MemoryStream = New MemoryStream
document.Save(stream)
' Close the instances of PdfLoadedDocument and PdfDocument
loadedDocument.Close(True)
document.Close(True)
' Return the stream
Return stream
- An Excel document can be converted to PDF by using the Convert method of ExcelToPdfConverter. Define the ConvertExcelToPDF static method with the following code snippet to convert an Excel document to PDF.
C#
// Create an instance of ExcelEngine
ExcelEngine excelEngine = new ExcelEngine();
// Initialize IApplication and set the default application version
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2016;
// Load the Excel document into IWorkbook
IWorkbook workbook = application.Workbooks.Open(filePath, ExcelOpenType.Automatic);
// Initialize ExcelToPdfConverter for the workbook
ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook);
// Initialize ExcelToPdfConverterSettings and set the layout
ExcelToPdfConverterSettings settings = new ExcelToPdfConverterSettings();
settings.LayoutOptions = LayoutOptions.FitAllColumnsOnOnePage;
// Convert the Excel document to PDF with converter settings
PdfDocument document = converter.Convert(settings);
// Save the PDF document as a stream
MemoryStream stream = new MemoryStream();
document.Save(stream);
// Close the instances of PdfDocument, IWorkbook, and dispose of ExcelEngine
document.Close(true);
workbook.Close();
excelEngine.Dispose();
// Return the stream
return stream;
VB.NET
' Create an instance of ExcelEngine
Dim excelEngine As ExcelEngine = New ExcelEngine
' Initialize IApplication and set the default application version
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2016
' Load the Excel document into IWorkbook
Dim workbook As IWorkbook = application.Workbooks.Open(filePath, ExcelOpenType.Automatic)
' Initialize ExcelToPdfConverter for the workbook
Dim converter As ExcelToPdfConverter = New ExcelToPdfConverter(workbook)
' Initialize ExcelToPdfConverterSettings and set the layout
Dim settings As ExcelToPdfConverterSettings = New ExcelToPdfConverterSettings
settings.LayoutOptions = LayoutOptions.FitAllColumnsOnOnePage
' Convert the Excel document to PDF with converter settings
Dim document As PdfDocument = converter.Convert(settings)
' Save the PDF document as a stream
Dim stream As MemoryStream = New MemoryStream
document.Save(stream)
' Close the instances of PdfDocument, IWorkbook, and dispose of ExcelEngine
document.Close(True)
workbook.Close
excelEngine.Dispose()
' Return the stream
Return stream
- You can convert a word document into PDF using the ConvertToPDF method of DocToPDFConverter. Include the following code snippet in the definition part of the ConvertWordToPDF method.
C#
// Load an existing Word document into WordDocument
WordDocument wordDocument = new WordDocument(filePath, FormatType.Automatic);
// Initialize the DocToPDFConverter
DocToPDFConverter converter = new DocToPDFConverter();
// Convert Word document into PDF document
PdfDocument document = converter.ConvertToPDF(wordDocument);
// Save the PDF document as a stream
MemoryStream stream = new MemoryStream();
document.Save(stream);
// Close the instances of PdfDocument and WordDocument
document.Close(true);
wordDocument.Close();
// Return the stream
return stream;
VB.NET
' Load an existing Word document into WordDocument
Dim wordDocument As WordDocument = New WordDocument(filePath, FormatType.Automatic)
' Initialize the DocToPDFConverter
Dim converter As DocToPDFConverter = New DocToPDFConverter
' Convert Word document into PDF document
Dim document As PdfDocument = converter.ConvertToPDF(wordDocument)
' Save the PDF document as a stream
Dim stream As MemoryStream = New MemoryStream
document.Save(stream)
' Close the instances of PdfDocument and WordDocument
document.Close(True)
wordDocument.Close()
' Return the stream
Return stream
- Converting image to PDF is nothing but drawing the image on the PDF document. This can be achieved by using the DrawImage method of PdfGraphics. Define the ImageToPDF static method with the following code snippet to convert an image to PDF.
C#
// Create a new PDF document
PdfDocument document = new PdfDocument();
// Add a page to the document
PdfPage page = document.Pages.Add();
// Load the image into PdfBitmap
PdfBitmap image = new PdfBitmap(imagePath);
// Draw the image on PdfPage
page.Graphics.DrawImage(image, 70, 30);
// Save the PDF document as a stream
MemoryStream stream = new MemoryStream();
document.Save(stream);
// Close the instance of PdfDocument
document.Close(true);
// Return the stream
return stream;
VB.NET
' Create a new PDF document
Dim document As PdfDocument = New PdfDocument
' Add a page to the document
Dim page As PdfPage = document.Pages.Add
' Load the image into PdfBitmap
Dim image As PdfBitmap = New PdfBitmap(imagePath)
' Draw the image on PdfPage
page.Graphics.DrawImage(image, 70, 30)
' Save the PDF document as a stream
Dim stream As MemoryStream = New MemoryStream
document.Save(stream)
' Close the instance of PdfDocument
document.Close(True)
' Return the stream
Return stream
- Use the following code snippet in the AddWatermark method to merge and add a watermark to the PDF documents.
C#
for (int i = 0; i < loadedDocument.Pages.Count; i++)
{
// Set the width, height, and margins for PdfDocument
document.PageSettings.Margins.All = 0;
document.PageSettings.Width = 500;
document.PageSettings.Height = 800;
// Create a PdfTemplate
PdfTemplate template = loadedDocument.Pages[i].CreateTemplate();
// Add a page to the PdfDocument
PdfPage page = document.Pages.Add();
// Create PdfGraphics for the page
PdfGraphics graphics = page.Graphics;
// Draw the PDF template
graphics.DrawPdfTemplate(template, new PointF(0, 0), new SizeF(page.GetClientSize().Width, page.GetClientSize().Height));
// Initialize PdfStandardFont
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold);
// Save the graphics of the page
PdfGraphicsState state = page.Graphics.Save();
// Draw the watermark on the PDF page
graphics.SetTransparency(0.5f);
graphics.DrawString("Page Number : " + document.Pages.Count.ToString(), font, PdfBrushes.Red, new PointF(350, 400));
}
VB.NET
For i As Integer = 0 To loadedDocument.Pages.Count - 1 Step 1
' Set the width, height, and margins for PdfDocument
document.PageSettings.Margins.All = 0
document.PageSettings.Width = 500
document.PageSettings.Height = 800
' Create a PdfTemplate
Dim template As PdfTemplate = loadedDocument.Pages(i).CreateTemplate
' Add a page to the PdfDocument
Dim page As PdfPage = document.Pages.Add
' Create PdfGraphics for the page
Dim graphics As PdfGraphics = page.Graphics
' Draw the PDF template
graphics.DrawPdfTemplate(template, New PointF(0, 0), New SizeF(page.GetClientSize.Width, page.GetClientSize.Height))
' Initialize PdfStandardFont
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold)
' Save the graphics of the page
Dim state As PdfGraphicsState = page.Graphics.Save
' Draw the watermark on the PDF page
graphics.SetTransparency(0.5!)
graphics.DrawString("Page Number : " + document.Pages.Count.ToString(), font, PdfBrushes.Red, New PointF(350, 400))
Next
By executing the program, you will get the PDF document as follows.
Take a moment to peruse the documentation, where you will find other options like RTF to PDF conversion, XPS to PDF conversion, PDF to image conversion, HTML to MHTML, HTML to SVG, and partial webpage to SVG, etc.
Click here to explore the rich set of Syncfusion PDF features.
An online sample link to convert Word documents to PDF, RTF to PDF, XPS to PDF, TIFF to PDF, PDF to image, and Excel documents to PDF.
See Also:
Merge PDF documents with grouped bookmarks.
Merge all PDF files in a folder into a single PDF document.
Starting with v16.2.0.x, if you reference Syncfusion® assemblies from the trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without a trial message.
I hope you enjoyed learning about how to merge different files into a single PDF document using C#/VB.NET.
You can refer to our .NET PDF to learn about its other groundbreaking feature representations, documentation and how to quickly get started with configuration specifications. You can also explore our demo to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums or feedback portal. We are always happy to assist you!