跳過到頁腳內容
使用IRONPDF

使用IronPDF創建Azure PDF生成器 (.NET 10指南)

將 IronPDF 的專業渲染引擎與 Azure 靈活的雲端基礎架構結合,即可輕鬆產生 Azure PDF 檔案。 本指南將向您展示如何建置、部署和調整一個可用於生產的 PDF 產生器,該產生器可以處理從 HTML 轉換到複雜文件操作的所有操作。

建立一個可靠的雲端 PDF 生成器面臨著獨特的挑戰。 由於沙箱限制、記憶體限制和分散式系統複雜性等因素,許多開發人員難以找到可用於生產環境的解決方案。 這就是AzureIronPDF能夠完美配合的地方——IronPDF 提供專業的PDF 生成功能,可以隨著工作負載的增加而擴展,同時保持基本功能。

無論您是產生發票、報告,還是將 Web 內容轉換為 PDF,本指南都會向您展示如何建立可靠的 Azure PDF 產生器。 您將負責從簡單的HTML 轉換為複雜的文件操作的所有工作,同時也要兼顧效能和成本。

立即開始免費試用 IronPDF ,並跟著教學建立您的雲端 PDF 解決方案。

優秀的 Azure PDF 產生器應該具備哪些特色?

並非所有PDF解決方案都能在雲端環境中運作良好。 一個可用於生產環境的 Azure PDF 產生器,除了基本的文件建立功能外,還必須滿足關鍵要求。 了解 Azure Functions 部署選項是成功的關鍵。

為什麼效能對雲端 PDF 生成至關重要?

效能和可擴展性決定了解決方案的成敗。 您的生成器必須能夠處理並發請求而不會出現瓶頸,在高峰期自動擴展,並能對複雜文件保持一致的回應時間。 選擇一個專為雲端環境而建置、了解無伺服器架構細微差別的程式庫。

您應該考慮哪些 Azure 特有的限制?

Azure平台有一些特殊需要考慮的因素。 應用程式服務沙盒限制了 Win32/圖形 API——使用桌面圖形堆疊的函式庫可能會失敗。 消費計畫中的記憶體限制會導致處理較大文件時發生故障。 分散式特性需要高效率的無狀態操作。 如需 Azure 部署故障排除的詳細步驟,請參閱完整的故障排除文件

哪些企業功能是不可或缺的?

企業應用需要的不只是HTML轉換。 現代 PDF 產生器必須支援 JavaScript 渲染,處理複雜的 CSS,並提供加密和數位簽章等安全功能。 IronPDF 透過其基於 Chrome 的渲染引擎解決了這些問題,使其非常適合 Azure 部署。

Azure 應用程式服務和 Azure 函數有什麼不同?

Azure 應用程式服務和 Azure 函數都託管雲端應用程序,但用途不同。 選擇合適的方案會影響您的架構、成本模型和部署方法。

如何選擇 Azure 應用程式服務?

Azure 應用程式服務為 Web 應用、REST API 和行動後端提供完全託管服務。 它提供持久資源,支援長時間運行的進程,並包含內建的擴充、部署槽位和 CI/CD 整合。 這些特性使其成為持續運行應用程式的理想選擇。

如何判斷 Azure Functions 何時是更好的選擇?

Azure Functions為事件驅動型、短生命週期任務提供無伺服器運算。 函數僅在觸發時運行(例如 HTTP 請求、定時器或訊息佇列觸發),您只需為執行時間付費。它們非常適合後台作業、資料處理、自動化腳本和微服務,無需持續執行主機。

用於產生 PDF 的 Azure 託管選項
特點 應用程式服務 Azure Functions
計費模式 每月固定金額 每次執行
閒置成本 始終計費。 怠速時為零
冷啟動風險 極簡主義 是的(消費計劃)
運行時間過長的PDF文件 支援 逾時限制適用
客製化容器 支援 僅限高級/專用

如何在 Azure Functions 中安裝 IronPDF?

在 Azure Functions 中設定 IronPDF 需要選擇正確的套件。 該程式庫提供適用於 Windows 和 Linux 環境的選項。 選擇合適的軟體包可以確保最佳效能並避免相容性問題。

應該安裝哪個 IronPDF 軟體包?

對於基於 Windows 的 Azure Functions,請使用NuGet上提供的標準 IronPDF 套件。 對於 Linux 容器,請使用 IronPdf.Linux 和 run-from-package 部署,以加快冷啟動速度。

# NuGet Package Manager (Windows / 應用程式服務)
Install-Package IronPdf

