跳過到頁腳內容
使用IRONPDF

如何使用C#將圖像轉換為PDF【代碼示例教程】

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 a professional, responsive support team.

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.

Let's take a look at how to create a sample project to learn about converting images to PDF.

Create a Visual Studio Project

To create a new project, open Microsoft Visual Studio. It is 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 as per your requirement.
  3. Click on Next. Name the Project.
  4. Click Next and select the .NET Framework version.
  5. Click the Create button.

The new project will be created as shown below.

How to Convert Image to PDF in C# [Code Example Tutorial], Figure 1: Create a new Console Application in Visual Studio Create a new Console Application in Visual Studio

Next, install the IronPDF NuGet Package in this project to use its features. The interesting thing about IronPDF is that it takes the frustration out of generating PDF documents by not relying on proprietary APIs. HTML to PDF rendering example 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.

Install the IronPDF NuGet Package

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

How to Convert Image to PDF in C# [Code Example Tutorial], Figure 2: Package Manager Console UI Package Manager Console UI

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

Install-Package IronPdf

Press Enter.

How to Convert Image to PDF in C# [Code Example Tutorial], Figure 3: Install the IronPdf package in the Package Manager Console Install the IronPdf package in the Package Manager Console

Convert Image File to PDF Document

The next step will show how to convert the following image to PDF.

Example Image

How to Convert Image to PDF in C# [Code Example Tutorial], Figure 4: The sample image 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;
Imports IronPdf
$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);
    // Save the resulting PDF to the specified path
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\bird.pdf");
}
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);
    // Save the resulting PDF to the specified path
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\bird.pdf");
}
Public Shared Sub Main(ByVal args() As String)
	' Convert a single image to the PDF document
	Dim doc As PdfDocument = ImageToPdfConverter.ImageToPdf("D:\Iron Software\ImageToPDF\bird.jpg", IronPdf.Imaging.ImageBehavior.CropPage)
	' Save the resulting PDF to the specified path
	doc.SaveAs("D:\Iron Software\ImageToPDF\bird.pdf")
End Sub
$vbLabelText   $csharpLabel

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). 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;
ImageToPdfConverter.PaperSize = IronPdf.Rendering.PdfPaperSize.Letter
$vbLabelText   $csharpLabel

There are multiple page-size options provided, and you can set them as per your requirements.

Convert Multiple Images to a PDF File

The following example will convert JPG images into a new document.

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"));
    // Convert the images to a PDF document and save it
    PdfDocument doc = ImageToPdfConverter.ImageToPdf(imageFiles);
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\JpgToPDF.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"));
    // Convert the images to a PDF document and save it
    PdfDocument doc = ImageToPdfConverter.ImageToPdf(imageFiles);
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\JpgToPDF.pdf");
}
Public Shared Sub Main(ByVal args() As String)
	' Enumerate and filter JPG files from the specified directory
	Dim imageFiles = System.IO.Directory.EnumerateFiles("D:\Iron Software\ImageToPDF\").Where(Function(f) f.EndsWith(".jpg") OrElse f.EndsWith(".jpeg"))
	' Convert the images to a PDF document and save it
	Dim doc As PdfDocument = ImageToPdfConverter.ImageToPdf(imageFiles)
	doc.SaveAs("D:\Iron Software\ImageToPDF\JpgToPDF.pdf")
End Sub
$vbLabelText   $csharpLabel

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.

The next line will take all the images and combine them into a single PDF document.

Print PDF File

The following code snippet will print the document:

doc.Print();
doc.Print();
doc.Print()
$vbLabelText   $csharpLabel

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 more details about printing documents, please visit this PDF printing example.

Summary

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.

Additionally, some of the important features of IronPDF include:

There are multiple useful and interesting features provided by IronPDF, please visit this IronPDF homepage for more details.

IronPDF is a part of the Iron Software suite. The Iron Suite includes additional interesting products such as IronXL, IronBarcode, IronOCR, and IronWebscraper, and all of these products are extremely useful. 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 details.

常見問題解答

如何在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 在PdfDocument類別中包含一個Print方法,讓您可以使用預設或指定的印表機設定來列印 PDF 文件。

IronPDF還提供哪些功能?

IronPDF 還提供其他功能,例如從 URL 產生 PDF、加密和解密 PDF、合併 PDF 文件以及建立和編輯 PDF 表單。

如何在 Visual Studio 專案中安裝 IronPDF?

若要在 Visual Studio 專案中安裝 IronPDF,請開啟程式包管理器控制台並執行命令Install-Package IronPdf

使用 IronPDF 產生 PDF 檔案有哪些優勢?

IronPDF 提供了一個簡單、高效且文件齊全的 PDF 生成 API,無需依賴任何專有 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 來轉換多個映像。您也可以透過ChromePdfRenderOptions指定諸如ImageBehavior或渲染選項之類的選項進行自訂。這與先前的 .NET 版本的工作方式完全相同。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。