If you have multiple images that you want to combine into one file for easier distribution or storage, converting them into a single PDF document is a great solution. This process not only saves space but also ensures that all your images are kept together in one file, making it convenient to share or transfer. In this article, you will learn how to combine several images into a single PDF document in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Combine Multiple Images into a Single PDF in C# and VB.NET
In order to convert all the images in a folder to a PDF, we iterate through each image, add a new page to the PDF with the same size as the image, and then draw the image onto the new page. The following are the detailed steps.
- Create a PdfDocument object.
- Set the page margins to zero using PdfDocument.PageSettings.SetMargins() method.
- Get the folder where the images are stored.
- Iterate through each image file in the folder, and get the width and height of a specific image.
- Add a new page that has the same width and height as the image to the PDF document using PdfDocument.Pages.Add() method.
- Draw the image on the page using PdfPageBase.Canvas.DrawImage() method.
- Save the document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace ConvertMultipleImagesIntoPdf { class Program { static void Main(string[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Set the page margins to 0 doc.PageSettings.SetMargins(0); //Get the folder where the images are stored DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images"); //Iterate through the files in the folder foreach (FileInfo file in folder.GetFiles()) { //Load a particular image Image image = Image.FromFile(file.FullName); //Get the image width and height float width = image.PhysicalDimension.Width; float height = image.PhysicalDimension.Height; //Add a page that has the same size as the image PdfPageBase page = doc.Pages.Add(new SizeF(width, height)); //Create a PdfImage object based on the image PdfImage pdfImage = PdfImage.FromImage(image); //Draw image at (0, 0) of the page page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height); } //Save to file doc.SaveToFile("CombinaImagesToPdf.pdf"); doc.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.