# .NET CLI (cross-platform)
dotnet add package IronPdf
# NuGet Package Manager (Windows / 應用程式服務)
Install-Package IronPdf

# .NET CLI (cross-platform)
dotnet add package IronPdf
SHELL
# Linux / container deployments
Install-Package IronPdf.Linux

# .NET CLI alternative
dotnet add package IronPdf.Linux
# Linux / container deployments
Install-Package IronPdf.Linux

# .NET CLI alternative
dotnet add package IronPdf.Linux
SHELL

如何為 Azure Functions 配置 IronPDF?

以下是一個完整的 Azure 函數,它使用頂層語句為 .NET 10 正確配置,用於處理 PDF 產生:

using IronPdf;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using System.Net;

// Configure IronPDF once at startup
License.LicenseKey = Environment.GetEnvironmentVariable("IronPdfLicenseKey") ?? string.Empty;
Installation.LinuxAndDockerDependenciesAutoConfig = true;
Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
Installation.CustomDeploymentDirectory = "/tmp";

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .Build();

host.Run();

// Azure Function class
public class PdfGeneratorFunction
{
    private readonly ILogger _logger;

    public PdfGeneratorFunction(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger<PdfGeneratorFunction>();
    }

    [Function("GeneratePdf")]
    public async Task<HttpResponseData> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "generate-pdf")] HttpRequestData req)
    {
        string htmlContent = await req.ReadAsStringAsync() ?? string.Empty;
        var response = req.CreateResponse(HttpStatusCode.OK);

        if (string.IsNullOrWhiteSpace(htmlContent))
        {
            response.StatusCode = HttpStatusCode.BadRequest;
            await response.WriteStringAsync("HTML content is required.");
            return response;
        }

        try
        {
            var renderer = new ChromePdfRenderer
            {
                RenderingOptions = new ChromePdfRenderOptions
                {
                    MarginTop = 10,
                    MarginBottom = 10,
                    MarginLeft = 10,
                    MarginRight = 10,
                    EnableJavaScript = true
                }
            };

            using var pdf = renderer.RenderHtmlAsPdf(htmlContent);
            response.Headers.Add("Content-Type", "application/pdf");
            await response.WriteBytesAsync(pdf.BinaryData);
            _logger.LogInformation("Generated PDF with {PageCount} pages.", pdf.PageCount);
            return response;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error generating PDF.");
            response.StatusCode = HttpStatusCode.InternalServerError;
            await response.WriteStringAsync($"PDF generation failed: {ex.Message}");
            return response;
        }
    }
}
using IronPdf;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using System.Net;

// Configure IronPDF once at startup
License.LicenseKey = Environment.GetEnvironmentVariable("IronPdfLicenseKey") ?? string.Empty;
Installation.LinuxAndDockerDependenciesAutoConfig = true;
Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
Installation.CustomDeploymentDirectory = "/tmp";

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .Build();

host.Run();

// Azure Function class
public class PdfGeneratorFunction
{
    private readonly ILogger _logger;

    public PdfGeneratorFunction(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger<PdfGeneratorFunction>();
    }

    [Function("GeneratePdf")]
    public async Task<HttpResponseData> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "generate-pdf")] HttpRequestData req)
    {
        string htmlContent = await req.ReadAsStringAsync() ?? string.Empty;
        var response = req.CreateResponse(HttpStatusCode.OK);

        if (string.IsNullOrWhiteSpace(htmlContent))
        {
            response.StatusCode = HttpStatusCode.BadRequest;
            await response.WriteStringAsync("HTML content is required.");
            return response;
        }

        try
        {
            var renderer = new ChromePdfRenderer
            {
                RenderingOptions = new ChromePdfRenderOptions
                {
                    MarginTop = 10,
                    MarginBottom = 10,
                    MarginLeft = 10,
                    MarginRight = 10,
                    EnableJavaScript = true
                }
            };

            using var pdf = renderer.RenderHtmlAsPdf(htmlContent);
            response.Headers.Add("Content-Type", "application/pdf");
            await response.WriteBytesAsync(pdf.BinaryData);
            _logger.LogInformation("Generated PDF with {PageCount} pages.", pdf.PageCount);
            return response;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error generating PDF.");
            response.StatusCode = HttpStatusCode.InternalServerError;
            await response.WriteStringAsync($"PDF generation failed: {ex.Message}");
            return response;
        }
    }
}
Imports IronPdf
Imports Microsoft.Azure.Functions.Worker
Imports Microsoft.Azure.Functions.Worker.Http
Imports Microsoft.Extensions.Logging
Imports System.Net

