DEV Community

Jeremy K.
Jeremy K.

Posted on

Merge Multiple Images into a Single PDF in C#

In daily development, it is often necessary to merge multiple images (such as JPG, PNG, BMP, etc.) into a single PDF document for easy storage and sharing. This article will introduce how to implement this function using C# in conjunction with the Spire.PDF for .NET library, which provides concise APIs for quick PDF operations without relying on Adobe Acrobat.


I. Preparation

Spire.PDF for .NET is a professional PDF processing library that supports creating, editing, and converting PDF documents. It also offers rich image processing capabilities, allowing easy insertion of images into PDF pages.

Installation Steps:
It is recommended to install via the NuGet Package Manager:

  • In Visual Studio, right-click on the project and select "Manage NuGet Packages"
  • Search for "Spire.PDF" and install it
  • After installation, reference the namespaces: using Spire.Pdf; and using Spire.Pdf.Graphics;

II. Core Implementation Steps

Functional Requirement

Merge all images (supporting formats like JPG, PNG, BMP, etc.) in a specified folder into a single PDF in sequence, with each image occupying one page and the page size adapting to the image dimensions.

C# Code Example

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace ConvertMultipleImagesIntoPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            // Set page margins to 0
            pdf.PageSettings.SetMargins(0);

            // Get the folder where images are stored
            DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");

            // Traverse images
            foreach (FileInfo file in folder.GetFiles())
            {
                Image image = Image.FromFile(file.FullName);

                // Get image dimensions
                float width = image.PhysicalDimension.Width;
                float height = image.PhysicalDimension.Height;

                // Add a PDF page with the same size as the image
                PdfPageBase page = pdf.Pages.Add(new SizeF(width, height));

                // Draw the image onto the page
                PdfImage pdfImage = PdfImage.FromImage(image);
                page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
            }

            // Save the PDF document
            pdf.SaveToFile("CombinaImagesToPdf.pdf");
            pdf.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation

  1. Parameter Configuration: Specify the path to the image folder, which can be modified according to actual needs.
  2. PDF Page Creation: Create a PDF page with exactly the same dimensions as the image (ensuring the page size fits the image without stretching or cropping).
  3. Image Drawing: page.Canvas.DrawImage() draws the image starting from the top-left corner (0,0) of the page, with dimensions consistent with the original image.
  4. Resource Release: Dispose() manually releases the resources occupied by the PdfDocument object.

III. Advanced Tips

1. Fixing PDF Page Size

If all pages need to use a fixed size (e.g., A4), you can modify the page creation logic:

// Create an A4-sized page (210mm × 297mm)
PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4);
Enter fullscreen mode Exit fullscreen mode

2. Scaling Images to Fit the Page

If the image size exceeds the page, it can be automatically scaled:

// Calculate the scaling ratio (to ensure the image is fully displayed within the page)
float scaleX = page.Canvas.ClientSize.Width / pdfImage.Width;
float scaleY = page.Canvas.ClientSize.Height / pdfImage.Height;
float scale = Math.Min(scaleX, scaleY);

// Draw with proportional scaling
page.Canvas.DrawImage(pdfImage, x, y, pdfImage.Width * scale, pdfImage.Height * scale);
Enter fullscreen mode Exit fullscreen mode

Conclusion: With the Spire.PDF for .NET library, the image-to-PDF function can be implemented with simple code, which is more concise and user-friendly compared to traditional solutions (System.Drawing + GDI+). This method is suitable for scenarios such as batch processing of images, generating electronic photo albums, archiving scanned documents, etc., and can be extended with more features (such as adding page numbers, watermarks, etc.) according to actual needs.

Top comments (0)