Windows Forms: How to Convert Image to Pdf in C#

This post shows you How to Convert image to PDF using PdfSharp in C# Windows Forms Application.

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.

Creating 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.

Right-clicking on your project, then select Manage Nuget Packages=>Search 'pdfsharp'=>download and install it.

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);
                    PdfDocument pdf = new PdfDocument();
                    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);
                    XGraphics g = XGraphics.FromPdfPage(pdf.Pages[0]);
                    XImage img = XImage.FromFile(files[i]);
                    if (true)
                    {
                        size = new XSize(img.PixelWidth, img.PixelHeight);
                        page.Height = size.Height;
                        page.Width = size.Width;
                    }
                    g.DrawImage(img, 0, 0);
                    img.Dispose();
                    g.Dispose();
                    pdf.Save(fileName);
                    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);
                    var page = new PdfPage();
                    page.Size = PageSize.A4;
                    pdf.Pages.Add(page);
                    XGraphics g = XGraphics.FromPdfPage(pdf.Pages[i]);
                    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;
                    }
                    g.DrawImage(img, 0, 0);
                    img.Dispose();
                    g.Dispose();
                }
                FileInfo fi = new FileInfo(files[0]);
                string fileName = fi.FullName.Replace(fi.Extension, ".pdf");
                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#.