' Configure IronPDF once at startup
License.LicenseKey = If(Environment.GetEnvironmentVariable("IronPdfLicenseKey"), String.Empty)
Installation.LinuxAndDockerDependenciesAutoConfig = True
Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
Installation.CustomDeploymentDirectory = "/tmp"

Dim host = New HostBuilder() _
    .ConfigureFunctionsWorkerDefaults() _
    .Build()

host.Run()

' Azure Function class
Public Class PdfGeneratorFunction
    Private ReadOnly _logger As ILogger

    Public Sub New(loggerFactory As ILoggerFactory)
        _logger = loggerFactory.CreateLogger(Of PdfGeneratorFunction)()
    End Sub

    <Function("GeneratePdf")>
    Public Async Function Run(
        <HttpTrigger(AuthorizationLevel.Function, "post", Route:="generate-pdf")> req As HttpRequestData) As Task(Of HttpResponseData)

        Dim htmlContent As String = Await req.ReadAsStringAsync() OrElse String.Empty
        Dim response = req.CreateResponse(HttpStatusCode.OK)

        If String.IsNullOrWhiteSpace(htmlContent) Then
            response.StatusCode = HttpStatusCode.BadRequest
            Await response.WriteStringAsync("HTML content is required.")
            Return response
        End If

        Try
            Dim renderer = New ChromePdfRenderer With {
                .RenderingOptions = New ChromePdfRenderOptions With {
                    .MarginTop = 10,
                    .MarginBottom = 10,
                    .MarginLeft = 10,
                    .MarginRight = 10,
                    .EnableJavaScript = True
                }
            }

            Using pdf = renderer.RenderHtmlAsPdf(htmlContent)
                response.Headers.Add("Content-Type", "application/pdf")
                Await response.WriteBytesAsync(pdf.BinaryData)
                _logger.LogInformation("Generated PDF with {PageCount} pages.", pdf.PageCount)
                Return response
            End Using
        Catch ex As Exception
            _logger.LogError(ex, "Error generating PDF.")
            response.StatusCode = HttpStatusCode.InternalServerError
            Await response.WriteStringAsync($"PDF generation failed: {ex.Message}")
            Return response
        End Try
    End Function
End Class
$vbLabelText   $csharpLabel

這些配置設定為何重要?

配置設定可確保 Azure 部署成功。 LinuxAndDockerDependenciesAutoConfig 正確配置 Chrome 依賴項,同時停用 GPU 模式可防止無伺服器渲染問題。 將部署目錄設定為 /tmp 可在受限的 Azure Functions 環境中提供寫入權限,這是"存取被拒絕"錯誤的常見原因。

範例輸出 PDF 文件

由 Azure 函數產生的月度報告 PDF,顯示銷售指標、區域資料表和公司亮點,並附有專業的綠色標題。

產生 PDF 檔案時,應該選擇哪個 Azure 託管層?

與較輕的工作負載相比,使用 IronPDF 產生 PDF 需要更多的計算和圖形支援。 微軟和 IronPDF 都建議避免使用免費、共享和消耗層級,因為有 GDI+ 限制、共享運算限制和記憶體不足等問題。

IronPDF 推薦的 Azure 層級
層級 GDI+ 支援 適用於PDF 注意事項
免費/共享 受限沙盒
消費(功能) 限額 限額 內存容量限制適用
基本/標準 最低推薦
高級/獨立 是的(最好是) 完整功能存取權限

對於高容量工作負載,高級版或獨立版可提供專用計算、VNET 集成,並且沒有冷啟動延遲——所有這些因素都直接提高了 PDF 吞吐量和可靠性。

如何使用 Azure Functions 建置無伺服器 PDF API?

使用 Azure Functions 建置無伺服器 PDF API 可實現自動擴充、按需付費定價和極少的基礎架構管理。 以下函數接受具有可選安全性設定的 JSON 請求,並傳回 PDF 位元組流。

如何建構生產環境的 PDF API?

using IronPdf;
using IronPdf.Editing;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using System.Net;
using System.Text.Json;

public class PdfApiFunction
{
    private static readonly ChromePdfRenderer Renderer = new ChromePdfRenderer
    {
        RenderingOptions = new ChromePdfRenderOptions
        {
            PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
            PrintHtmlBackgrounds = true,
            CreatePdfFormsFromHtml = true,
            CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
        }
    };

