푸터 콘텐츠로 바로가기
IRONPDF 사용

How to Convert Image to PDF in C# [Code Example Tutorial]

IronPDF provides a simple, free solution for converting images to PDF in C# through its ImageToPdf method, allowing developers to convert single or multiple images with just a few lines of code and customizable page settings.

Numerous libraries allow C# developers to convert images to PDFs. Finding a free, user-friendly library with good performance can be challenging, as some are paid, complex, or limited in functionality. Among these libraries, IronPDF stands out as a free, efficient, and easy-to-implement C# library. It comes with comprehensive documentation and dedicated support.

IronPDF is a .NET library for generating, reading, editing, and saving PDF files in .NET projects. IronPDF features HTML-to-PDF for .NET 5, Core, Standard & Framework with full HTML-to-PDF support, including CSS3 and JS. The library leverages a Chrome rendering engine to ensure pixel-perfect PDF generation from various sources.

Let's look at how to create a sample project to learn about converting images to PDF. This tutorial will guide you through the installation process, basic image conversion, and advanced features for handling multiple images and different formats.

How Do I Create a Visual Studio Project?

To create a new project, open Microsoft Visual Studio. It's recommended to use the latest version of Visual Studio. The steps for creating a new project may differ between versions, but the remainder should be the same for every version.

  1. Click on Create New Project.
  2. Select Project Template, then select the Console Application template for this demonstration. You can use any template as per your requirement, including ASP.NET Core or Blazor applications.
  3. Click on Next. Name the Project (for example, "ImageToPDFConverter").
  4. Click Next and select the .NET Framework version.
  5. Click the Create button.

The new project will be created as shown below. The project structure will include a Program.cs file where we'll write our image conversion code.

Visual Studio new console application project creation screen showing template selection and configuration options Create a new Console Application in Visual Studio

Which .NET Framework Version Should I Choose?

IronPDF supports a wide range of .NET versions, including .NET Framework 4.6.2+, .NET Core 3.1+, and .NET 5/6/7/8+. For new projects, it's recommended to use the latest LTS (Long Term Support) version of .NET for optimal performance and security updates. The library also works seamlessly on Windows, Linux, and macOS platforms.

Next, install the IronPDF NuGet Package in this project to use its features. The great thing about IronPDF is that it takes the frustration out of generating PDF documents by not relying on proprietary APIs. HTML to PDF rendering renders pixel-perfect PDFs from open standard document types: HTML, JS, CSS, JPG, PNG, GIF, and SVG. In short, it uses the skills that developers already possess.

How Do I Install the IronPDF NuGet Package?

To install the NuGet Package, go to Tools > NuGet Package Manager > Package Manager Console. The following window will appear:

Package Manager Console interface in Visual Studio showing command line interface for NuGet package management Package Manager Console UI

Next, write the following command in the Package Manager Console:

Install-Package IronPdf

Press Enter. The installation process will download IronPDF and its dependencies, including the necessary Chrome rendering engine components.

Package Manager Console showing successful installation of IronPDF package with version information and dependencies Install the IronPdf package in the Package Manager Console

What Are Alternative Installation Methods?

You can also install IronPDF through:

  • NuGet Package Manager UI: Right-click on your project, select "Manage NuGet Packages," search for "IronPdf," and click Install
  • Package Reference: Add <PackageReference Include="IronPdf" Version="*" /> to your .csproj file
  • Direct Download: Download the DLL from the IronPDF website and reference it manually
  • Command Line: Use dotnet add package IronPdf in the terminal

For Azure deployments, you might need additional configuration. Similarly, Docker environments require specific setup steps.

How Do I Convert an Image File to PDF Document?

The next step will show how to convert the following image to PDF. IronPDF makes this process straightforward with its ImageToPdf converter functionality.

What Image Formats Are Supported?

IronPDF supports a wide variety of image formats for PDF conversion:

  • JPEG/JPG: The most common format for photographs
  • PNG: Ideal for images with transparency
  • GIF: Including animated GIFs (first frame used)
  • BMP: Windows bitmap format
  • TIFF: Including multi-page TIFF files
  • SVG: Scalable vector graphics
  • WebP: Modern web image format

Sample bird image showing a colorful bird perched on a branch, demonstrating image quality for PDF conversion The sample image

To use the library, reference the IronPDF library in the program.cs file. Write the following code snippet at the top of the file:

using IronPdf;
using IronPdf.Imaging;
using System.Linq;
using IronPdf;
using IronPdf.Imaging;
using System.Linq;
$vbLabelText   $csharpLabel

Next, write the following code inside the main function. This will convert a JPG file to a PDF file:

public static void Main(string[] args)
{
    // Convert a single image to the PDF document
    PdfDocument doc = ImageToPdfConverter.ImageToPdf(@"D:\Iron Software\ImageToPDF\bird.jpg", IronPdf.Imaging.ImageBehavior.CropPage);

    // Optional: Set document properties
    doc.MetaData.Author = "IronPDF Tutorial";
    doc.MetaData.Title = "Image to PDF Conversion";
    doc.MetaData.Subject = "Converting JPG to PDF";

    // Save the resulting PDF to the specified path
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\bird.pdf");

    Console.WriteLine("PDF created successfully!");
}
public static void Main(string[] args)
{
    // Convert a single image to the PDF document
    PdfDocument doc = ImageToPdfConverter.ImageToPdf(@"D:\Iron Software\ImageToPDF\bird.jpg", IronPdf.Imaging.ImageBehavior.CropPage);

    // Optional: Set document properties
    doc.MetaData.Author = "IronPDF Tutorial";
    doc.MetaData.Title = "Image to PDF Conversion";
    doc.MetaData.Subject = "Converting JPG to PDF";

    // Save the resulting PDF to the specified path
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\bird.pdf");

    Console.WriteLine("PDF created successfully!");
}
$vbLabelText   $csharpLabel

How Does ImageBehavior Affect the Output?

In the above code example, the ImageToPdfConverter class provided by IronPDF is used for image conversion. The ImageToPdf method can be used to create PDF documents from images. It accepts both image files and a System.Drawing object as input.

The static method ImageToPdf converts a single image file to an identical PDF document of matching dimensions. It takes two arguments: Image Path and Image Behavior (how the image will display on paper). The ImageBehavior enum provides several options:

  • CropPage: Sets PDF page size to match image dimensions
  • CenteredOnPage: Centers image on page without resizing
  • FitToPage: Scales image to fit within page margins
  • FitToPageAndMaintainAspectRatio: Scales while preserving aspect ratio

Imaging.ImageBehavior.CropPage will set the paper size equal to the image size. The default page size is A4. You can set it via the following line of code:

ImageToPdfConverter.PaperSize = IronPdf.Rendering.PdfPaperSize.Letter;
ImageToPdfConverter.PaperSize = IronPdf.Rendering.PdfPaperSize.Letter;
$vbLabelText   $csharpLabel

You can also set custom page sizes for specific requirements:

// Set custom page size in millimeters
ImageToPdfConverter.PaperSize = new IronPdf.Rendering.PdfPaperSize(210, 297);
// Set custom page size in millimeters
ImageToPdfConverter.PaperSize = new IronPdf.Rendering.PdfPaperSize(210, 297);
$vbLabelText   $csharpLabel

What Paper Size Options Are Available?

There are multiple page-size options provided, and you can set them as per your requirements. IronPDF supports all standard paper sizes:

  • A Series: A0, A1, A2, A3, A4 (default), A5, A6, A7, A8, A9, A10
  • B Series: B0 through B10
  • US Sizes: Letter, Legal, Ledger, Tabloid, Executive
  • Other: Foolscap, Crown, Demy, Royal, and more

You can also configure page orientation (Portrait or Landscape) and custom margins for your PDFs.

How Do I Convert Multiple Images to a PDF File?

The following example will convert JPG images into a new document. This is particularly useful for creating photo albums, catalogs, or combining scanned documents:

public static void Main(string[] args)
{
    // Enumerate and filter JPG files from the specified directory
    var imageFiles = System.IO.Directory.EnumerateFiles(@"D:\Iron Software\ImageToPDF\")
                                        .Where(f => f.EndsWith(".jpg") || f.EndsWith(".jpeg"));

    // Sort files alphabetically (optional)
    var sortedImageFiles = imageFiles.OrderBy(f => f);

    // Convert the images to a PDF document
    PdfDocument doc = ImageToPdfConverter.ImageToPdf(sortedImageFiles);

    // Add page numbers to each page
    for (int i = 0; i < doc.PageCount; i++)
    {
        doc.AddTextFooter($"Page {i + 1} of {doc.PageCount}", 
                         FontFamily.Arial, 
                         fontSize: 10,
                         y: 25);
    }

    // Save the combined PDF
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\JpgToPDF.pdf");

    Console.WriteLine($"Combined {doc.PageCount} images into a single PDF!");
}
public static void Main(string[] args)
{
    // Enumerate and filter JPG files from the specified directory
    var imageFiles = System.IO.Directory.EnumerateFiles(@"D:\Iron Software\ImageToPDF\")
                                        .Where(f => f.EndsWith(".jpg") || f.EndsWith(".jpeg"));

    // Sort files alphabetically (optional)
    var sortedImageFiles = imageFiles.OrderBy(f => f);

    // Convert the images to a PDF document
    PdfDocument doc = ImageToPdfConverter.ImageToPdf(sortedImageFiles);

    // Add page numbers to each page
    for (int i = 0; i < doc.PageCount; i++)
    {
        doc.AddTextFooter($"Page {i + 1} of {doc.PageCount}", 
                         FontFamily.Arial, 
                         fontSize: 10,
                         y: 25);
    }

    // Save the combined PDF
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\JpgToPDF.pdf");

    Console.WriteLine($"Combined {doc.PageCount} images into a single PDF!");
}
$vbLabelText   $csharpLabel

How Can I Filter Different Image Formats?

In the above code, System.IO.Directory.EnumerateFiles retrieves all files available in the specified folder. The Where clause filters all the JPG images from that folder and stores them in the imageFiles collection. If you have PNG or any other image format, you can just add that to the Where query:

// Filter multiple image formats
var imageFiles = System.IO.Directory.EnumerateFiles(@"D:\Iron Software\ImageToPDF\")
    .Where(f => f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || 
                f.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) ||
                f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
                f.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) ||
                f.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
                f.EndsWith(".tiff", StringComparison.OrdinalIgnoreCase));
// Filter multiple image formats
var imageFiles = System.IO.Directory.EnumerateFiles(@"D:\Iron Software\ImageToPDF\")
    .Where(f => f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || 
                f.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) ||
                f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
                f.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) ||
                f.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
                f.EndsWith(".tiff", StringComparison.OrdinalIgnoreCase));
$vbLabelText   $csharpLabel

You can also use a more concise approach with an array of extensions:

string[] imageExtensions = { ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tiff" };
var imageFiles = System.IO.Directory.EnumerateFiles(@"D:\Iron Software\ImageToPDF\")
    .Where(f => imageExtensions.Any(ext => f.EndsWith(ext, StringComparison.OrdinalIgnoreCase)));
string[] imageExtensions = { ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tiff" };
var imageFiles = System.IO.Directory.EnumerateFiles(@"D:\Iron Software\ImageToPDF\")
    .Where(f => imageExtensions.Any(ext => f.EndsWith(ext, StringComparison.OrdinalIgnoreCase)));
$vbLabelText   $csharpLabel

What Order Will Images Appear in the PDF?

By default, images appear in the order returned by the file system, which may not be alphabetical. To control the order, you can sort the files:

  • Alphabetical: imageFiles.OrderBy(f => f)
  • By Creation Date: imageFiles.OrderBy(f => new FileInfo(f).CreationTime)
  • By File Size: imageFiles.OrderBy(f => new FileInfo(f).Length)
  • Custom Order: Use a custom comparison function

The next line will take all the images and combine them into a single PDF document. Each image becomes a separate page in the PDF.

How Do I Print a PDF File?

The following code snippet will print the document using IronPDF's printing capabilities:

// Print using default printer
doc.Print();

// Print silently (without print dialog)
doc.Print(showPreview: false);

// Print to a specific printer
var printerName = "Microsoft Print to PDF";
doc.Print(printerName);
// Print using default printer
doc.Print();

// Print silently (without print dialog)
doc.Print(showPreview: false);

// Print to a specific printer
var printerName = "Microsoft Print to PDF";
doc.Print(printerName);
$vbLabelText   $csharpLabel

Can I Specify Printer Settings?

The Print method provided by the PdfDocument class will print the document using the default printer. It also provides an option to change the printer name and other settings. For advanced printing options:

// Advanced printing with settings
using System.Drawing.Printing;

var printDocument = doc.GetPrintDocument();
printDocument.PrinterSettings.PrinterName = "Your Printer Name";
printDocument.PrinterSettings.Copies = 2;
printDocument.PrinterSettings.Collate = true;
printDocument.PrinterSettings.PrintRange = PrintRange.SomePages;
printDocument.PrinterSettings.FromPage = 1;
printDocument.PrinterSettings.ToPage = 3;

printDocument.Print();
// Advanced printing with settings
using System.Drawing.Printing;

var printDocument = doc.GetPrintDocument();
printDocument.PrinterSettings.PrinterName = "Your Printer Name";
printDocument.PrinterSettings.Copies = 2;
printDocument.PrinterSettings.Collate = true;
printDocument.PrinterSettings.PrintRange = PrintRange.SomePages;
printDocument.PrinterSettings.FromPage = 1;
printDocument.PrinterSettings.ToPage = 3;

printDocument.Print();
$vbLabelText   $csharpLabel

For more details about printing documents, please visit this PDF printing example. You can also explore network printing options for enterprise environments.

What Are the Key Takeaways?

This tutorial showed a very easy way to convert images into a PDF file with code examples, either converting a single image into a PDF or combining multiple images into a single PDF file. Moreover, it also explained how to print documents with a single line of code.

Key points covered:

  • Installing IronPDF via NuGet Package Manager
  • Converting single images to PDF with custom behavior
  • Batch converting multiple images to one PDF
  • Controlling page size, orientation, and margins
  • Adding metadata and page numbers to PDFs
  • Printing PDFs programmatically with options

Additionally, some important features of IronPDF include:

Where Can I Learn More About IronPDF?

There are multiple useful features provided by IronPDF. Explore these resources:

For specific use cases, explore:

How Much Does IronPDF Cost?

IronPDF is part of the Iron Software suite. The Iron Suite includes additional useful products such as IronXL for Excel operations, IronBarcode for barcode generation, IronOCR for text recognition, and IronWebscraper for web data extraction. You can save up to 250% by purchasing the complete Iron Suite, as you can currently get all five products for the price of just two. Please visit the licensing details page for more information.

IronPDF offers:

  • Free development license for testing
  • Professional licenses starting from $749
  • Royalty-free redistribution options
  • SaaS and OEM licensing available
  • 30-day money-back guarantee
  • Free support and updates for one year

Try IronPDF free for 30 days with a trial license, or explore licensing options for your team.

자주 묻는 질문

C#에서 이미지를 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF의 ImageToPdf 메서드를 사용하여 C#에서 이미지를 PDF로 변환할 수 있습니다. 이 메서드를 사용하면 이미지 경로와 원하는 PDF 출력 설정을 지정할 수 있습니다.

여러 이미지를 하나의 PDF 파일로 변환할 수 있나요?

예, IronPDF를 사용하면 이미지 파일 모음을 제공하는 ImageToPdf 방법을 사용하여 여러 이미지를 단일 PDF 파일로 변환할 수 있습니다.

PDF로 변환할 때 호환되는 이미지 형식은 무엇인가요?

IronPDF는 JPG, PNG, GIF, SVG 등 다양한 이미지 형식을 PDF 문서로 변환하는 기능을 지원합니다.

이미지를 PDF로 변환할 때 페이지 크기는 어떻게 설정하나요?

변환 중 페이지 크기를 설정하려면 ImageToPdfConverter 클래스 내의 PaperSize 속성을 사용하여 Letter 또는 A4와 같은 표준 크기를 선택합니다.

IronPDF로 만든 PDF 문서를 인쇄할 수 있나요?

예, IronPDF에는 기본 또는 지정된 프린터 설정을 사용하여 PDF 문서를 인쇄할 수 있는 PdfDocument 클래스 내에 Print 메서드가 포함되어 있습니다.

IronPDF는 어떤 추가 기능을 제공하나요?

IronPDF는 URL에서 PDF 생성, PDF 암호화 및 암호 해독, PDF 파일 병합, PDF 양식 생성 및 편집과 같은 추가 기능을 제공합니다.

Visual Studio 프로젝트에 IronPDF를 설치하려면 어떻게 하나요?

Visual Studio 프로젝트에 IronPDF를 설치하려면 패키지 관리자 콘솔을 열고 Install-Package IronPdf 명령을 실행합니다.

PDF 생성에 IronPDF를 사용하면 어떤 이점이 있나요?

IronPDF는 독점 API에 의존하지 않고도 PDF 생성을 위한 간단하고 효율적이며 잘 문서화된 API를 제공합니다. 또한 전문적인 지원을 제공하며 다양한 PDF 작업을 효과적으로 처리합니다.

IronPDF는 .NET 10과 호환되며, .NET 10 프로젝트에서 이미지에서 PDF로 변환하는 데 어떻게 사용하나요?

예 - IronPDF는 .NET 10과 완벽하게 호환되며 .NET 10 프로젝트에서 이미지를 PDF로 변환하는 기능을 바로 지원합니다. 이를 사용하려면 .NET 10 프로젝트에 IronPdf NuGet 패키지를 설치한 다음 ImageToPdfConverter.ImageToPdf("path/to/image.png")와 같은 메서드를 호출하여 단일 이미지를 변환하거나 이미지 경로의 IEnumerable을 전달하여 여러 이미지를 변환할 수 있습니다. 또한 ImageBehavior와 같은 옵션을 지정하거나 ChromePdfRenderOptions를 통해 렌더링 옵션을 지정하여 사용자 정의할 수 있습니다. 이는 이전 .NET 버전과 동일하게 작동합니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.