How to Convert Image to Pdf in C#

By FoxLearn 7/18/2024 7:55:53 AM   5.32K
To convert an image to a PDF using PdfSharp in a C# Windows Forms Application, you'll need to follow these steps.

If you have many image files, you need to convert to a pdf file or multiple pdf files, the following article will guide you on how to do it.

How to Convert Image to Pdf in C#

First, You need create a simple Windows Forms application allows you to select image files, then convert image to pdf file in c#.

convert image to pdf c#

If you want to convert multiple images to single pdf file, you should checked single file.

You'll need to install the PdfSharp library via NuGet Package Manager by right-clicking on your project, then select Manage Nuget Packages=>Search 'pdfsharp'=>download and install it.

pdfsharp

You can also, Install PdfSharp via NuGet Package Manager by opening NuGet Package Manager Console and run the following command

Install-Package PdfSharp

PDFsharp is the Open Source .NET library that easily creates and handles PDF documents on the fly from any .NET language. The same drawing routines can be used to create PDF documents, draw on the screen, or send output to any printer.

Adding a click event handler to the Open file button allows you to select image files.

private void btnOpenFile_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "JPEG|*.jpg", Multiselect = true })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
            listBox.Items.AddRange(ofd.FileNames);
    }
}

Dragging a BackgroundWorker from your visual studio toolbox to your form designer, then add the DoWork event handler to your BackgroundWorker.

Convert image to pdf using pdfsharp c#

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        List<string> files = (e.Argument as List<string>);
        int index = 1;
        if (!chkSingleFile.Checked)
        {
            XSize size = new XSize(0, 0);
            if (!backgroundWorker.CancellationPending)
            {
                for (int i = 0; i < files.Count; i++)
                {
                    backgroundWorker.ReportProgress(index++ * 100 / files.Count);
                    // Create a new PDF document
                    PdfDocument pdf = new PdfDocument();
                    // Add a page to the document
                    var page = new PdfPage();
                    page.Size = PageSize.A4;
                    FileInfo fi = new FileInfo(files[i]);
                    string fileName = fi.FullName.Replace(fi.Extension, ".pdf");
                    pdf.Pages.Add(page);
                    // Get the XGraphics object for drawing
                    XGraphics g = XGraphics.FromPdfPage(pdf.Pages[0]);
                    // Load the image
                    XImage img = XImage.FromFile(files[i]);
                    if (true)
                    {
                        size = new XSize(img.PixelWidth, img.PixelHeight);
                        page.Height = size.Height;
                        page.Width = size.Width;
                    }
                    // Draw the image on the PDF page
                    g.DrawImage(img, 0, 0);
                    img.Dispose();
                    g.Dispose();
                    // Save the PDF document
                    pdf.Save(fileName);
                    // Close the document
                    pdf.Close();
                }
            }
        }
        else
        {
            //convert multiple images to pdf c#
            if (!backgroundWorker.CancellationPending)
            {
                PdfDocument pdf = new PdfDocument();
                XSize size = new XSize(0, 0);
                for (int i = 0; i < files.Count; i++)
                {
                    backgroundWorker.ReportProgress(index++ * 100 / files.Count);
                    // Add a page to the document
                    var page = new PdfPage();
                    page.Size = PageSize.A4;
                    pdf.Pages.Add(page);
                    // Get the XGraphics object for drawing
                    XGraphics g = XGraphics.FromPdfPage(pdf.Pages[i]);
                    // Load the image
                    XImage img = XImage.FromFile(files[i]);
                    if (true)
                    {
                        size = new XSize(img.PixelWidth, img.PixelHeight);
                        page.Height = size.Height - 320;
                        page.Width = size.Width - 230;
                    }
                    // Draw the image on the PDF page
                    g.DrawImage(img, 0, 0);
                    img.Dispose();
                    g.Dispose();
                }
                FileInfo fi = new FileInfo(files[0]);
                string fileName = fi.FullName.Replace(fi.Extension, ".pdf");
                // Save the PDF document
                pdf.Save(fileName);
                pdf.Close();
            }
        }
    }
    catch (Exception ex)
    {
        backgroundWorker.CancelAsync();
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

and don't forget the WorkerReportsProgress, WorkerSupportsCancellation to True.

Using BackgroundWorker allows you to process data in a separate thread from the main thread.

Adding a ProgressChanged event handler to your BackgroundWorker allows you to show progress percentage.

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    lblStatus.Text = $"{e.ProgressPercentage}%";
}

Adding a RunWorkerCompleter event handler allows you to update data when processing is complete.

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    lblStatus.Text = "Completed !";
}

Finally, Add a click event handler to the Convert button allows you to initialize your data and run your BackgroundWorker.

private void btnConvert_Click(object sender, EventArgs e)
{
    List<string> files = new List<string>();
    foreach (string file in listBox.Items)
        files.Add(file);
    backgroundWorker.RunWorkerAsync(files);
}

And don't forget to include the below namespace in your form.

using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;

Pdfsharp is a free library that makes it easy convert image to pdf in c#.