    [Function("ConvertUrlToPdf")]
    public async Task<HttpResponseData> ConvertUrl(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
    {
        var body = await req.ReadAsStringAsync() ?? "{}";
        var request = JsonSerializer.Deserialize<ConvertUrlRequest>(body);

        if (string.IsNullOrEmpty(request?.Url))
        {
            var bad = req.CreateResponse(HttpStatusCode.BadRequest);
            await bad.WriteStringAsync("URL is required.");
            return bad;
        }

        using var pdf = Renderer.RenderUrlAsPdf(request.Url);

        if (request.AddWatermark)
        {
            pdf.ApplyWatermark(
                "<h2>CONFIDENTIAL</h2>",
                30,
                VerticalAlignment.Middle,
                HorizontalAlignment.Center);
        }

        if (request.ProtectWithPassword && !string.IsNullOrEmpty(request.Password))
        {
            pdf.SecuritySettings.UserPassword = request.Password;
            pdf.SecuritySettings.AllowUserCopyPasteContent = false;
        }

        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "application/pdf");
        await response.WriteBytesAsync(pdf.BinaryData);
        return response;
    }
}

public class ConvertUrlRequest
{
    public string Url { get; set; } = string.Empty;
    public bool AddWatermark { get; set; }
    public bool ProtectWithPassword { get; set; }
    public string Password { get; set; } = string.Empty;
}
using IronPdf;
using IronPdf.Editing;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using System.Net;
using System.Text.Json;

public class PdfApiFunction
{
    private static readonly ChromePdfRenderer Renderer = new ChromePdfRenderer
    {
        RenderingOptions = new ChromePdfRenderOptions
        {
            PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
            PrintHtmlBackgrounds = true,
            CreatePdfFormsFromHtml = true,
            CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
        }
    };

    [Function("ConvertUrlToPdf")]
    public async Task<HttpResponseData> ConvertUrl(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
    {
        var body = await req.ReadAsStringAsync() ?? "{}";
        var request = JsonSerializer.Deserialize<ConvertUrlRequest>(body);

        if (string.IsNullOrEmpty(request?.Url))
        {
            var bad = req.CreateResponse(HttpStatusCode.BadRequest);
            await bad.WriteStringAsync("URL is required.");
            return bad;
        }

        using var pdf = Renderer.RenderUrlAsPdf(request.Url);

        if (request.AddWatermark)
        {
            pdf.ApplyWatermark(
                "<h2>CONFIDENTIAL</h2>",
                30,
                VerticalAlignment.Middle,
                HorizontalAlignment.Center);
        }

        if (request.ProtectWithPassword && !string.IsNullOrEmpty(request.Password))
        {
            pdf.SecuritySettings.UserPassword = request.Password;
            pdf.SecuritySettings.AllowUserCopyPasteContent = false;
        }

        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "application/pdf");
        await response.WriteBytesAsync(pdf.BinaryData);
        return response;
    }
}

public class ConvertUrlRequest
{
    public string Url { get; set; } = string.Empty;
    public bool AddWatermark { get; set; }
    public bool ProtectWithPassword { get; set; }
    public string Password { get; set; } = string.Empty;
}
Imports IronPdf
Imports IronPdf.Editing
Imports Microsoft.Azure.Functions.Worker
Imports Microsoft.Azure.Functions.Worker.Http
Imports System.Net
Imports System.Text.Json

Public Class PdfApiFunction
    Private Shared ReadOnly Renderer As New ChromePdfRenderer With {
        .RenderingOptions = New ChromePdfRenderOptions With {
            .PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
            .PrintHtmlBackgrounds = True,
            .CreatePdfFormsFromHtml = True,
            .CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
        }
    }

    <Function("ConvertUrlToPdf")>
    Public Async Function ConvertUrl(
        <HttpTrigger(AuthorizationLevel.Function, "post")> req As HttpRequestData) As Task(Of HttpResponseData)

        Dim body As String = Await req.ReadAsStringAsync() ?? "{}"
        Dim request As ConvertUrlRequest = JsonSerializer.Deserialize(Of ConvertUrlRequest)(body)

        If String.IsNullOrEmpty(request?.Url) Then
            Dim bad As HttpResponseData = req.CreateResponse(HttpStatusCode.BadRequest)
            Await bad.WriteStringAsync("URL is required.")
            Return bad
        End If

        Using pdf = Renderer.RenderUrlAsPdf(request.Url)
            If request.AddWatermark Then
                pdf.ApplyWatermark(
                    "<h2>CONFIDENTIAL</h2>",
                    30,
                    VerticalAlignment.Middle,
                    HorizontalAlignment.Center)
            End If

            If request.ProtectWithPassword AndAlso Not String.IsNullOrEmpty(request.Password) Then
                pdf.SecuritySettings.UserPassword = request.Password
                pdf.SecuritySettings.AllowUserCopyPasteContent = False
            End If

            Dim response As HttpResponseData = req.CreateResponse(HttpStatusCode.OK)
            response.Headers.Add("Content-Type", "application/pdf")
            Await response.WriteBytesAsync(pdf.BinaryData)
            Return response
        End Using
    End Function
