
如何在C# .NET中將JPG轉換為PDF
使用ASP.NET Core和IronPDF建立一個具備生產環境準備的.NET PDF API,集中化您的PDF生成邏輯,通過RESTful端點實現HTML到PDF轉換、合併、水印及動態模板處理,使文件建立在您的應用程式中保持一致。
在使用現代應用程式時,.NET開發者通常需要建立一個集中化的PDF生成服務。無論您是在生成發票、報告、證書還是合約,擁有一個專用的.NET PDF API能夠改善您的PDF生成工作流程。 這有什麼幫助呢?它提供了跨您的桌面和網路應用程式的一致性、可維護性和可擴展性。 管理文件內容、PDF頁面和PDF表單欄位變得簡單直接。
在本教程中,您將學習如何使用ASP.NET Core和IronPDF這個功能強大的.NET PDF程式庫,建立一個具備生產環境準備的PDF API。 我們將建立RESTful端點,從HTML生成PDF,合併文件,新增水印,並在您的Web API處理各種現實世界的PDF情境。
為什麼要建立一個專用的PDF API?

在深入程式碼之前,讓我們理解為什麼要建立一個專用的PDF API是有意義的:
- 中央化邏輯:所有PDF生成邏輯集中在一個地方,簡化維護和更新。
- 微服務架構:非常適合需要PDF功能的面向服務架構中的不同應用程式。
- 性能優化:更容易擴展和優化專用的大型PDF、多頁面及動態資料的服務,使用非同步操作和性能技術。
- 語言無關性:無論編程語言如何,任何客戶端應用程式都可以使用API。
- 一致的輸出:確保您的組織中的所有PDF保持一致的布局、格式和內容。
準備開始建設了嗎? 下載IronPDF的免費試用,然後跟隨本教程,在您的.NET Framework專案中以編程方式建立PDF文件。
IronPDF如何成為完整的.NET PDF程式庫?

IronPDF作為.NET開發者的首選PDF程式庫,以其全面的功能集,使Web API項目中的PDF生成變得簡單且可靠。 基於Chrome渲染引擎構建,確保在幾行程式碼內實現像素級精準的HTML到PDF轉換,同時保留所有樣式、JavaScript執行和響應式設計。
IronPDF理想用於.NET PDF API開發的關鍵能力:
- 基於Chrome的渲染:使用Google Chrome的引擎進行精確的HTML到PDF轉換,完全支持嵌入式圖片和網頁資源。
- 豐富的功能集:可通過數位簽名、PDF表單、註釋、加密、壓縮等進行文件編輯。
- 建立安全的PDF:使用加密、數位簽名和文件保護管理敏感內容。
- 多種輸入格式:使用HTML、URL、圖片和Office文件建立PDF。
- 高級操作:合併頁面、拆分文件、應用水印、建立互動表單,並以程式設計方式操作PDF。
- 跨平台支持:適用於Windows、Linux、macOS、Docker和雲平台。
- 性能優化:非同步操作、高效的記憶體管理和快速的渲染,提供渲染延遲選項。
如何設置您的PDF文件API專案?
讓我們開始建立一個新的ASP.NET Core Web API專案並安裝必要的包。
有什麼先決條件?
- .NET 6.0 SDK or later
- Visual Studio 2022 or Visual Studio Code
- 用於測試您的PDF REST API的Postman或類似API測試工具
我要怎麼建立這個項目?
首先,讓我們建立一個項目來建立我們的PDF生成工具。
dotnet new webapi -n PdfApiService
cd PdfApiService
如何安裝IronPDF?
接下來,通過NuGet將IronPDF新增到您的項目中:
> dotnet add package IronPdf
或者,在Visual Studio中的NuGet包管理控制台中使用:
PM > Install-Package IronPdf
有關高級安裝選項,包括平台特定包、Docker設置或Linux配置,請參閱IronPDF安裝文件。
我應使用什麼專案結構?
良好的C#開發需要保持清晰且結構良好的專案資料夾。 例如:

如何建立您的首個PDF端點?
讓我們建立一個簡單的端點,將HTML轉換為PDF格式。 首先,建立服務介面和實現:
我要怎麼建立PDF服務?
首先,將以下內容新增到您的IPdfService.cs文件中:
public interface IPdfService
{
byte[] GeneratePdfFromHtml(string htmlContent);
byte[] GeneratePdfFromUrl(string url);
}Public Interface IPdfService
Function GeneratePdfFromHtml(htmlContent As String) As Byte()
Function GeneratePdfFromUrl(url As String) As Byte()
End Interface在PdfService.cs文件中,新增此內容:
using IronPdf;
public class PdfService : IPdfService
{
private readonly ChromePdfRenderer _renderer;
public PdfService()
{
_renderer = new ChromePdfRenderer();
// Configure rendering options for optimal PDF generation in .NET
_renderer.RenderingOptions.MarginTop = 20;
_renderer.RenderingOptions.MarginBottom = 20;
_renderer.RenderingOptions.PrintHtmlBackgrounds = true;
}
public byte[] GeneratePdfFromHtml(string htmlContent)
{
// Generate PDF from HTML using the .NET PDF API
var pdf = _renderer.RenderHtmlAsPdf(htmlContent);
return pdf.BinaryData;
}
public byte[] GeneratePdfFromUrl(string url)
{
// Convert URL to PDF in the REST API
var pdf = _renderer.RenderUrlAsPdf(url);
return pdf.BinaryData;
}
}Imports IronPdf
Public Class PdfService
Implements IPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
' Configure rendering options for optimal PDF generation in .NET
_renderer.RenderingOptions.MarginTop = 20
_renderer.RenderingOptions.MarginBottom = 20
_renderer.RenderingOptions.PrintHtmlBackgrounds = True
End Sub
Public Function GeneratePdfFromHtml(htmlContent As String) As Byte()
' Generate PDF from HTML using the .NET PDF API
Dim pdf = _renderer.RenderHtmlAsPdf(htmlContent)
Return pdf.BinaryData
End Function
Public Function GeneratePdfFromUrl(url As String) As Byte()
' Convert URL to PDF in the REST API
Dim pdf = _renderer.RenderUrlAsPdf(url)
Return pdf.BinaryData
End Function
End ClassPdfService負責將HTML轉換為PDF。 使用IronPDF的ChromePdfRenderer,此類設置預設值,如頁邊距和背景渲染,以獲得專業效果。 如需高級渲染配置,請探索IronPDF的渲染選項。
當控制器傳遞原始HTML時,服務將其渲染為高品質PDF並返回字節資料以供下載。 它還使用URL到PDF轉換,將整個網頁直接轉換為PDF。
我要怎麼建立控制器?
現在為您的API建立控制器。 這提供了一個從HTML生成PDF文件的端點,讓您可以下載和保存PDF文件到您的系統。
// Controllers/PdfController.cs
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
private readonly IPdfService _pdfService;
public PdfController(IPdfService pdfService)
{
_pdfService = pdfService;
}
[HttpPost("html-to-pdf")]
public IActionResult ConvertHtmlToPdf([FromBody] HtmlRequest request)
{
try
{
var pdfBytes = _pdfService.GeneratePdfFromHtml(request.HtmlContent);
// Return as downloadable file
return File(pdfBytes, "application/pdf", "document.pdf");
}
catch (Exception ex)
{
return BadRequest($"Error generating PDF: {ex.Message}");
}
}
}Imports Microsoft.AspNetCore.Mvc
<ApiController>
<Route("api/[controller]")>
Public Class PdfController
Inherits ControllerBase
Private ReadOnly _pdfService As IPdfService
Public Sub New(pdfService As IPdfService)
_pdfService = pdfService
End Sub
<HttpPost("html-to-pdf")>
Public Function ConvertHtmlToPdf(<FromBody> request As HtmlRequest) As IActionResult
Try
Dim pdfBytes = _pdfService.GeneratePdfFromHtml(request.HtmlContent)
' Return as downloadable file
Return File(pdfBytes, "application/pdf", "document.pdf")
Catch ex As Exception
Return BadRequest($"Error generating PDF: {ex.Message}")
End Try
End Function
End Class然後,在HtmlRequest.cs文件中,新增此內容:
// Models/HtmlRequest.cs
public class HtmlRequest
{
public string HtmlContent { get; set; }
public string FileName { get; set; } = "document.pdf";
}' Models/HtmlRequest.vb
Public Class HtmlRequest
Public Property HtmlContent As String
Public Property FileName As String = "document.pdf"
End Class這設置了一個API端點,將HTML轉換為可下載的PDF。 當有人將HTML發送至PdfController將轉換委派給服務。
建立完成後,控制器會將PDF作為可下載文件返回。該請求使用HtmlRequest模型,其中包含HTML和可選的檔案名稱。 這使得客戶端可以輕鬆發送HTML並接收精美的PDF。
我要怎麼註冊服務?
更新您的Program.cs來註冊PDF服務:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register PDF service
builder.Services.AddSingleton<IPdfService, PdfService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapControllers();
app.Run();Imports Microsoft.AspNetCore.Builder
Imports Microsoft.Extensions.DependencyInjection
Dim builder = WebApplication.CreateBuilder(args)
builder.Services.AddControllers()
builder.Services.AddEndpointsApiExplorer()
builder.Services.AddSwaggerGen()
' Register PDF service
builder.Services.AddSingleton(Of IPdfService, PdfService)()
Dim app = builder.Build()
If app.Environment.IsDevelopment() Then
app.UseSwagger()
app.UseSwaggerUI()
End If
app.UseHttpsRedirection()
app.MapControllers()
app.Run()如何處理不同的響應型別?
您的API應支援根據客戶端需求不同的PDF返回方式:
[HttpPost("generate")]
public IActionResult GeneratePdf([FromBody] PdfRequest request)
{
var pdfBytes = _pdfService.GeneratePdfFromHtml(request.HtmlContent);
switch (request.ResponseType?.ToLower())
{
case "base64":
return Ok(new
{
data = Convert.ToBase64String(pdfBytes),
filename = request.FileName
});
case "inline":
return File(pdfBytes, "application/pdf");
default: // download
return File(pdfBytes, "application/pdf", request.FileName);
}
}Imports Microsoft.AspNetCore.Mvc
<HttpPost("generate")>
Public Function GeneratePdf(<FromBody> request As PdfRequest) As IActionResult
Dim pdfBytes = _pdfService.GeneratePdfFromHtml(request.HtmlContent)
Select Case request.ResponseType?.ToLower()
Case "base64"
Return Ok(New With {
.data = Convert.ToBase64String(pdfBytes),
.filename = request.FileName
})
Case "inline"
Return File(pdfBytes, "application/pdf")
Case Else ' download
Return File(pdfBytes, "application/pdf", request.FileName)
End Select
End Function這新增了一個靈活的PDF生成端點。 而不是強制下載,GeneratePdf方法讓客戶端選擇如何接收結果:作為下載、在瀏覽器中內嵌或以Base64編碼供API使用。
ResponseType選項。 這讓使用者對PDF交付具有控制權,使API更具多樣性。想要了解如何在不存取文件系統的情況下處理記憶體中的PDF,請參閱IronPDF的記憶體流文件。
當我們運行程式時,將在Swagger上看到此輸出:

如何實現常見的PDF操作?
讓我們擴展我們的服務以處理各種PDF生成場景:
我怎麼將URL轉換為PDF?
[HttpPost("url-to-pdf")]
public async Task<IActionResult> ConvertUrlToPdf([FromBody] UrlRequest request)
{
try
{
var pdfBytes = await Task.Run(() =>
_pdfService.GeneratePdfFromUrl(request.Url));
return File(pdfBytes, "application/pdf",
$"{request.FileName ?? "website"}.pdf");
}
catch (Exception ex)
{
return BadRequest($"Failed to convert URL: {ex.Message}");
}
}
public class UrlRequest
{
public string Url { get; set; }
public string FileName { get; set; }
}Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Mvc
<HttpPost("url-to-pdf")>
Public Async Function ConvertUrlToPdf(<FromBody> request As UrlRequest) As Task(Of IActionResult)
Try
Dim pdfBytes = Await Task.Run(Function() _pdfService.GeneratePdfFromUrl(request.Url))
Return File(pdfBytes, "application/pdf", $"{If(request.FileName, "website")}.pdf")
Catch ex As Exception
Return BadRequest($"Failed to convert URL: {ex.Message}")
End Try
End Function
Public Class UrlRequest
Public Property Url As String
Public Property FileName As String
End Class此端點將URL轉換為可下載的PDF。 當POST請求到達_pdfService在後台將URL轉換為PDF字節,然後返回它們以供下載。 如果轉換失敗,它會以清晰的錯誤消息響應。 對於需要身份驗證的網站,請查看IronPDF的登錄文件。
讓我們嘗試使用URL"https://www.apple.com/nz"並測試POST請求。以下是我們獲得的輸出:
輸出看起來如何?

