跳過到頁腳內容
使用IRONPDF

C#將圖像添加到PDF(開發者教程)

From a developer's perspective, programmatically adding images to PDF documents is a challenging task due to the variety of image formats and their complexity to manipulate. Therefore, the IronPDF C# library is recommended to add images to the PDF document programmatically. Let's explore what IronPDF is and how to use it effectively.

IronPDF: C# PDF Library

The IronPDF C# library is a PDF library written in C# and targeting the PDF object model. This library provides the developer with a way to create, edit, and save PDF files without the need to tightly maintain relevance to specific APIs such as Adobe's Acrobat. The IronPDF C# library can be used when you don't want to use Adobe Acrobat or another individual piece of software.

This library assists developers with plenty of tools for creating, editing PDF files with C#, and saving PDF files and features that other .NET PDF libraries do not offer. Many developers prefer the IronPDF C# library because it provides everything they are looking for in a PDF library on Windows, Linux, and macOS platforms, and at no cost whatsoever! IronPDF constantly adds features and extends its services to make it the best utility for your PDF needs. The library excels beyond the bare-bones requirements for those who need to browse, search, find, extract data from PDF files or create PDF files. Let's take a look at how the IronPDF is used to add images to a PDF document.

Create or Open C# Project

To add images to a PDF document, the latest version of Visual Studio is recommended for creating a C# project for a smooth experience.

  • Open Visual Studio.

How to Add Images in PDF using C#, Figure 1: Visual Studio starting up UI Visual Studio starting up UI

  • Click on the "Create a New Project" button.
  • Select "C# Console Application" from the Project templates and click on the Next button. You can choose a platform according to your needs.

How to Add Images in PDF using C#, Figure 2: Create a Console Application in Visual Studio Create a Console Application in Visual Studio

  • Next, give a name to your project and click on the Next button.
  • Choose Target .NET Framework >= .NET Core 3.1 version and click on the Create button.

By following the above steps, you will be able to create a new C# project easily. You can use an already existing C# project. Just open the project and install the IronPDF library.

Install the IronPDF Library

The IronPDF library can be installed in multiple ways.

  • Using NuGet Package Manager
  • Using Package Manager Console

Using NuGet Package Manager

To install the library using NuGet Package Manager, follow the steps below:

  • Go to Tools > NuGet Package Manager > Manage NuGet Package for Solution from the main menu options.

How to Add Images in PDF using C#, Figure 3: Navigate to NuGet Package Manager Navigate to NuGet Package Manager

  • This will open the NuGet Package Manager window. Go to the browse tab and search for IronPDF. Select the IronPDF library and click on the "Install" button.

How to Add Images in PDF using C#, Figure 4: Install the IronPdf package from the NuGet Package Manager Install the IronPdf package from the NuGet Package Manager

Using Package Manager Console

Below are the steps to install the IronPDF library using the Console.

  • Go to the Package Manager Console (usually located at the bottom of Visual Studio).
  • Write the following command to start the installation of the IronPDF library.
Install-Package IronPdf

It will start the installation, and you will be able to see the progress of the installation. After installation, you will be able to use the IronPDF library in your project very quickly.

How to Add Images in PDF using C#, Figure 5:


The library has been installed, and now it's time to write code for adding images to the PDF document. Starting with importing the IronPDF namespace. So, write the following line in your code file:

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

Adding Bitmaps and Images to the PDF Document

There are multiple ways to add images to PDF documents using IronPDF: use a direct image file, convert images to bytes, or use System.Drawing.Bitmap. Furthermore, the IronPDF library supports multiple image formats.

Let's take a look:

using IronPdf;
using System.IO;
using System.Drawing;

class PDFImageAdder
{
    /* This method demonstrates how to convert an image file to a PDF document in C# */
    static void Main(string[] args)
    {
        // Initialize IronPdf Renderer
        var renderer = new IronPdf.ChromePdfRenderer();

        // Read the PNG image file into binary format
        var pngBinaryData = File.ReadAllBytes("embed_me.png");

        // Convert image binary data to base64 for embedding in HTML
        var ImgDataURI = "data:image/png;base64," + Convert.ToBase64String(pngBinaryData);

        // Embed the image as a base64 data URI in an HTML <img> tag
        var ImgHtml = $"<img src='{ImgDataURI}'>";

        // Render the HTML as a PDF document
        using var pdfdoc = renderer.RenderHtmlAsPdf(ImgHtml);

        // Save the rendered PDF document
        pdfdoc.SaveAs("embedded_example_1.pdf");
    }
}
using IronPdf;
using System.IO;
using System.Drawing;