End Class

Public Class ConvertUrlRequest
    Public Property Url As String = String.Empty
    Public Property AddWatermark As Boolean
    Public Property ProtectWithPassword As Boolean
    Public Property Password As String = String.Empty
End Class
$vbLabelText   $csharpLabel

這種結構既能提供靈活性,又能保持徹底分離。 此函數接受 JSON 請求,對其進行錯誤處理,並傳回具有可選安全性設定的 PDF 檔案。 您可以新增浮水印、實施密碼保護和套用數位簽章

生產環境中產生 PDF 的最佳實務是什麼?

生產環境 PDF 產生需要格外關注效能、可靠性和資源管理。 這些最佳實務可確保在實際條件下處理並發請求時達到最佳效能。

如何管理記憶體和資源?

當請求並發時,記憶體管理變得至關重要。 請務必使用 using 語句釋放 PDF 物件。 對於大型文檔,採用串流輸出而不是將整個 PDF 載入到記憶體中。 實施請求限流以防止流量高峰期間記憶體耗盡。

using IronPdf;
using Microsoft.Extensions.Logging;

public static class PdfProductionService
{
    // Limit concurrent PDF operations to avoid memory exhaustion
    private static readonly SemaphoreSlim Throttle = new SemaphoreSlim(5);

    public static async Task<byte[]> GeneratePdfAsync(string html, ILogger log)
    {
        await Throttle.WaitAsync();
        try
        {
            using var renderer = new ChromePdfRenderer
            {
                RenderingOptions = new ChromePdfRenderOptions
                {
                    Timeout = 60,
                    UseMarginsOnHeaderAndFooter = UseMargins.無ne
                }
            };

            renderer.RenderingOptions.WaitFor.RenderDelay(1000);
            using var pdf = renderer.RenderHtmlAsPdf(html);

            log.LogInformation(
                "PDF generated: {Pages} pages, {Bytes} bytes",
                pdf.PageCount,
                pdf.BinaryData.Length);

            return pdf.BinaryData;
        }
        finally
        {
            Throttle.Release();
        }
    }
}
using IronPdf;
using Microsoft.Extensions.Logging;

public static class PdfProductionService
{
    // Limit concurrent PDF operations to avoid memory exhaustion
    private static readonly SemaphoreSlim Throttle = new SemaphoreSlim(5);

    public static async Task<byte[]> GeneratePdfAsync(string html, ILogger log)
    {
        await Throttle.WaitAsync();
        try
        {
            using var renderer = new ChromePdfRenderer
            {
                RenderingOptions = new ChromePdfRenderOptions
                {
                    Timeout = 60,
                    UseMarginsOnHeaderAndFooter = UseMargins.無ne
                }
            };

            renderer.RenderingOptions.WaitFor.RenderDelay(1000);
            using var pdf = renderer.RenderHtmlAsPdf(html);

            log.LogInformation(
                "PDF generated: {Pages} pages, {Bytes} bytes",
                pdf.PageCount,
                pdf.BinaryData.Length);

            return pdf.BinaryData;
        }
        finally
        {
            Throttle.Release();
        }
    }
}
Imports IronPdf
Imports Microsoft.Extensions.Logging
Imports System.Threading

Public Module PdfProductionService
    ' Limit concurrent PDF operations to avoid memory exhaustion
    Private ReadOnly Throttle As New SemaphoreSlim(5)

    Public Async Function GeneratePdfAsync(html As String, log As ILogger) As Task(Of Byte())
        Await Throttle.WaitAsync()
        Try
            Using renderer As New ChromePdfRenderer With {
                .RenderingOptions = New ChromePdfRenderOptions With {
                    .Timeout = 60,
                    .UseMarginsOnHeaderAndFooter = UseMargins.None
                }
            }
                renderer.RenderingOptions.WaitFor.RenderDelay(1000)
                Using pdf = renderer.RenderHtmlAsPdf(html)
                    log.LogInformation("PDF generated: {Pages} pages, {Bytes} bytes", pdf.PageCount, pdf.BinaryData.Length)
                    Return pdf.BinaryData
                End Using
            End Using
        Finally
            Throttle.Release()
        End Try
    End Function
End Module
$vbLabelText   $csharpLabel

如何監控PDF產生運作狀況?