我要怎麼新增自定義水印?
public byte[] AddWatermarkFromFile(string filePath, string watermarkText)
{
// Load PDF directly from file
var pdf = PdfDocument.FromFile(filePath);
pdf.ApplyWatermark(
$"<h1 style='color:red;font-size:72px;'>{watermarkText}</h1>",
75,
IronPdf.Editing.VerticalAlignment.Middle,
IronPdf.Editing.HorizontalAlignment.Center
);
return pdf.BinaryData;
}Imports IronPdf
Public Function AddWatermarkFromFile(filePath As String, watermarkText As String) As Byte()
' Load PDF directly from file
Dim pdf = PdfDocument.FromFile(filePath)
pdf.ApplyWatermark(
$"<h1 style='color:red;font-size:72px;'>{watermarkText}</h1>",
75,
IronPdf.Editing.VerticalAlignment.Middle,
IronPdf.Editing.HorizontalAlignment.Center
)
Return pdf.BinaryData
End Function這會手動載入本地文件進行測試。 您可以調整這個設置,以便您的PDF API生成PDF後,輕鬆應用自定義水印。 有關高級水印選項,包括圖像水印和自定義定位,請參閱水印指南。
水印輸出的樣子如何?

如何使用模板新增動態資料?
對於實際應用,您經常需要從含有動態資料的模板生成PDF:
[HttpPost("from-template")]
public IActionResult GenerateFromTemplate([FromBody] TemplateRequest request)
{
// Simple template replacement
var html = request.Template;
foreach (var item in request.Data)
{
html = html.Replace($"{{{{{item.Key}}}}}", item.Value);
}
var pdfBytes = _pdfService.GeneratePdfFromHtml(html);
return File(pdfBytes, "application/pdf", request.FileName);
}
public class TemplateRequest
{
public string Template { get; set; }
public Dictionary<string, string> Data { get; set; }
public string FileName { get; set; } = "document.pdf";
}Imports Microsoft.AspNetCore.Mvc
<HttpPost("from-template")>
Public Function GenerateFromTemplate(<FromBody> request As TemplateRequest) As IActionResult
' Simple template replacement
Dim html As String = request.Template
For Each item In request.Data
html = html.Replace($"{{{{{item.Key}}}}}", item.Value)
Next
Dim pdfBytes As Byte() = _pdfService.GeneratePdfFromHtml(html)
Return File(pdfBytes, "application/pdf", request.FileName)
End Function
Public Class TemplateRequest
Public Property Template As String
Public Property Data As Dictionary(Of String, String)
Public Property FileName As String = "document.pdf"
End Class關於具有Razor、Handlebars或其他引擎的高級模板案例,請查看IronPDF的HTML to PDF文件。 您還可以探索CSHTML到PDF轉換用於MVC應用程式,和Razor到PDF用於Blazor應用程式。 有關無頭Razor渲染,請參閱CSHTML無頭指南。
如何優化性能?
在構建生產PDF API時,性能至關重要。 以下是關鍵的優化策略:
為什麼要使用非同步操作?
當您的項目涉及I/O操作時,請使用非同步編碼。 這在您的PDF內容來自外部資源時尤其重要,例如:
- 下載HTML頁面(
RenderUrlAsPdf) - 通過HTTP獲取圖像、CSS或字體
- 讀寫檔案到磁碟或雲儲存
這些操作可以阻止執行緒,但非同步操作可以防止API執行緒閒置等待。 有關詳盡的非同步PDF生成模式,請參考非同步PDF生成指南。
範例:
public async Task<byte[]> GeneratePdfFromHtmlAsync(string htmlContent)
{
return await Task.Run(() =>
{
var pdf = _renderer.RenderHtmlAsPdf(htmlContent);
return pdf.BinaryData;
});
}Imports System.Threading.Tasks
Public Async Function GeneratePdfFromHtmlAsync(htmlContent As String) As Task(Of Byte())
Return Await Task.Run(Function()
Dim pdf = _renderer.RenderHtmlAsPdf(htmlContent)
Return pdf.BinaryData
End Function)
End Function我應配置哪些渲染選項?
配置IronPDF以獲得最佳性能:
_renderer.RenderingOptions.EnableJavaScript = false; // If JS not needed
_renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
_renderer.RenderingOptions.RenderDelay = 0; // Remove if no JS
_renderer.RenderingOptions.Timeout = 30; // Set reasonable timeoutnet有關詳盡的渲染配置選項,包括視窗設置、自定義紙張尺寸以及頁面方向,請查閱渲染選項文件。
如何保護您的PDF API?
安全對於任何生產API都至關重要。 這裡是一個簡單的API金鑰驗證方法:
// Middleware/ApiKeyMiddleware.cs
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private const string ApiKeyHeader = "X-API-Key";
public ApiKeyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue(ApiKeyHeader, out var apiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key required");
return;
}
// Validate API key (in production, check against database)
var validApiKey = context.RequestServices
.GetRequiredService<IConfiguration>()["ApiKey"];
if (apiKey != validApiKey)
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Invalid API Key");
return;
}
await _next(context);
}
}
// In Program.cs
app.UseMiddleware<ApiKeyMiddleware>();Imports Microsoft.AspNetCore.Http
Imports Microsoft.Extensions.Configuration
Imports System.Threading.Tasks
' Middleware/ApiKeyMiddleware.vb
Public Class ApiKeyMiddleware
Private ReadOnly _next As RequestDelegate
Private Const ApiKeyHeader As String = "X-API-Key"
Public Sub New(next As RequestDelegate)
_next = next
End Sub
Public Async Function InvokeAsync(context As HttpContext) As Task
Dim apiKey As String = Nothing
If Not context.Request.Headers.TryGetValue(ApiKeyHeader, apiKey) Then
context.Response.StatusCode = 401
Await context.Response.WriteAsync("API Key required")
Return
End If
' Validate API key (in production, check against database)
Dim validApiKey As String = context.RequestServices.GetRequiredService(Of IConfiguration)()("ApiKey")
If apiKey <> validApiKey Then
context.Response.StatusCode = 403
Await context.Response.WriteAsync("Invalid API Key")
Return
End If
Await _next(context)
End Function
End Class
' In Program.vb
app.UseMiddleware(Of ApiKeyMiddleware)()對於高級身份驗證場景,請考慮:
- JWT 認證 - API驗證的行業標準
- OAuth 2.0 - 用於第三方整合
- Azure AD整合 - 企業級認證
- API速率限制 - 防止濫用並確保公平使用
- HTTP頭 - 用於增強安全性的自定義頭配置
有關PDF特定的安全性,實施密碼保護、數位簽名以及PDF淨化以去除潛在的惡意內容。
如何構建一個現實世界的發票生成API?
讓我們構建一個實用的發票生成端點,用於展示完整的實現。 本範例顯示了一個生產環境的.NET PDF API如何生成具備動態資料的專業發票。
首先,在您的Models資料夾中建立一個新文件。 這裡,我將它稱為Invoice.cs。 然後新增以下程式碼:
public class Invoice
{
public string InvoiceNumber { get; set; }
public DateTime Date { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public List<InvoiceItem> Items { get; set; }
public decimal Tax { get; set; }
}
public class InvoiceItem
{
public string Description { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal Total => Quantity * UnitPrice;
}Public Class Invoice
Public Property InvoiceNumber As String
Public Property [Date] As DateTime
Public Property CustomerName As String
Public Property CustomerAddress As String
Public Property Items As List(Of InvoiceItem)
Public Property Tax As Decimal
End Class
Public Class InvoiceItem
Public Property Description As String
Public Property Quantity As Integer
Public Property UnitPrice As Decimal
Public ReadOnly Property Total As Decimal
Get
Return Quantity * UnitPrice
End Get
End Property
End Class接下來,為發票生成器建立一個新的服務文件。 在您的Services資料夾中,新增如下程式碼。 我建立了一個名為InvoiceService.cs的文件。 此程式碼處理您的發票PDF的樣式和佈局:
public class InvoiceService
{
private readonly ChromePdfRenderer _renderer;
public InvoiceService()
{
_renderer = new ChromePdfRenderer();
_renderer.RenderingOptions.MarginTop = 10;
_renderer.RenderingOptions.MarginBottom = 10;
_renderer.RenderingOptions.PrintHtmlBackgrounds = true;
}
public byte[] GenerateInvoice(Invoice invoice)
{
var html = BuildInvoiceHtml(invoice);
// Add footer with page numbers
_renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
MaxHeight = 15,
HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
DrawDividerLine = true
};
var pdf = _renderer.RenderHtmlAsPdf(html);
return pdf.BinaryData;
}
private string BuildInvoiceHtml(Invoice invoice)
{
var subtotal = invoice.Items.Sum(i => i.Total);
var taxAmount = subtotal * (invoice.Tax / 100);
var total = subtotal + taxAmount;
var itemsHtml = string.Join("", invoice.Items.Select(item =>
$@"<tr>
<td>{item.Description}</td>
<td class='text-center'>{item.Quantity}</td>
<td class='text-right'>${item.UnitPrice:F2}</td>
<td class='text-right'>${item.Total:F2}</td>
</tr>"));
return $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{font-family: Arial, sans-serif;}}
.invoice-header {{background-color: #f8f9fa;
padding: 20px;
margin-bottom: 20px;}}
table {{width: 100%;
border-collapse: collapse;}}
th, td {{padding: 10px;
border-bottom: 1px solid #ddd;}}
th {{background-color: #007bff;
color: white;}}
.text-right {{text-align: right;}}
.text-center {{text-align: center;}}
.total-section {{margin-top: 20px;
text-align: right;}}
</style>
</head>
<body>
<div class='invoice-header'>
<h1>Invoice #{invoice.InvoiceNumber}</h1>
<p>Date: {invoice.Date:yyyy-MM-dd}</p>
</div>
<div>
<h3>Bill To:</h3>
<p>{invoice.CustomerName}<br/>{invoice.CustomerAddress}</p>
</div>
<table>
<thead>
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
{itemsHtml}
</tbody>
</table>
<div class='total-section'>
<p>Subtotal: ${subtotal:F2}</p>
<p>Tax ({invoice.Tax}%): ${taxAmount:F2}</p>
<h3>Total: ${total:F2}</h3>
</div>
</body>
</html>";
}
}
最後,建立一個新的控制器以使用API存取和建立發票:
[ApiController]
[Route("api/[controller]")]
public class InvoiceController : ControllerBase
{
private readonly InvoiceService _invoiceService;
public InvoiceController(InvoiceService invoiceService)
{
_invoiceService = invoiceService;
}
[HttpPost("generate")]
public IActionResult GenerateInvoice([FromBody] Invoice invoice)
{
try
{
var pdfBytes = _invoiceService.GenerateInvoice(invoice);
var fileName = $"Invoice_{invoice.InvoiceNumber}.pdf";
return File(pdfBytes, "application/pdf", fileName);
}
catch (Exception ex)
{
return StatusCode(500, $"Error generating invoice: {ex.Message}");
}
}
}Imports Microsoft.AspNetCore.Mvc
<ApiController>
<Route("api/[controller]")>
Public Class InvoiceController
Inherits ControllerBase
Private ReadOnly _invoiceService As InvoiceService
Public Sub New(invoiceService As InvoiceService)
_invoiceService = invoiceService
End Sub
<HttpPost("generate")>
Public Function GenerateInvoice(<FromBody> invoice As Invoice) As IActionResult
Try
Dim pdfBytes = _invoiceService.GenerateInvoice(invoice)
Dim fileName = $"Invoice_{invoice.InvoiceNumber}.pdf"
Return File(pdfBytes, "application/pdf", fileName)
Catch ex As Exception
Return StatusCode(500, $"Error generating invoice: {ex.Message}")
End Try
End Function
End Class如需高級發票功能,請考慮新增條碼、QR碼、頁碼和自定義頁眉/頁腳。 您還可以實施PDF/A合規以進行長期歸檔,或與電子簽名工作流程整合。
發票輸出的樣子如何?

有哪些容器部署考量?
雖然這個教程重點放在本地開發上,但這裡是對將您的PDF API容器化的一個簡要概述:
我要怎麼建立基本的Dockerfile?
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["PdfApiService.csproj", "."]
RUN dotnet restore
COPY . .
RUN dotnet build -c Release -o /app/build
FROM build AS publish
RUN dotnet publish -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
# IronPDF requires additional dependencies on Linux
RUN apt-get update && apt-get install -y \
libgdiplus \
libc6-dev \
libx11-dev \
&& rm -rf /var/lib/apt/lists/*
ENTRYPOINT ["dotnet", "PdfApiService.dll"]
關於您的.NET PDF API的詳細部署指南,請參閱:
- IronPDF Docker文件 - 完整的容器化指南
- IronPDF Azure部署 - Azure函式和應用服務
- IronPDF AWS部署 - Lambda和EC2部署
- IronPDF Linux設置 - 特定於Linux的配置
- 作為遠程容器運行 - IronPDF引擎容器化
- 本地與遠程引擎 - 部署架構選項
有哪些錯誤處理最佳實踐?
對於具有容錯能力的程式,實施全域錯誤處理器以提供一致的錯誤回應:
// Middleware/ErrorHandlingMiddleware.cs
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ErrorHandlingMiddleware> _logger;
public ErrorHandlingMiddleware(RequestDelegate next, ILogger<ErrorHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred processing request {Path}", context.Request.Path);
await HandleExceptionAsync(context, ex);
}
}
private static async Task HandleExceptionAsync(HttpContext context, Exception ex)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = ex switch
{
ArgumentNullException => 400,
UnauthorizedAccessException => 401,
_ => 500
};
var response = new
{
error = "An error occurred processing your request",
message = ex.Message,
statusCode = context.Response.StatusCode
};
await context.Response.WriteAsync(JsonSerializer.Serialize(response));
}
}' Middleware/ErrorHandlingMiddleware.vb
Public Class ErrorHandlingMiddleware
Private ReadOnly _next As RequestDelegate
Private ReadOnly _logger As ILogger(Of ErrorHandlingMiddleware)
Public Sub New(ByVal [next] As RequestDelegate, ByVal logger As ILogger(Of ErrorHandlingMiddleware))
_next = [next]
_logger = logger
End Sub
Public Async Function InvokeAsync(ByVal context As HttpContext) As Task
Try
Await _next(context)
Catch ex As Exception
_logger.LogError(ex, "An error occurred processing request {Path}", context.Request.Path)
Await HandleExceptionAsync(context, ex)
End Try
End Function
Private Shared Async Function HandleExceptionAsync(ByVal context As HttpContext, ByVal ex As Exception) As Task
context.Response.ContentType = "application/json"
context.Response.StatusCode = If(TypeOf ex Is ArgumentNullException, 400, If(TypeOf ex Is UnauthorizedAccessException, 401, 500))
Dim response = New With {
.error = "An error occurred processing your request",
.message = ex.Message,
.statusCode = context.Response.StatusCode
}
Await context.Response.WriteAsync(JsonSerializer.Serialize(response))
End Function
End Class有關特定IronPDF疑難排解場景,請參考:
準備好構建您的生產.NET PDF API了嗎?
您現在已使用ASP.NET Core和IronPDF構建了一個強大的.NET PDF API,能夠處理各種文件生成情境。 此REST API為您的應用程式提供集中化PDF操作的堅實基礎。
關鍵要點:
- IronPDF使Web API項目中的PDF生成變得簡單,具有基於Chrome的渲染。
- 使用IronPDF的高級編輯工具輕鬆編輯現有的PDF。
- RESTful設計原則確保您的PDF API直觀且易於維護。
- 正確的錯誤處理和安全措施對於生產環境至關重要。
- 通過非同步操作和快取進行性能優化,提高可擴展性。
- 完全支持桌面和網頁應用程式,提供可擴展的文件解決方案。
IronPDF允許開發者高效地建立PDF、保存PDF文件和轉換HTML,使其成為現代.NET Framework應用的重要PDF API。
接下來怎麼辦?
準備好了嗎?在您的生產.NET PDF API中實施IronPDF? 以下是您的下一步行動:
- 開始您的免費試用 - 在您的開發環境中測試IronPDF的全功能。
- 探索高級功能 - 查看數位簽名、PDF表單、PDF/A合規、元資料管理和其他高級PDF功能。
- 自信擴展 - 查看滿足您的生產API需求的授權選項,包括擴展和升級。
今天就構建您的.NET PDF API,並通過IronPDF簡化整個應用程式生態系統中的文件生成!

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.
Related Articles