class PDFImageAdder
{
    /* This method demonstrates how to convert an image file to a PDF document in C# */
    static void Main(string[] args)
    {
        // Initialize IronPdf Renderer
        var renderer = new IronPdf.ChromePdfRenderer();

        // Read the PNG image file into binary format
        var pngBinaryData = File.ReadAllBytes("embed_me.png");

        // Convert image binary data to base64 for embedding in HTML
        var ImgDataURI = "data:image/png;base64," + Convert.ToBase64String(pngBinaryData);

        // Embed the image as a base64 data URI in an HTML <img> tag
        var ImgHtml = $"<img src='{ImgDataURI}'>";

        // Render the HTML as a PDF document
        using var pdfdoc = renderer.RenderHtmlAsPdf(ImgHtml);

        // Save the rendered PDF document
        pdfdoc.SaveAs("embedded_example_1.pdf");
    }
}
Imports IronPdf
Imports System.IO
Imports System.Drawing

Friend Class PDFImageAdder
	' This method demonstrates how to convert an image file to a PDF document in C# 
	Shared Sub Main(ByVal args() As String)
		' Initialize IronPdf Renderer
		Dim renderer = New IronPdf.ChromePdfRenderer()

		' Read the PNG image file into binary format
		Dim pngBinaryData = File.ReadAllBytes("embed_me.png")

		' Convert image binary data to base64 for embedding in HTML
		Dim ImgDataURI = "data:image/png;base64," & Convert.ToBase64String(pngBinaryData)

		' Embed the image as a base64 data URI in an HTML <img> tag
		Dim ImgHtml = $"<img src='{ImgDataURI}'>"

		' Render the HTML as a PDF document
		Dim pdfdoc = renderer.RenderHtmlAsPdf(ImgHtml)

		' Save the rendered PDF document
		pdfdoc.SaveAs("embedded_example_1.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

This program will load the image first. The ReadAllBytes function converts the image into bytes format in the above code. After that, the image data will be encoded into base64 and placed into an HTML <img> tag as a string. After that, the HTML string will be rendered to a PDF by using the RenderHtmlAsPdf method function. It will create a PDF page in the PDF document.

The next example will show how to use a Bitmap image in the PDF document. IronPDF has a useful method to embed a System.Drawing.Image in an HTML document, which may then be rendered as a PDF. Visit the following ImageUtilities API to understand more about it. The following code will show how it works:

using IronPdf;
using System.Drawing;

class PDFImageAdder
{
    static void Main(string[] args)
    {
        // Initialize IronPdf Renderer
        var renderer = new IronPdf.ChromePdfRenderer();

        // Create a Bitmap image
        Bitmap MyImage = new Bitmap("Path-to-Your-Image");

        // Convert the Bitmap image to a Data URI
        string DataURI = IronPdf.Util.ImageToDataUri(MyImage);

        // Embed the image as a Data URI in an HTML <img> tag
        var ImgHtml = $"<img src='{DataURI}'>";

        // Render the HTML to PDF
        using var pdfdoc2 = renderer.RenderHtmlAsPdf(ImgHtml);

        // Save the PDF document
        pdfdoc2.SaveAs("embedded_example_2.pdf");
    }
}
using IronPdf;
using System.Drawing;

class PDFImageAdder
{
    static void Main(string[] args)
    {
        // Initialize IronPdf Renderer
        var renderer = new IronPdf.ChromePdfRenderer();

        // Create a Bitmap image
        Bitmap MyImage = new Bitmap("Path-to-Your-Image");

        // Convert the Bitmap image to a Data URI
        string DataURI = IronPdf.Util.ImageToDataUri(MyImage);

        // Embed the image as a Data URI in an HTML <img> tag
        var ImgHtml = $"<img src='{DataURI}'>";

        // Render the HTML to PDF
        using var pdfdoc2 = renderer.RenderHtmlAsPdf(ImgHtml);

        // Save the PDF document
        pdfdoc2.SaveAs("embedded_example_2.pdf");
    }
}
Imports IronPdf
Imports System.Drawing

Friend Class PDFImageAdder
	Shared Sub Main(ByVal args() As String)
		' Initialize IronPdf Renderer
		Dim renderer = New IronPdf.ChromePdfRenderer()

		' Create a Bitmap image
		Dim MyImage As New Bitmap("Path-to-Your-Image")

		' Convert the Bitmap image to a Data URI
		Dim DataURI As String = IronPdf.Util.ImageToDataUri(MyImage)

		' Embed the image as a Data URI in an HTML <img> tag
		Dim ImgHtml = $"<img src='{DataURI}'>"

		' Render the HTML to PDF
		Dim pdfdoc2 = renderer.RenderHtmlAsPdf(ImgHtml)

		' Save the PDF document
		pdfdoc2.SaveAs("embedded_example_2.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

In the above code, the ImageToDataUri function is used to convert an image into a URI format. The image is then drawn in the PDF document using the RenderHtmlAsPdf function. This applies to multiple images.

Additionally, IronPDF is also capable of rendering charts in PDFs, adding barcodes to PDF documents, enhancing PDF security with passwords and watermarking PDF files, and even handling PDF forms programmatically.

Licensing

IronPDF is an excellent PDF library that assists you in creating and customizing PDF files, and it is available to purchase today. However, IronPDF is entirely free for development purposes. You can also activate the free trial version for production without any payment details. After purchasing IronPDF, Iron Software makes you a fantastic offer to purchase five Iron Software packages for the price of just two. Yes! You heard right — you can purchase a suite of five Iron Software products for the price of just two. Buy it now! Visit the IronPDF licensing page for more details.

常見問題解答

如何使用 C# 為 PDF 新增圖片?

您可以使用 C# 將圖像新增至 PDF 中,方法是將圖像轉換為 base64 格式,然後將其嵌入到 HTML 中。 related to 如何使用 C# 為 PDF 新增圖片?使用標籤,並使用 IronPDF 的RenderHtmlAsPdf方法將 HTML 轉換為 PDF。

如何設定一個用於向 PDF 新增圖像的 C# 項目?

要設定一個用於向 PDF 新增映像的 C# 項目,請開啟 Visual Studio,建立一個新的 C# 控制台應用程序,並確保您的專案面向 .NET Framework 3.1 或更高版本。透過 NuGet 套件管理器或套件管理器控制台安裝 IronPDF 庫。

如何在 C# 中將影像轉換為 base64 格式以便嵌入 PDF?

在 C# 中,你可以透過將映像檔讀取到位元組數組中,然後使用Convert.ToBase64String將其轉換為 Base64 字串。這個 Base64 字串可以嵌入到 HTML 中。 related to 如何在 C# 中將影像轉換為 base64 格式以便嵌入 PDF?使用 IronPDF 進行 PDF 轉換的標籤。

PDF檔案支援嵌入哪些圖像格式?

IronPDF 支援多種影像格式,可讓您在 PDF 文件中嵌入各種類型的影像,包括 JPEG、PNG 和 BMP。

如何使用 C# 將點陣圖影像嵌入 PDF 中?

若要使用 C# 將點陣圖影像嵌入 PDF,請使用ImageToDataUri函數將點陣圖轉換為資料 URI,然後將其嵌入到 HTML 中。 related to 如何使用 C# 將點陣圖影像嵌入 PDF 中?標籤,並使用 IronPDF 的RenderHtmlAsPdf方法將其渲染為 PDF。

如何在嵌入圖片的同時增強PDF的安全性?

IronPDF 提供多種增強 PDF 安全性的功能,例如新增密碼和權限。使用者可以在 PDF 建立過程中設定安全選項,同時實現嵌入影像的功能。

我可以在PDF檔案中新增圖表、條碼以及圖片嗎?

是的,除了圖片之外,IronPDF 還允許您在 PDF 文件中添加圖表和條碼。這些元素可以使用 HTML 和 CSS 建立和渲染,然後使用 IronPDF 轉換為 PDF 檔案。

IronPDF有哪些授權許可選項?

IronPDF 提供免費試用版供開發者使用,並提供經濟實惠的授權選項以滿足更廣泛的應用需求。更多資訊請造訪 IronPDF 許可頁面。

如何使用軟體包管理器控制台安裝 IronPDF?

若要使用軟體套件管理器控制台安裝 IronPDF,請使用指令Install-Package IronPdf

IronPDF 與 .NET 10 相容嗎?

是的-IronPDF 完全相容於 .NET 10,以及更早的版本,包括 .NET 9、8、7、6、.NET Core、.NET Standard 和 .NET Framework。

Curtis Chau
技術作家

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

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