監控功能可讓您了解 PDF 產生器的運作狀況。 使用 Application Insights 追蹤產生時間、故障率和資源消耗。 設定異常警報,例如錯誤率增加或響應速度下降。 記錄每次請求的詳細信息,以便進行故障排除。

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;

// Track custom metrics using Application Insights
var telemetry = new TelemetryClient(TelemetryConfiguration.CreateDefault());

var sw = System.Diagnostics.Stopwatch.StartNew();
var pdfBytes = await PdfProductionService.GeneratePdfAsync(html, logger);
sw.Stop();

telemetry.TrackMetric("PdfGenerationTimeMs", sw.Elapsed.TotalMilliseconds);
telemetry.TrackMetric("PdfFileSizeBytes", pdfBytes.Length);
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;

// Track custom metrics using Application Insights
var telemetry = new TelemetryClient(TelemetryConfiguration.CreateDefault());

var sw = System.Diagnostics.Stopwatch.StartNew();
var pdfBytes = await PdfProductionService.GeneratePdfAsync(html, logger);
sw.Stop();

telemetry.TrackMetric("PdfGenerationTimeMs", sw.Elapsed.TotalMilliseconds);
telemetry.TrackMetric("PdfFileSizeBytes", pdfBytes.Length);
Imports Microsoft.ApplicationInsights
Imports Microsoft.ApplicationInsights.Extensibility
Imports System.Diagnostics

' Track custom metrics using Application Insights
Dim telemetry As New TelemetryClient(TelemetryConfiguration.CreateDefault())

Dim sw As Stopwatch = Stopwatch.StartNew()
Dim pdfBytes = Await PdfProductionService.GeneratePdfAsync(html, logger)
sw.Stop()

telemetry.TrackMetric("PdfGenerationTimeMs", sw.Elapsed.TotalMilliseconds)
telemetry.TrackMetric("PdfFileSizeBytes", pdfBytes.Length)
$vbLabelText   $csharpLabel

如何在 Azure 中處理進階 PDF 功能?

IronPDF 的高級功能將您的 PDF 生成器擴展到基本創建之外。 Azure 完全支援這些功能,並可實現專業的文件處理工作流程。

如何使用加密和權限控制來保護PDF檔案?

IronPDF 支援密碼保護和權限管理,可實現精細的文件控制。 PDF權限與密碼功能採用AES-256加密:

using IronPdf;

// Load or generate the PDF
using var pdf = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Secure Report</h1>");

// Apply password protection
pdf.SecuritySettings.UserPassword = "view-password";
pdf.SecuritySettings.OwnerPassword = "admin-password";

// Restrict permissions
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;

pdf.SaveAs("azure-secure-report.pdf");
using IronPdf;

// Load or generate the PDF
using var pdf = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Secure Report</h1>");

// Apply password protection
pdf.SecuritySettings.UserPassword = "view-password";
pdf.SecuritySettings.OwnerPassword = "admin-password";

// Restrict permissions
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;

pdf.SaveAs("azure-secure-report.pdf");
Imports IronPdf

' Load or generate the PDF
Using pdf = New ChromePdfRenderer().RenderHtmlAsPdf("<h1>Secure Report</h1>")

    ' Apply password protection
    pdf.SecuritySettings.UserPassword = "view-password"
    pdf.SecuritySettings.OwnerPassword = "admin-password"

    ' Restrict permissions
    pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights
    pdf.SecuritySettings.AllowUserCopyPasteContent = False
    pdf.SecuritySettings.AllowUserAnnotations = False

    pdf.SaveAs("azure-secure-report.pdf")
End Using
$vbLabelText   $csharpLabel

您可以將加密與數位簽章結合起來,以建立不可否認、防篡改的文件。

如何添加頁首、頁尾和浮水印?

在 Azure 中新增帶有動態頁碼和自訂浮水印的頁首和頁尾的方式與在任何其他 .NET 環境中的方式相同:

using IronPdf;

using var pdf = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Report content goes here.</p>");

// Add dynamic header with page numbers
var header = new HtmlHeaderFooter
{
    HtmlFragment = "<div style='text-align:right;font-size:10px'>Page {page} of {total-pages}</div>",
    Height = 15
};
pdf.AddHTMLHeaders(header);

// Apply a draft watermark when needed
pdf.ApplyWatermark(
    "<h1 style='color:gray;opacity:0.3'>DRAFT</h1>",
    45,
    IronPdf.Editing.VerticalAlignment.Middle,
    IronPdf.Editing.HorizontalAlignment.Center);

pdf.SaveAs("report-with-header.pdf");
using IronPdf;

