如何將圖片添加到 PDF
將圖像嵌入到 PDF 中意味著將圖像直接放置在 PDF 文件內,確保文件是自包含的,並且不依賴於外部資源。 這使得PDF即使在沒有網絡連接或外部文件的情況下也能無縫顯示圖像。
IronPDF 能夠將 HTML 字串、文件和網頁 URL 渲染成 PDF。 利用這種方法,可以將圖像嵌入到HTML中,然後轉換成PDF文件。
開始使用 IronPDF!
立即在您的專案中使用IronPDF,並享受免費試用。
如何將圖片添加到 PDF
- 下載 IronPDF C# 庫
- 準備要嵌入的圖像文件
- 使用
img
在 HTML 中嵌入圖像的 `` 標籤
- 使用将 HTML 渲染为 PDF
將HTML渲染為PDF
方法 - 使用 Base64 編碼嵌入圖像
在PDF中嵌入圖片示例
img> 標籤,然後將 HTML 轉換成 PDF。imgRenderHtmlAsPdf
方法將 HTML 轉換為 PDF。 如果您有現有的PDF文件,您可以使用其中一种方法将图像盖章到PDF文件上。圖像加蓋器或 HTML 加蓋器教程.
:path=/static-assets/pdf/content-code-examples/how-to/add-images-to-pdfs-embed-image.cs
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
string html = @"<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>";
// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
// Export PDF
pdf.SaveAs("embedImage.pdf");
Imports IronPdf
Private renderer As New ChromePdfRenderer()
Private html As String = "<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>"
' Render HTML to PDF
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
' Export PDF
pdf.SaveAs("embedImage.pdf")
嵌入 Base64 示例
要在HTML中使用base64嵌入圖片,您必須首先通過讀取圖片文件或通過網絡請求獲得圖片的二進制數據。使用Microsoft .NET中的Convert.ToBase64String
方法將二進制數據轉換為base64。在base64數據之前,使用"data:image/svg+xml;base64,"構建HTML中的圖片標籤。 您可能已經注意到,在base64數據之前已指定圖像類型。 訪問MDN 網頁文檔上的圖像格式有關圖像格式類型的更多資訊。
:path=/static-assets/pdf/content-code-examples/how-to/add-images-to-pdfs-base64-image.cs
using IronPdf;
using System;
using System.IO;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Import image file binary data
byte[] binaryData = File.ReadAllBytes("ironpdf-logo-text-dotnet.svg");
// Convert the binary data to base 64
string imgDataUri = Convert.ToBase64String(binaryData);
// Embed in HTML
string html = $"<img src='data:image/svg+xml;base64,{imgDataUri}'>";
// Convert HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
// Export the PDF
pdf.SaveAs("embedImageBase64.pdf");
Imports IronPdf
Imports System
Imports System.IO
Private renderer As New ChromePdfRenderer()
' Import image file binary data
Private binaryData() As Byte = File.ReadAllBytes("ironpdf-logo-text-dotnet.svg")
' Convert the binary data to base 64
Private imgDataUri As String = Convert.ToBase64String(binaryData)
' Embed in HTML
Private html As String = $"<img src='data:image/svg+xml;base64,{imgDataUri}'>"
' Convert HTML to PDF
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
' Export the PDF
pdf.SaveAs("embedImageBase64.pdf")