using var pdf = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Report content goes here.</p>");

// Add dynamic header with page numbers
var header = new HtmlHeaderFooter
{
    HtmlFragment = "<div style='text-align:right;font-size:10px'>Page {page} of {total-pages}</div>",
    Height = 15
};
pdf.AddHTMLHeaders(header);

// Apply a draft watermark when needed
pdf.ApplyWatermark(
    "<h1 style='color:gray;opacity:0.3'>DRAFT</h1>",
    45,
    IronPdf.Editing.VerticalAlignment.Middle,
    IronPdf.Editing.HorizontalAlignment.Center);

pdf.SaveAs("report-with-header.pdf");
Imports IronPdf

Using pdf = New ChromePdfRenderer().RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Report content goes here.</p>")
    ' Add dynamic header with page numbers
    Dim header As New HtmlHeaderFooter With {
        .HtmlFragment = "<div style='text-align:right;font-size:10px'>Page {page} of {total-pages}</div>",
        .Height = 15
    }
    pdf.AddHTMLHeaders(header)

    ' Apply a draft watermark when needed
    pdf.ApplyWatermark(
        "<h1 style='color:gray;opacity:0.3'>DRAFT</h1>",
        45,
        IronPdf.Editing.VerticalAlignment.Middle,
        IronPdf.Editing.HorizontalAlignment.Center)

    pdf.SaveAs("report-with-header.pdf")
End Using
$vbLabelText   $csharpLabel

您還可以合併或拆分 PDF提取文字將 PDF 轉換為圖像以及處理PDF 表單

你應該注意哪些常見錯誤?

即使設定正確,將 PDF 產生器部署到 Azure 時也經常會出現一些問題。 了解這些問題可以節省寶貴的故障排除時間。

為什麼會出現"訪問被拒絕"錯誤?

當 IronPDF 無法寫入臨時檔案時,會出現"拒絕存取路徑"錯誤。 設定 Installation.CustomDeploymentDirectory = "/tmp" 以確保寫入權限。 如果使用Run-from-Package部署,請確保應用程式具有單獨的可寫入路徑,因為 /home/site/wwwroot 在該模式下是唯讀的。

如何解決超時和渲染問題?

當渲染複雜文件超過 Azure 的函數逾時時間時,會發生逾時異常。 增加渲染器逾時時間,為 JavaScript 密集型頁面新增渲染延遲,或將大型作業卸載到持久任務佇列。

字體渲染問題表現為字體缺失或錯誤。 使用 Base64 編碼嵌入字體,使用 Azure 原生支援的 Web 安全性字體,或切換到容器部署以實現完全的字體控制。

PDF產生過程中出現記憶體異常的原因是什麼?

PDF 生成過程佔用大量內存,因此會出現內存異常。 常見問題包括大型或併發請求期間出現記憶體不足異常。

最佳實踐包括:

  • 使用 using 語句立即釋放 PdfDocument 對象
  • 使用 SemaphoreSlim 限制並發請求,如生產服務範例所示
  • 對於大型 PDF 文件,請使用基於流的輸出,而不是載入整個位元組數組。
  • 從按需付費套餐升級到高級套餐或專用套餐,即可獲得可預測的記憶體分配。

如何部署和監控 Azure PDF 產生器?

完善的部署策略可確保您的 PDF 產生器保持穩定、可觀察且易於更新。 以下實務適用於 Azure 應用程式服務或 Azure 函數。

您應該遵循哪些部署最佳實務?

*自動化 CI/CD:*使用 Azure DevOps 或 GitHub Actions 實現可重複、可稽核的部署 許可證金鑰:將 IronPDF 許可證儲存在 Azure Key Vault 中,而不是原始碼控製或環境變數中。 可寫入路徑:在應用程式啟動時配置 IronPDF 暫存資料夾(Linux 容器使用 /tmp軟體包選擇:**對於基於容器的部署,請使用 IronPdf.Linux; 使用標準的 IronPdf 套件進行 Windows 應用程式服務

如何設定監控和指標?

Application Insights 可直接與 Azure Functions 和應用程式服務整合。使用 TelemetryClient 追蹤每個 PDF 生成事件的自訂指標:

using Microsoft.ApplicationInsights;

var telemetryClient = new TelemetryClient();
telemetryClient.TrackMetric("PdfGenerationTimeMs", generationTime.TotalMilliseconds);
telemetryClient.TrackMetric("PdfPageCount", pdfPageCount);
telemetryClient.TrackMetric("PdfFileSizeBytes", fileSizeBytes);
using Microsoft.ApplicationInsights;

var telemetryClient = new TelemetryClient();
telemetryClient.TrackMetric("PdfGenerationTimeMs", generationTime.TotalMilliseconds);
telemetryClient.TrackMetric("PdfPageCount", pdfPageCount);
telemetryClient.TrackMetric("PdfFileSizeBytes", fileSizeBytes);
Imports Microsoft.ApplicationInsights

Dim telemetryClient As New TelemetryClient()
telemetryClient.TrackMetric("PdfGenerationTimeMs", generationTime.TotalMilliseconds)
telemetryClient.TrackMetric("PdfPageCount", pdfPageCount)
telemetryClient.TrackMetric("PdfFileSizeBytes", fileSizeBytes)
$vbLabelText   $csharpLabel

在 Azure 入口網站中設定基於指標的警報,以便在產生時間超過可接受閾值或錯誤率飆升時通知您。

如何立即開始使用 Azure PDF 產生功能?

現在,您已經對建置可用於生產的 Azure PDF 產生器有了完整的了解:從選擇正確的 Azure 層級和安裝正確的 NuGet 套件,到配置雲端環境的渲染器,再到新增安全性、監控和資源限制。

Azure 的雲端基礎架構與 IronPDF 基於 Chrome 的渲染引擎結合,創建了一個可隨您的需求擴展的 PDF 平台。 無論您是每小時處理少量文檔還是數千份文檔,此生成器都能保持穩定的效能和可預測的成本。

首先查看IronPDF 功能概述,了解所有可用功能,然後查閱文件以取得 API 詳細資訊。 準備部署時,啟動免費試用許可證即可進行全功能測試,無需支付任何文件費用。 查看許可證選項,選擇適合您生產工作負載的方案。

如需更多文件處理選項,請瀏覽IronPDF NuGet 安裝指南和完整的IronSoftware 產品套件

!{--01001100010010010100001001010010010000010101001001011001010 111110100011101000101010101010001011111010100110101010001000001 010100100101010001000101010001000101111101010111010010010101010 001001000010111110101000001010101000010010000101111101010000010 1001001001111010001000101010101000011010101010001011111010101000101001001001001010101010001010010010010010100001010101010101 010101011000010101000100010101001110010001000101010001000101111101000010010011000100111110100010010011000100111100

常見問題解答

在 Azure 上使用 IronPDF 進行 PDF 生成有什麼優勢?

IronPDF 提供企業級的 PDF 生成功能,無縫集成到 Azure 中,確保可擴展性和可靠性。它克服了雲環境中常見的沙盒限制和內存限制等挑戰。

IronPDF 如何在 Azure 環境中處理內存限制?

IronPDF 優化了在 Azure 的內存約束內運行,利用高效的處理技術生成 PDF,而不超過可用資源。

IronPDF 可以與 Azure Functions 一起使用嗎?

是的,IronPDF 可以集成到 Azure Functions 中以創建無服務器的 PDF 生成解決方案,受益於自動擴展和具有成本效益的執行。

在使用 IronPDF 與 Azure 時涉及哪些安全考慮?

IronPDF 支援安全的 PDF 生成,遵循資料傳輸和存儲的保護最佳實踐,確保符合 Azure 的安全標準。

可以在 Azure App Service 上部署 IronPDF 嗎?

絕對可以,IronPDF 可以部署在 Azure App Service 上,允許開發人員在管理託管環境中利用其特性。

IronPDF 支援在 Azure 中的 PDF 功能自定義嗎?

是的,IronPDF 提供廣泛的 PDF 生成自定義選項,包括佈局、設計和互動性,同時在 Azure 中運行。

IronPDF 如何確保在分佈式 Azure 系統中的高性能?

IronPDF旨在在分散式系統中輕鬆擴展,利用Azure的基礎設施保持高性能和可靠性。

IronPDF是否支援.NET 10用於Azure PDF生成?

是的,IronPDF與Azure環境中的.NET 10完全兼容—包括Functions、App Services和容器部署。它提供開箱即用的無縫支援,無需特殊的變通方法。IronPDF的平台要求明確列出.NET 10為其支援的運行時之一。 (ironpdf.com)

IronPDF支援哪些.NET版本,並且如何利用.NET 10來提高性能?

IronPDF支援廣泛的.NET版本,包括.NET 6、7、8、9和10。使用.NET 10意味著您能夠享受到最新運行時優化、改進的垃圾回收以及Azure中的增強性能—特別是針對無伺服器或容器化PDF生成。ironpdf.com確認在其"C# PDF庫"功能列表中支援.NET 10。

Curtis Chau
技術作家

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

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

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我