跳過到頁腳內容
產品比較

APITemplate io和IronPDF對比C# PDF庫

作為C#開發人員,我經常在項目中面臨生成和操作PDF的挑戰。 高效、可靠且易於集成的PDF解決方案是我們領域中的常見痛點。 That's why I decided to explore APITemplate and IronPDF, two popular tools that promise to streamline PDF-related tasks in C# applications.

在本文中,我將分享我對APITemplate和IronPDF的實踐體驗,對比它們的特性、性能和集成能力。 我希望為您提供清晰、無偏見的分析,以幫助您為下一個項目做出明智的決策。 當我第一次接觸APITemplate和IronPDF時,它們在解決C#開發中的PDF相關挑戰方面的潛力讓我很感興趣。 讓我們來分解每個工具提供的功能。

APITemplate

APITemplate io和IronPDF C# PDF庫比較:圖1

APITemplate是一項基於雲的服務,專注於從模板生成PDF和圖像。 它提供了一個API,允許開發人員通過將JSON數據發送到預定義的模板來創建文檔和圖形。 在我的初步測試中,我發現APITemplate使用起來很簡單。 我可以使用他們的網頁界面創建模板,然後使用他們的API從我的C#應用中填充數據。

APITemplate的核心特性

基於模板的生成

APITemplate的核心優勢在於其基於模板的方法。 我可以創建可重用的文檔和圖像模板,這為我節省了大量重複性任務的時間。 它還提供了一個Markdown模板編輯器來生成PDF。 您可以從與Zapier和其他第三方集成的可重用模板生成PDF。

JSON數據集成

JSON數據集成是一個我經常使用的功能。 它提供了以JSON數據填充模板的能力。 這使得我可以輕鬆地與我的C#應用集成,因為我可以將對象序列化為JSON並發送到API。

API控制台

API控制台功能為我節省了大量時間。 通過它,我可以直接從他們的網站預覽和測試API調用,幫助我在將它們實施到C#代碼之前調試和微調我的請求。

可定制的頁眉和頁腳

能夠在我的PDF中添加自定義頁眉和頁腳,這對於創建專業的報告和發票尤為重要。 我可以輕鬆地包含頁碼、日期或公司徽標。

IronPDF

APITemplate io和IronPDF C# PDF庫比較:圖2

IronPDF,另一面,是專門為C#應用中PDF操作而設計的.NET庫。 它提供了一系列廣泛的功能,包括PDF創建、編輯和轉換。 其中一個突出的特點是能夠從HTML生成PDF,這對於基於網絡的應用非常有用。

我第一次使用IronPDF的經驗是通過NuGet安裝,並直接集成到我的C#項目中。 其API集成過程非常順利,意味著我能夠在我的項目中迅速啟用它。我對能夠輕鬆地以編程方式創建PDF感到驚訝,而不用依賴外部服務。

我注意到的關鍵區別是APITemplate在創建預定義模板的文檔方面表現出色,而IronPDF則提供了在C#代碼中自定義PDF操作的更多靈活性。 APITemplate的雲端特性意味著你不需要擔心PDF生成的服務器資源,但它確實需要網絡連接。 IronPDF作為本地庫,雖然可以離線工作,但需要使用你的服務器資源。

IronPDF的核心特性

從HTML創建PDF

IronPDF在從HTML內容生成PDF方面表現出色。 我廣泛使用這個功能來動態創建報告和文檔。 這只需要傳遞HTML字符串或甚至是URL到庫中。 IronPDF對現代網絡標準的廣泛支持意味著我從HTML內容生成的每個PDF都出色地高質量文檔。

PDF操作

這一功能允許我以編程方式編輯現有的PDF。 我可以向PDF文檔中添加文本、圖像或甚至新頁面,這對於更新報告或表單非常有用。

PDF合併和拆分

在處理大型文檔時,我發現這個功能特別有用。 IronPDF makes it easy to combine multiple PDFs into one or split a single PDF into several files.

文本提取

當我需要從PDF中提取文本內容進行分析或索引時,IronPDF的文本提取功能派上了用場。 它可以很好地處理各種PDF佈局,使數據提取變得輕而易舉。

表單填寫

對於涉及自動表單完成的項目,IronPDF的表單填充功能非常有用。 我可以以編程方式填充PDF表單,省去了手動輸入數據的時間。

電子簽名

安全性在我的許多項目中至關重要。 IronPDF允許我為PDF添加電子簽名,提高了文檔的真實性和安全性。

密碼保護

在處理敏感文檔時,我使用IronPDF為PDF添加密碼保護。 這對於確保我的機密信息保持安全非常有幫助。

PDF轉圖像

有時我需要將PDF頁面轉換為圖像以供預覽或縮略圖使用。 IronPDF使這一過程變得簡單,只需要我編寫幾行代碼,並支持多種圖像格式。

跨平台兼容性

作為一名從事跨平台項目的.NET開發人員,我很欣賞IronPDF憑藉其.NET Standard支持而能夠完美運行於不同操作系統之上。

在您的C#項目中設定IronPDF和APITemplate

在C#項目中設置這些工具相當簡單。 根據我的經驗,我將帶您完成IronPDF和APITemplate的設置過程。

IronPDF

在我的C#項目中設置IronPDF,我按照以下步驟進行:

  1. 在Visual Studio中打開我的項目。

  2. 使用NuGet包管理器安裝IronPDF。 我可以選擇使用NuGet包管理器或包管理器控制台。

    1. 在NuGet包管理器中,搜索IronPDF並進行安裝。

    APITemplate io和IronPDF C# PDF庫比較:圖3

    1. 或者,在包管理器控制台中,我運行:
    Install-Package IronPdf

    APITemplate io和IronPDF C# PDF庫比較:圖4

  3. 安裝後,我在C#文件的頂部添加必要的using聲明:

    using IronPdf;
    using IronPdf;
    Imports IronPdf
    $vbLabelText   $csharpLabel
  4. 要激活許可,在應用程序啟動開始處添加這行代碼:

    IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
    IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
    IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE"
    $vbLabelText   $csharpLabel

就這樣! 現在我可以在代碼中開始使用IronPDF。

APITemplate

對於APITemplate,由於是基於網絡的API,設置過程略有不同:

  1. 首先,我在他們的網站上註冊一個APITemplate帳戶。
  2. 註冊後,我前往API部分獲取我的API密鑰。
  3. 在我的C#項目中,我不需要安裝任何特定的包。 我通常使用內置的HttpClient進行API調用。

  4. 我安全地存儲API密鑰。 在開發中,我可能會使用用戶機密:

    dotnet user-secrets set "APITemplate:ApiKey" "YOUR-API-KEY-HERE"
    dotnet user-secrets set "APITemplate:ApiKey" "YOUR-API-KEY-HERE"
    SHELL
  5. 在我的代碼中,我使用API密鑰設置HttpClient:

    using System.Net.Http;
    using System.Net.Http.Headers;
    
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add("X-API-KEY", Configuration["APITemplate:ApiKey"]);
    using System.Net.Http;
    using System.Net.Http.Headers;
    
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add("X-API-KEY", Configuration["APITemplate:ApiKey"]);
    Imports System.Net.Http
    Imports System.Net.Http.Headers
    
    Private client = New HttpClient()
    client.DefaultRequestHeaders.Add("X-API-KEY", Configuration("APITemplate:ApiKey"))
    $vbLabelText   $csharpLabel
  6. 現在我準備好進行APITemplate的API調用。

對於這個項目,我將使用APITemplate的官方示例GitHub項目,該項目已經配置好,您只需添加模板密鑰。 完成這些設置後,我可以在我的C#項目中開始使用IronPDF和APITemplate。 IronPDF在我的應用中本地運行,而APITemplate則需要網絡連接與其服務器通信。

IronPDF與APITemplate的高級功能

作為C#開發人員,我有機會深入探討IronPDF和APITemplate。 讓我們來看看讓我印象深刻的一些高級功能。

IronPDF的高級功能

支持JavaScript的HTML轉PDF

IronPDF的HTML轉PDF功能非常出色。 它不僅能渲染靜態HTML,還能處理JavaScript。 在處理動態網絡內容時,這對我來說是一個改變遊戲規則的功能。

下面是一個我如何使用它的簡單例子:

var Renderer = new ChromePdfRenderer();
string htmlContent = @"
    <html>
    <body>
        <h1>Dynamic Chart</h1>
        <canvas id='myChart'></canvas>
        <script src='https://cdn.jsdelivr.net/npm/chart.js'></script>
        <script>
            var ctx = document.getElementById('myChart').getContext('2d');
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                    datasets: [{
                        label: '# of Votes',
                        data: [12, 19, 3, 5, 2, 3],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        </script>
    </body>
    </html>";
var PDF = Renderer.RenderHtmlAsPdf(htmlContent);
PDF.SaveAs("dynamic_chart.pdf");
var Renderer = new ChromePdfRenderer();
string htmlContent = @"
    <html>
    <body>
        <h1>Dynamic Chart</h1>
        <canvas id='myChart'></canvas>
        <script src='https://cdn.jsdelivr.net/npm/chart.js'></script>
        <script>
            var ctx = document.getElementById('myChart').getContext('2d');
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                    datasets: [{
                        label: '# of Votes',
                        data: [12, 19, 3, 5, 2, 3],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        </script>
    </body>
    </html>";
var PDF = Renderer.RenderHtmlAsPdf(htmlContent);
PDF.SaveAs("dynamic_chart.pdf");
Dim Renderer = New ChromePdfRenderer()
Dim htmlContent As String = "
    <html>
    <body>
        <h1>Dynamic Chart</h1>
        <canvas id='myChart'></canvas>
        <script src='https://cdn.jsdelivr.net/npm/chart.js'></script>
        <script>
            var ctx = document.getElementById('myChart').getContext('2d');
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                    datasets: [{
                        label: '# of Votes',
                        data: [12, 19, 3, 5, 2, 3],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        </script>
    </body>
    </html>"
Dim PDF = Renderer.RenderHtmlAsPdf(htmlContent)
PDF.SaveAs("dynamic_chart.pdf")
$vbLabelText   $csharpLabel

此代碼生成了一個包括動態圖表的PDF,使用的是Chart.js。 JavaScript在PDF創建過程中被執行,結果是一個包含渲染圖表的PDF。 我使用過這個功能創建動態報告,這樣數據經常改變,從而省去了手動更新圖表和圖形的麻煩。

APITemplate io和IronPDF C# PDF庫比較:圖5

可以包括外部腳本,比如這個例子中的Chart.js,這意味著我可以利用強大的JavaScript庫,在我的PDF中創建豐富、動態的內容。 此外,這一功能允許我在HTML中使用CSS和響應式設計技術,以確保生成的PDF在各種設備和打印格式中看來都很不錯。 我甚至使用過媒體查詢來從同一HTML來源創建適合於屏幕查看和打印的PDF。

PDF加密和解密

涉及敏感信息時,安全性在我的很多項目中至關重要。 IronPDF的加密和解密功能在這些情況中不可或缺。

var pdf = PdfDocument.FromFile("input.pdf");
// Set user password (for opening the document)
pdf.Password = "user_password";
// Set owner password (for editing, printing, etc.)
pdf.OwnerPassword = "owner_password";
// Set specific permissions
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserEdits = IronPdf.Security.PdfEditSecurity.NoEdit;
pdf.SaveAs("highly_secured.pdf");
var pdf = PdfDocument.FromFile("input.pdf");
// Set user password (for opening the document)
pdf.Password = "user_password";
// Set owner password (for editing, printing, etc.)
pdf.OwnerPassword = "owner_password";
// Set specific permissions
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserEdits = IronPdf.Security.PdfEditSecurity.NoEdit;
pdf.SaveAs("highly_secured.pdf");
Dim pdf = PdfDocument.FromFile("input.pdf")
' Set user password (for opening the document)
pdf.Password = "user_password"
' Set owner password (for editing, printing, etc.)
pdf.OwnerPassword = "owner_password"
' Set specific permissions
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserEdits = IronPdf.Security.PdfEditSecurity.NoEdit
pdf.SaveAs("highly_secured.pdf")
$vbLabelText   $csharpLabel

APITemplate io和IronPDF C# PDF庫比較:圖6

此代碼不僅使用用戶密碼加密PDF,還設置擁有者密碼並提供逐細的權限控制。 我可以精確地指定用戶可以和不能對PDF進行的操作,例如打印或復製內容。

在解密方面,我經常使用這種方法:

try
{
    var pdf = PdfDocument.FromFile("encrypted.pdf", "user_password");
    pdf.SecuritySettings.RemovePasswordsAndEncryption();
    pdf.SaveAs("decrypted.pdf");
    Console.WriteLine("PDF decrypted successfully!");
}
catch (Exception ex)
{
    Console.WriteLine($"Decryption failed: {ex.Message}");
}
try
{
    var pdf = PdfDocument.FromFile("encrypted.pdf", "user_password");
    pdf.SecuritySettings.RemovePasswordsAndEncryption();
    pdf.SaveAs("decrypted.pdf");
    Console.WriteLine("PDF decrypted successfully!");
}
catch (Exception ex)
{
    Console.WriteLine($"Decryption failed: {ex.Message}");
}
Try
	Dim pdf = PdfDocument.FromFile("encrypted.pdf", "user_password")
	pdf.SecuritySettings.RemovePasswordsAndEncryption()
	pdf.SaveAs("decrypted.pdf")
	Console.WriteLine("PDF decrypted successfully!")
Catch ex As Exception
	Console.WriteLine($"Decryption failed: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

此代碼嘗試使用用戶密碼打開一個加密的PDF,移除所有安全限制,並將其保存為一個新的未加密文件。try-catch塊有助於處理密碼可能不正確的情況。

這些功能我已在多種情景中使用過,比如創建安全的文檔管理系統,對於不同用戶,根據不同的訪問級別提供PDF。 例如,在一個醫療記錄系統中,我確保敏感的患者信息被加密,僅能由授權人員訪問。

PDF壓縮

當處理大量PDF時,文件大小成為關鍵因素。 IronPDF的壓縮功能在管理存儲和帶寬限制方面對我來說非常有幫助。

這是一個我使用壓縮的更高級示例:

using IronPdf;
using System.IO;
using PdfDocument = IronPdf.PdfDocument;

var PDF = PdfDocument.FromFile(@"F:/Test.pdf");
// Compress images
PDF.CompressImages(80); // 80% quality
// Compress fonts
PDF.CompressStructTree();
// Save the compressed PDF
PDF.SaveAs(@"F:/highly_compressed.pdf");
// Compare file sizes
var originalSize = new FileInfo(@"F:/Test.pdf").Length;
var compressedSize = new FileInfo(@"F:/highly_compressed.pdf").Length;
var compressionRatio = (1 - (double)compressedSize / originalSize) * 100;
Console.WriteLine($"Original size: {originalSize / 1024} KB");
Console.WriteLine($"Compressed size: {compressedSize / 1024} KB");
Console.WriteLine($"Compression ratio: {compressionRatio:F2}%");
using IronPdf;
using System.IO;
using PdfDocument = IronPdf.PdfDocument;

var PDF = PdfDocument.FromFile(@"F:/Test.pdf");
// Compress images
PDF.CompressImages(80); // 80% quality
// Compress fonts
PDF.CompressStructTree();
// Save the compressed PDF
PDF.SaveAs(@"F:/highly_compressed.pdf");
// Compare file sizes
var originalSize = new FileInfo(@"F:/Test.pdf").Length;
var compressedSize = new FileInfo(@"F:/highly_compressed.pdf").Length;
var compressionRatio = (1 - (double)compressedSize / originalSize) * 100;
Console.WriteLine($"Original size: {originalSize / 1024} KB");
Console.WriteLine($"Compressed size: {compressedSize / 1024} KB");
Console.WriteLine($"Compression ratio: {compressionRatio:F2}%");
Imports IronPdf
Imports System.IO
Imports PdfDocument = IronPdf.PdfDocument

Private PDF = PdfDocument.FromFile("F:/Test.pdf")
' Compress images
PDF.CompressImages(80) ' 80% quality
' Compress fonts
PDF.CompressStructTree()
' Save the compressed PDF
PDF.SaveAs("F:/highly_compressed.pdf")
' Compare file sizes
Dim originalSize = (New FileInfo("F:/Test.pdf")).Length
Dim compressedSize = (New FileInfo("F:/highly_compressed.pdf")).Length
Dim compressionRatio = (1 - CDbl(compressedSize) / originalSize) * 100
Console.WriteLine($"Original size: {originalSize \ 1024} KB")
Console.WriteLine($"Compressed size: {compressedSize \ 1024} KB")
Console.WriteLine($"Compression ratio: {compressionRatio:F2}%")
$vbLabelText   $csharpLabel

這是結果:

APITemplate io和IronPDF C# PDF庫比較:圖7

我發現這些技術結合起來,在不顯著影響質量的情況下對於減少文件大小效果非常好。

我在不同情境中使用過這個功能:

  1. 郵件附件: 當通過電子郵件發送PDF時,我會壓縮它們以確保它們不超過附件大小限制。
  2. 網絡應用程序: 對於用戶需要下載的PDF,壓縮有助於減少加載時間和帶寬使用。
  3. 歸檔: 在長期存儲大量PDF時,壓縮顯著降低了存儲成本。

在一個項目中,我為一家律師事務所工作了一個文檔管理系統。 他們有數千份PDF格式的案件文件,其中許多是掃描的文檔,文件大小非常大。 通過實施這個壓縮技術,我們將他們的存儲要求降低了超過60%,這在他們的雲存儲賬單中節省了大量成本。

電子簽名

為PDF添加電子簽名是許多業務流程中必須具備的功能,以確保文檔的真實性和防抵賴性。 IronPDF使得這個複雜的任務出人意料地簡單。 這是我實施電子簽名的更詳細示例:

using IronPdf;
using IronPdf.Signing;

var renderer = new ChromePdfRenderer();
var pdf = PdfDocument.FromFile(@"F:/Contract.pdf");
var signature = new IronPdf.Signing.PdfSignature(@"F:/Iron.pfx", "123")
{
    // Step 3. Optional signing options and a handwritten signature graphic
    SigningContact = "support@ironsoftware.com",
    SigningLocation = "New York, USA",
    SigningReason = "Signing PDF"
};
pdf.Sign(signature);
pdf.SaveAs(@"F:/signed.pdf");
using IronPdf;
using IronPdf.Signing;

var renderer = new ChromePdfRenderer();
var pdf = PdfDocument.FromFile(@"F:/Contract.pdf");
var signature = new IronPdf.Signing.PdfSignature(@"F:/Iron.pfx", "123")
{
    // Step 3. Optional signing options and a handwritten signature graphic
    SigningContact = "support@ironsoftware.com",
    SigningLocation = "New York, USA",
    SigningReason = "Signing PDF"
};
pdf.Sign(signature);
pdf.SaveAs(@"F:/signed.pdf");
Imports IronPdf
Imports IronPdf.Signing

Private renderer = New ChromePdfRenderer()
Private pdf = PdfDocument.FromFile("F:/Contract.pdf")
Private signature = New IronPdf.Signing.PdfSignature("F:/Iron.pfx", "123") With {
	.SigningContact = "support@ironsoftware.com",
	.SigningLocation = "New York, USA",
	.SigningReason = "Signing PDF"
}
pdf.Sign(signature)
pdf.SaveAs("F:/signed.pdf")
$vbLabelText   $csharpLabel

我在幾個真實應用中使用過這個功能:

  1. 合同管理系統: 我們為一家需要電子方式寄出和接收合約的公司實施了這項功能。 電子簽名確保了合同的法律有效性。
  2. 醫療紀錄系統: 在一個醫療應用程序中,我們使用電子簽名來允許醫生在病歷和處方上簽字。
  3. 政府文檔處理: 對於某個政府機構,我們實施了一個系統,可以將官方文件進行電子簽名。

PDF分拆和合併

能否分割和合併PDF是一個我在文檔管理系統中經常使用的基本功能。 IronPDF在這些功能的實現上既強大又靈活。 這是PDF拆分和合併的更高級示例:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        // Create first PDF with three pages
        const string html_a = @"
            <h1>Document A</h1>
            <p>This is the first page of Document A.</p>
            <div style='page-break-after: always;'></div>
            <h2>Document A - Page 2</h2>
            <p>This is the second page of Document A.</p>
            <div style='page-break-after: always;'></div>
            <h2>Document A - Page 3</h2>
            <p>This is the third and final page of Document A.</p>";
        // Create second PDF with two pages
        const string html_b = @"
            <h1>Document B</h1>
            <p>Welcome to the first page of Document B.</p>
            <div style='page-break-after: always;'></div>
            <h2>Document B - Page 2</h2>
            <p>This is the second and last page of Document B.</p>";
        // Render HTML to PDF
        var renderer = new ChromePdfRenderer();
        var pdfdoc_a = renderer.RenderHtmlAsPdf(html_a);
        var pdfdoc_b = renderer.RenderHtmlAsPdf(html_b);
        // Merge PDFs
        var merged = PdfDocument.Merge(pdfdoc_a, pdfdoc_b);
        merged.SaveAs(@"F:/IronPdf/MergedDocument.pdf");
        Console.WriteLine("Merged PDF created: MergedDocument.pdf");
        // Load the merged PDF
        var pdf = PdfDocument.FromFile(@"F:/IronPdf/MergedDocument.pdf");
        // Extract the first page
        var firstPage = pdf.CopyPage(0);
        firstPage.SaveAs(@"F:/IronPdf/FirstPageOnly.pdf");
        Console.WriteLine("First page extracted: FirstPageOnly.pdf");
        // Extract pages 2 to 4 (note: index starts at 0)
        var middlePages = pdf.CopyPages(1, 3);
        middlePages.SaveAs(@"F:/IronPdf/Pages2to4.pdf");
        Console.WriteLine("Pages 2 to 4 extracted: Pages2to4.pdf");
        Console.WriteLine("Process completed. Press any key to exit.");
        Console.ReadKey();
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        // Create first PDF with three pages
        const string html_a = @"
            <h1>Document A</h1>
            <p>This is the first page of Document A.</p>
            <div style='page-break-after: always;'></div>
            <h2>Document A - Page 2</h2>
            <p>This is the second page of Document A.</p>
            <div style='page-break-after: always;'></div>
            <h2>Document A - Page 3</h2>
            <p>This is the third and final page of Document A.</p>";
        // Create second PDF with two pages
        const string html_b = @"
            <h1>Document B</h1>
            <p>Welcome to the first page of Document B.</p>
            <div style='page-break-after: always;'></div>
            <h2>Document B - Page 2</h2>
            <p>This is the second and last page of Document B.</p>";
        // Render HTML to PDF
        var renderer = new ChromePdfRenderer();
        var pdfdoc_a = renderer.RenderHtmlAsPdf(html_a);
        var pdfdoc_b = renderer.RenderHtmlAsPdf(html_b);
        // Merge PDFs
        var merged = PdfDocument.Merge(pdfdoc_a, pdfdoc_b);
        merged.SaveAs(@"F:/IronPdf/MergedDocument.pdf");
        Console.WriteLine("Merged PDF created: MergedDocument.pdf");
        // Load the merged PDF
        var pdf = PdfDocument.FromFile(@"F:/IronPdf/MergedDocument.pdf");
        // Extract the first page
        var firstPage = pdf.CopyPage(0);
        firstPage.SaveAs(@"F:/IronPdf/FirstPageOnly.pdf");
        Console.WriteLine("First page extracted: FirstPageOnly.pdf");
        // Extract pages 2 to 4 (note: index starts at 0)
        var middlePages = pdf.CopyPages(1, 3);
        middlePages.SaveAs(@"F:/IronPdf/Pages2to4.pdf");
        Console.WriteLine("Pages 2 to 4 extracted: Pages2to4.pdf");
        Console.WriteLine("Process completed. Press any key to exit.");
        Console.ReadKey();
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create first PDF with three pages
		Const html_a As String = "
            <h1>Document A</h1>
            <p>This is the first page of Document A.</p>
            <div style='page-break-after: always;'></div>
            <h2>Document A - Page 2</h2>
            <p>This is the second page of Document A.</p>
            <div style='page-break-after: always;'></div>
            <h2>Document A - Page 3</h2>
            <p>This is the third and final page of Document A.</p>"
		' Create second PDF with two pages
		Const html_b As String = "
            <h1>Document B</h1>
            <p>Welcome to the first page of Document B.</p>
            <div style='page-break-after: always;'></div>
            <h2>Document B - Page 2</h2>
            <p>This is the second and last page of Document B.</p>"
		' Render HTML to PDF
		Dim renderer = New ChromePdfRenderer()
		Dim pdfdoc_a = renderer.RenderHtmlAsPdf(html_a)
		Dim pdfdoc_b = renderer.RenderHtmlAsPdf(html_b)
		' Merge PDFs
		Dim merged = PdfDocument.Merge(pdfdoc_a, pdfdoc_b)
		merged.SaveAs("F:/IronPdf/MergedDocument.pdf")
		Console.WriteLine("Merged PDF created: MergedDocument.pdf")
		' Load the merged PDF
		Dim pdf = PdfDocument.FromFile("F:/IronPdf/MergedDocument.pdf")
		' Extract the first page
		Dim firstPage = pdf.CopyPage(0)
		firstPage.SaveAs("F:/IronPdf/FirstPageOnly.pdf")
		Console.WriteLine("First page extracted: FirstPageOnly.pdf")
		' Extract pages 2 to 4 (note: index starts at 0)
		Dim middlePages = pdf.CopyPages(1, 3)
		middlePages.SaveAs("F:/IronPdf/Pages2to4.pdf")
		Console.WriteLine("Pages 2 to 4 extracted: Pages2to4.pdf")
		Console.WriteLine("Process completed. Press any key to exit.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

APITemplate io和IronPDF C# PDF庫比較:圖8

這是由代碼生成的合並文檔:

APITemplate io和IronPDF C# PDF庫比較:圖9

表單填寫

自動表格填寫在我的許多項目中已成為巨大的時間節省。 IronPDF允許我以編程方式填充PDF表單,這對於處理大量的表單或創建個性化文檔非常有價值。 這是一個更全面的填表示例:

using IronPdf;
using System;

// Load the combined form
PdfDocument pdf = PdfDocument.FromFile(@"F:/completeForm.pdf");

// Handle radio buttons
var radioForm = pdf.Form.FindFormField("traveltype");
radioForm.Value = "Airplane";

// Handle checkbox
var checkboxForm = pdf.Form.FindFormField("taskCompleted");
checkboxForm.Value = "Yes";

// Handle combobox
var comboboxForm = pdf.Form.FindFormField("priority");
comboboxForm.Value = "Low";

// Print out all the available choices for combobox
foreach (var choice in comboboxForm.Choices)
{
    Console.WriteLine(choice);
}

// Handle text inputs
pdf.Form.FindFormField("firstname").Value = "John";
pdf.Form.FindFormField("lastname").Value = "Smith";

// Handle text area
pdf.Form.FindFormField("address").Value = "Iron Software\r\n205 N. Michigan Ave.";

// Save the edited PDF
pdf.SaveAs(@"F:/completeFormEdited.pdf");
using IronPdf;
using System;

// Load the combined form
PdfDocument pdf = PdfDocument.FromFile(@"F:/completeForm.pdf");

// Handle radio buttons
var radioForm = pdf.Form.FindFormField("traveltype");
radioForm.Value = "Airplane";

// Handle checkbox
var checkboxForm = pdf.Form.FindFormField("taskCompleted");
checkboxForm.Value = "Yes";

// Handle combobox
var comboboxForm = pdf.Form.FindFormField("priority");
comboboxForm.Value = "Low";

// Print out all the available choices for combobox
foreach (var choice in comboboxForm.Choices)
{
    Console.WriteLine(choice);
}

// Handle text inputs
pdf.Form.FindFormField("firstname").Value = "John";
pdf.Form.FindFormField("lastname").Value = "Smith";

// Handle text area
pdf.Form.FindFormField("address").Value = "Iron Software\r\n205 N. Michigan Ave.";

// Save the edited PDF
pdf.SaveAs(@"F:/completeFormEdited.pdf");
Imports Microsoft.VisualBasic
Imports IronPdf
Imports System

' Load the combined form
Private pdf As PdfDocument = PdfDocument.FromFile("F:/completeForm.pdf")

' Handle radio buttons
Private radioForm = pdf.Form.FindFormField("traveltype")
radioForm.Value = "Airplane"

' Handle checkbox
Dim checkboxForm = pdf.Form.FindFormField("taskCompleted")
checkboxForm.Value = "Yes"

' Handle combobox
Dim comboboxForm = pdf.Form.FindFormField("priority")
comboboxForm.Value = "Low"

' Print out all the available choices for combobox
For Each choice In comboboxForm.Choices
	Console.WriteLine(choice)
Next choice

' Handle text inputs
pdf.Form.FindFormField("firstname").Value = "John"
pdf.Form.FindFormField("lastname").Value = "Smith"

' Handle text area
pdf.Form.FindFormField("address").Value = "Iron Software" & vbCrLf & "205 N. Michigan Ave."

' Save the edited PDF
pdf.SaveAs("F:/completeFormEdited.pdf")
$vbLabelText   $csharpLabel

我在幾個真實應用中使用過這個功能:

  1. 人力資源入職系統: 我們創建了一個系統,這個系統根據人力資源數據庫的信息自動填充新員工的文件,節省了大量手動數據輸入的時間。

  2. 保險索賠處理: 對於一家保險公司,我們構建了一個系統,該系統預填充投保人信息的索賠表單,顯著加快了索賠提交過程。

  3. 學校申請系統: 在一個教育項目中,我們實施了一個系統,根據學生數據填寫學校申請表,這使得申請過程對於學生和管理人員都更加方便。

  4. 稅表生成: 對於一家會計事務所,我們創建了一個系統,可以根據客戶的財務數據自動填寫稅表,減少錯誤並在稅季節省時間。

能夠以編程方式填寫表單是自動化許多業務流程的重要因素,帶來了顯著的時間節省和減少手動數據輸入的錯誤。

水印

為PDF添加水印常常是出於品牌、保安或狀態指示的需要。 IronPDF提供了靈活的水印功能,這在許多項目中我發現非常有用。 這是一個我如何使用水印的詳細示例:

using IronPdf;
using IronSoftware.Drawing;

string watermarkHtml = @"
<img style='width: 250px;' src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>";

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>");

// Apply watermark with 45 degrees rotation and 70% opacity
pdf.ApplyWatermark(watermarkHtml, rotation: 30, opacity: 90);
pdf.SaveAs("watermarkOpacity&amp;Rotation.pdf");
using IronPdf;
using IronSoftware.Drawing;

string watermarkHtml = @"
<img style='width: 250px;' src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>";

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>");

// Apply watermark with 45 degrees rotation and 70% opacity
pdf.ApplyWatermark(watermarkHtml, rotation: 30, opacity: 90);
pdf.SaveAs("watermarkOpacity&amp;Rotation.pdf");
Imports IronPdf
Imports IronSoftware.Drawing

Private watermarkHtml As String = "
<img style='width: 250px;' src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>"

Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>")

' Apply watermark with 45 degrees rotation and 70% opacity
pdf.ApplyWatermark(watermarkHtml, rotation:= 30, opacity:= 90)
pdf.SaveAs("watermarkOpacity&amp;Rotation.pdf")
$vbLabelText   $csharpLabel

APITemplate io和IronPDF C# PDF庫比較:圖10

APITemplate的高級功能

動態模板生成

APITemplate的動態模板生成是一個強大的功能,允許使用自定義JSON數據創建高度可定制的文檔。 APITemplate的API支持動態組件。 您可以獲取代碼的PDF和圖像輸出。 在API控制台中,我能夠使用所見即所得編輯器輕鬆生成PDF文檔。

讓我們深入探討我在項目中如何使用這個功能。

using System;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace csharp
{
    class ReturnContent
    {
        public string download_url { get; set; }
        public string status { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var api_key = "a9e4MjA2NTg6MTc3Njk6Uk1ZSzVjTWs1T3d6VE9Mdw=";
            var template_id = "bf077b23b4a407ae";
            var url = $"https://rest.apitemplate.io/v2/create-pdf?template_id={template_id}";
            var data = new
            {
                date = "15/05/2022",
                invoice_no = "435568799",
                sender_address1 = "3244 Jurong Drive",
                sender_address2 = "Falmouth Maine 1703",
                sender_phone = "255-781-6789",
                sender_email = "dev@ironsoftware.com",
                rece_addess1 = "2354 Lakeside Drive",
                rece_addess2 = "New York 234562 ",
                rece_phone = "34333-84-223",
                rece_email = "info@ironsoftware.com",
                items = new[]
                {
                    new { item_name = "Oil", unit = 1, unit_price = 100, total = 100 },
                    new { item_name = "Rice", unit = 2, unit_price = 200, total = 400 },
                    new { item_name = "Orange", unit = 7, unit_price = 20, total = 1400 }
                },
                total = "total",
                footer_email = "info@ironsoftware.com"
            };
            var json_content = JsonSerializer.Serialize(data);
            var buffer = System.Text.Encoding.UTF8.GetBytes(json_content);
            var byteContent = new ByteArrayContent(buffer);
            Console.WriteLine(json_content);
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("X-API-KEY", api_key);
            var response = await client.PostAsync(url, byteContent);
            var ret = await response.Content.ReadAsStringAsync();
            var returnContent = JsonSerializer.Deserialize<ReturnContent>(ret);
            if (returnContent.status == "success")
            {
                Console.WriteLine($"Downloading {returnContent.download_url}...");
                var download_response = await client.GetAsync(returnContent.download_url);
                using (var stream = await download_response.Content.ReadAsStreamAsync())
                {
                    var fileInfo = new FileInfo(@"F:/generated_document.pdf");
                    using (var fileStream = fileInfo.OpenWrite())
                    {
                        await stream.CopyToAsync(fileStream);
                    }
                }
                Console.WriteLine("PDF file has been downloaded and saved as 'generated_document.pdf'");
            }
        }
    }
}
using System;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace csharp
{
    class ReturnContent
    {
        public string download_url { get; set; }
        public string status { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var api_key = "a9e4MjA2NTg6MTc3Njk6Uk1ZSzVjTWs1T3d6VE9Mdw=";
            var template_id = "bf077b23b4a407ae";
            var url = $"https://rest.apitemplate.io/v2/create-pdf?template_id={template_id}";
            var data = new
            {
                date = "15/05/2022",
                invoice_no = "435568799",
                sender_address1 = "3244 Jurong Drive",
                sender_address2 = "Falmouth Maine 1703",
                sender_phone = "255-781-6789",
                sender_email = "dev@ironsoftware.com",
                rece_addess1 = "2354 Lakeside Drive",
                rece_addess2 = "New York 234562 ",
                rece_phone = "34333-84-223",
                rece_email = "info@ironsoftware.com",
                items = new[]
                {
                    new { item_name = "Oil", unit = 1, unit_price = 100, total = 100 },
                    new { item_name = "Rice", unit = 2, unit_price = 200, total = 400 },
                    new { item_name = "Orange", unit = 7, unit_price = 20, total = 1400 }
                },
                total = "total",
                footer_email = "info@ironsoftware.com"
            };
            var json_content = JsonSerializer.Serialize(data);
            var buffer = System.Text.Encoding.UTF8.GetBytes(json_content);
            var byteContent = new ByteArrayContent(buffer);
            Console.WriteLine(json_content);
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("X-API-KEY", api_key);
            var response = await client.PostAsync(url, byteContent);
            var ret = await response.Content.ReadAsStringAsync();
            var returnContent = JsonSerializer.Deserialize<ReturnContent>(ret);
            if (returnContent.status == "success")
            {
                Console.WriteLine($"Downloading {returnContent.download_url}...");
                var download_response = await client.GetAsync(returnContent.download_url);
                using (var stream = await download_response.Content.ReadAsStreamAsync())
                {
                    var fileInfo = new FileInfo(@"F:/generated_document.pdf");
                    using (var fileStream = fileInfo.OpenWrite())
                    {
                        await stream.CopyToAsync(fileStream);
                    }
                }
                Console.WriteLine("PDF file has been downloaded and saved as 'generated_document.pdf'");
            }
        }
    }
}
Imports System
Imports System.IO
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks

Namespace csharp
	Friend Class ReturnContent
		Public Property download_url() As String
		Public Property status() As String
	End Class

	Friend Class Program
		Shared Async Function Main(ByVal args() As String) As Task
			Dim api_key = "a9e4MjA2NTg6MTc3Njk6Uk1ZSzVjTWs1T3d6VE9Mdw="
			Dim template_id = "bf077b23b4a407ae"
			Dim url = $"https://rest.apitemplate.io/v2/create-pdf?template_id={template_id}"
			Dim data = New With {
				Key .date = "15/05/2022",
				Key .invoice_no = "435568799",
				Key .sender_address1 = "3244 Jurong Drive",
				Key .sender_address2 = "Falmouth Maine 1703",
				Key .sender_phone = "255-781-6789",
				Key .sender_email = "dev@ironsoftware.com",
				Key .rece_addess1 = "2354 Lakeside Drive",
				Key .rece_addess2 = "New York 234562 ",
				Key .rece_phone = "34333-84-223",
				Key .rece_email = "info@ironsoftware.com",
				Key .items = {
					New With {
						Key .item_name = "Oil",
						Key .unit = 1,
						Key .unit_price = 100,
						Key .total = 100
					},
					New With {
						Key .item_name = "Rice",
						Key .unit = 2,
						Key .unit_price = 200,
						Key .total = 400
					},
					New With {
						Key .item_name = "Orange",
						Key .unit = 7,
						Key .unit_price = 20,
						Key .total = 1400
					}
				},
				Key .total = "total",
				Key .footer_email = "info@ironsoftware.com"
			}
			Dim json_content = JsonSerializer.Serialize(data)
			Dim buffer = System.Text.Encoding.UTF8.GetBytes(json_content)
			Dim byteContent = New ByteArrayContent(buffer)
			Console.WriteLine(json_content)
			Dim client = New HttpClient()
			client.DefaultRequestHeaders.Add("X-API-KEY", api_key)
			Dim response = Await client.PostAsync(url, byteContent)
			Dim ret = Await response.Content.ReadAsStringAsync()
			Dim returnContent = JsonSerializer.Deserialize(Of ReturnContent)(ret)
			If returnContent.status = "success" Then
				Console.WriteLine($"Downloading {returnContent.download_url}...")
				Dim download_response = Await client.GetAsync(returnContent.download_url)
				Using stream = Await download_response.Content.ReadAsStreamAsync()
					Dim fileInfo As New FileInfo("F:/generated_document.pdf")
					Using fileStream = fileInfo.OpenWrite()
						Await stream.CopyToAsync(fileStream)
					End Using
				End Using
				Console.WriteLine("PDF file has been downloaded and saved as 'generated_document.pdf'")
			End If
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

APITemplate io和IronPDF C# PDF庫比較:圖11

這是生成的PDF文檔:

APITemplate io和IronPDF C# PDF庫比較:圖12

批量PDF生成

在一次API調用中生成多個文檔是APITemplate的批量PDF生成功能的遊戲規則。 這是我如何詳細使用這個功能的示例:

using System;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace csharp
{
    class ReturnContent
    {
        public string download_url { get; set; }
        public string status { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var api_key = "a9e4MjA2NTg6MTc3Njk6Uk1ZSzVjTWs1T3d6VE9Mdw=";
            var template_id = "d4f77b23b4ab09fa";
            var url = $"https://rest.apitemplate.io/v2/create-pdf?template_id={template_id}";
            var membershipCards = new List<object>
            {
                new { name = "Iron Dev 1", email = "dev1@ironsoftware.com", membership_id = "M001", expiry_date = "2024-12-31" },
                new { name = "Iron Dev 2", email = "dev2@ironsoftware.com", membership_id = "M002", expiry_date = "2025-06-30" },
                new { name = "Iron Dev 3", email = "dev3@ironsoftware.com", membership_id = "M003", expiry_date = "2024-09-15" }
            };
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("X-API-KEY", api_key);
            for (int i = 0; i < membershipCards.Count; i++)
            {
                var json_content = JsonSerializer.Serialize(membershipCards[i]);
                var buffer = System.Text.Encoding.UTF8.GetBytes(json_content);
                var byteContent = new ByteArrayContent(buffer);
                Console.WriteLine($"Creating PDF for {((dynamic)membershipCards[i]).name}...");
                var response = await client.PostAsync(url, byteContent);
                var ret = await response.Content.ReadAsStringAsync();
                var returnContent = JsonSerializer.Deserialize<ReturnContent>(ret);
                if (returnContent.status == "success")
                {
                    Console.WriteLine($"Downloading {returnContent.download_url}...");
                    var download_response = await client.GetAsync(returnContent.download_url);
                    using (var stream = await download_response.Content.ReadAsStreamAsync())
                    {
                        var fileInfo = new FileInfo($"F:/membership_card_{i + 1}.pdf");
                        using (var fileStream = fileInfo.OpenWrite())
                        {
                            await stream.CopyToAsync(fileStream);
                        }
                    }
                    Console.WriteLine($"PDF file has been downloaded and saved as 'membership_card_{i + 1}.pdf'");
                }
                else
                {
                    Console.WriteLine($"Failed to create PDF for {((dynamic)membershipCards[i]).name}. Status: {returnContent.status}");
                }
            }
        }
    }
}
using System;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace csharp
{
    class ReturnContent
    {
        public string download_url { get; set; }
        public string status { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var api_key = "a9e4MjA2NTg6MTc3Njk6Uk1ZSzVjTWs1T3d6VE9Mdw=";
            var template_id = "d4f77b23b4ab09fa";
            var url = $"https://rest.apitemplate.io/v2/create-pdf?template_id={template_id}";
            var membershipCards = new List<object>
            {
                new { name = "Iron Dev 1", email = "dev1@ironsoftware.com", membership_id = "M001", expiry_date = "2024-12-31" },
                new { name = "Iron Dev 2", email = "dev2@ironsoftware.com", membership_id = "M002", expiry_date = "2025-06-30" },
                new { name = "Iron Dev 3", email = "dev3@ironsoftware.com", membership_id = "M003", expiry_date = "2024-09-15" }
            };
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("X-API-KEY", api_key);
            for (int i = 0; i < membershipCards.Count; i++)
            {
                var json_content = JsonSerializer.Serialize(membershipCards[i]);
                var buffer = System.Text.Encoding.UTF8.GetBytes(json_content);
                var byteContent = new ByteArrayContent(buffer);
                Console.WriteLine($"Creating PDF for {((dynamic)membershipCards[i]).name}...");
                var response = await client.PostAsync(url, byteContent);
                var ret = await response.Content.ReadAsStringAsync();
                var returnContent = JsonSerializer.Deserialize<ReturnContent>(ret);
                if (returnContent.status == "success")
                {
                    Console.WriteLine($"Downloading {returnContent.download_url}...");
                    var download_response = await client.GetAsync(returnContent.download_url);
                    using (var stream = await download_response.Content.ReadAsStreamAsync())
                    {
                        var fileInfo = new FileInfo($"F:/membership_card_{i + 1}.pdf");
                        using (var fileStream = fileInfo.OpenWrite())
                        {
                            await stream.CopyToAsync(fileStream);
                        }
                    }
                    Console.WriteLine($"PDF file has been downloaded and saved as 'membership_card_{i + 1}.pdf'");
                }
                else
                {
                    Console.WriteLine($"Failed to create PDF for {((dynamic)membershipCards[i]).name}. Status: {returnContent.status}");
                }
            }
        }
    }
}
'INSTANT VB NOTE: 'Option Strict Off' is used here since dynamic typing is used:
Option Strict Off

Imports System
Imports System.IO
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks
Imports System.Collections.Generic

Namespace csharp
	Friend Class ReturnContent
		Public Property download_url() As String
		Public Property status() As String
	End Class

	Friend Class Program
		Shared Async Function Main(ByVal args() As String) As Task
			Dim api_key = "a9e4MjA2NTg6MTc3Njk6Uk1ZSzVjTWs1T3d6VE9Mdw="
			Dim template_id = "d4f77b23b4ab09fa"
			Dim url = $"https://rest.apitemplate.io/v2/create-pdf?template_id={template_id}"
			Dim membershipCards = New List(Of Object) From {
				New With {
					Key .name = "Iron Dev 1",
					Key .email = "dev1@ironsoftware.com",
					Key .membership_id = "M001",
					Key .expiry_date = "2024-12-31"
				},
				New With {
					Key .name = "Iron Dev 2",
					Key .email = "dev2@ironsoftware.com",
					Key .membership_id = "M002",
					Key .expiry_date = "2025-06-30"
				},
				New With {
					Key .name = "Iron Dev 3",
					Key .email = "dev3@ironsoftware.com",
					Key .membership_id = "M003",
					Key .expiry_date = "2024-09-15"
				}
			}
			Dim client = New HttpClient()
			client.DefaultRequestHeaders.Add("X-API-KEY", api_key)
			For i As Integer = 0 To membershipCards.Count - 1
				Dim json_content = JsonSerializer.Serialize(membershipCards(i))
				Dim buffer = System.Text.Encoding.UTF8.GetBytes(json_content)
				Dim byteContent = New ByteArrayContent(buffer)
'INSTANT VB NOTE: In the following line, Instant VB substituted 'Object' for 'dynamic' - this will work in VB with Option Strict Off:
				Console.WriteLine($"Creating PDF for {CType(membershipCards(i), Object).name}...")
				Dim response = Await client.PostAsync(url, byteContent)
				Dim ret = Await response.Content.ReadAsStringAsync()
				Dim returnContent = JsonSerializer.Deserialize(Of ReturnContent)(ret)
				If returnContent.status = "success" Then
					Console.WriteLine($"Downloading {returnContent.download_url}...")
					Dim download_response = Await client.GetAsync(returnContent.download_url)
					Using stream = Await download_response.Content.ReadAsStreamAsync()
						Dim fileInfo As New FileInfo($"F:/membership_card_{i + 1}.pdf")
						Using fileStream = fileInfo.OpenWrite()
							Await stream.CopyToAsync(fileStream)
						End Using
					End Using
					Console.WriteLine($"PDF file has been downloaded and saved as 'membership_card_{i + 1}.pdf'")
				Else
'INSTANT VB NOTE: In the following line, Instant VB substituted 'Object' for 'dynamic' - this will work in VB with Option Strict Off:
					Console.WriteLine($"Failed to create PDF for {CType(membershipCards(i), Object).name}. Status: {returnContent.status}")
				End If
			Next i
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

此代碼在單個API調用中生成多個會員卡。 每張卡都根據個別會員信息進行了定制。 這是通過這段代碼生成的一張卡:

APITemplate io和IronPDF C# PDF庫比較:圖13

圖像生成

雖然PDF生成是APITemplate的主要關注點,但其圖像生成能力同樣令人印象深刻。您可以使用控制台中的圖像模板生成社交媒體圖片。 它還提供了響應式圖像智能裁剪。橫幅生成API與圖像API相同。 這是一個我如何使用它的更複雜的示例:

using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace csharp
{
    class ReturnContent
    {
        public string download_url { get; set; }
        public string status { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var api_key = "a9e4MjA2NTg6MTc3Njk6Uk1ZSzVjTWs1T3d6VE9Mdw=";
            var template_id = "f4377b23b4aeeed0";
            var url = $"https://rest.apitemplate.io/v2/create-image?template_id={template_id}";
            var json_content = @"{
    ""overrides"": [
        {
            ""name"": ""rect_image_bg"",
            ""stroke"": ""grey"",
            ""src"": ""https://images.unsplash.com/photo-1542401886-65d6c61db217?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxOTc1MDZ8MHwxfHNlYXJjaHwzfHxkZXNlcnR8ZW58MHwwfHx8MTYyMTUxOTI2OA&ixlib=rb-1.2.1&q=80&w=1080""
        },
        {
            ""name"": ""rect_container"",
            ""stroke"": ""grey"",
            ""backgroundColor"": ""rgba(255, 255, 255, 0.62)""
        },
        {
            ""name"": ""text_quote"",
            ""text"": ""Just witnessed the most breathtaking sunset over the Sahara. The way the light dances on the dunes, painting the sky in shades of orange and purple, is truly magical. Nature's artistry at its finest!  #DesertAdventures #SaharaSkies"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#414141""
        },
        {
            ""name"": ""text_footer"",
            ""text"": ""2024-07-30 - Twitter - iPhone 16 Pro"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#666666""
        },
        {
            ""name"": ""circle_profile"",
            ""stroke"": ""grey"",
            ""src"": ""https://images.unsplash.com/photo-1520998116484-6eeb2f72b5b9?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxOTc1MDZ8MHwxfHNlYXJjaHw2Mnx8aGFwcHl8ZW58MHwwfHx8MTYyMTY5MjkwNw&ixlib=rb-1.2.1&q=80&w=1080""
        },
        {
            ""name"": ""text_name"",
            ""text"": ""Sarah Wanderlust"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#4E4E4E""
        },
        {
            ""name"": ""text_twitter"",
            ""text"": ""@sarahexplores"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#4E4E4E""
        }
    ]
}";
            var buffer = System.Text.Encoding.UTF8.GetBytes(json_content);
            var byteContent = new ByteArrayContent(buffer);
            Console.WriteLine(json_content);
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("X-API-KEY", api_key);
            var response = await client.PostAsync(url, byteContent);
            var ret = await response.Content.ReadAsStringAsync();
            var returnContent = JsonSerializer.Deserialize<ReturnContent>(ret);
            if (returnContent.status == "success")
            {
                Console.WriteLine($"Downloading {returnContent.download_url}...");
                var download_response = await client.GetAsync(returnContent.download_url);
                using (var stream = await download_response.Content.ReadAsStreamAsync())
                {
                    var fileInfo = new FileInfo("image.jpeg");
                    using (var fileStream = fileInfo.OpenWrite())
                    {
                        await stream.CopyToAsync(fileStream);
                    }
                }
            }
        }
    }
}
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace csharp
{
    class ReturnContent
    {
        public string download_url { get; set; }
        public string status { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var api_key = "a9e4MjA2NTg6MTc3Njk6Uk1ZSzVjTWs1T3d6VE9Mdw=";
            var template_id = "f4377b23b4aeeed0";
            var url = $"https://rest.apitemplate.io/v2/create-image?template_id={template_id}";
            var json_content = @"{
    ""overrides"": [
        {
            ""name"": ""rect_image_bg"",
            ""stroke"": ""grey"",
            ""src"": ""https://images.unsplash.com/photo-1542401886-65d6c61db217?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxOTc1MDZ8MHwxfHNlYXJjaHwzfHxkZXNlcnR8ZW58MHwwfHx8MTYyMTUxOTI2OA&ixlib=rb-1.2.1&q=80&w=1080""
        },
        {
            ""name"": ""rect_container"",
            ""stroke"": ""grey"",
            ""backgroundColor"": ""rgba(255, 255, 255, 0.62)""
        },
        {
            ""name"": ""text_quote"",
            ""text"": ""Just witnessed the most breathtaking sunset over the Sahara. The way the light dances on the dunes, painting the sky in shades of orange and purple, is truly magical. Nature's artistry at its finest!  #DesertAdventures #SaharaSkies"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#414141""
        },
        {
            ""name"": ""text_footer"",
            ""text"": ""2024-07-30 - Twitter - iPhone 16 Pro"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#666666""
        },
        {
            ""name"": ""circle_profile"",
            ""stroke"": ""grey"",
            ""src"": ""https://images.unsplash.com/photo-1520998116484-6eeb2f72b5b9?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxOTc1MDZ8MHwxfHNlYXJjaHw2Mnx8aGFwcHl8ZW58MHwwfHx8MTYyMTY5MjkwNw&ixlib=rb-1.2.1&q=80&w=1080""
        },
        {
            ""name"": ""text_name"",
            ""text"": ""Sarah Wanderlust"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#4E4E4E""
        },
        {
            ""name"": ""text_twitter"",
            ""text"": ""@sarahexplores"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#4E4E4E""
        }
    ]
}";
            var buffer = System.Text.Encoding.UTF8.GetBytes(json_content);
            var byteContent = new ByteArrayContent(buffer);
            Console.WriteLine(json_content);
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("X-API-KEY", api_key);
            var response = await client.PostAsync(url, byteContent);
            var ret = await response.Content.ReadAsStringAsync();
            var returnContent = JsonSerializer.Deserialize<ReturnContent>(ret);
            if (returnContent.status == "success")
            {
                Console.WriteLine($"Downloading {returnContent.download_url}...");
                var download_response = await client.GetAsync(returnContent.download_url);
                using (var stream = await download_response.Content.ReadAsStreamAsync())
                {
                    var fileInfo = new FileInfo("image.jpeg");
                    using (var fileStream = fileInfo.OpenWrite())
                    {
                        await stream.CopyToAsync(fileStream);
                    }
                }
            }
        }
    }
}
Imports System
Imports System.IO
Imports System.Net.Http
Imports System.Text
Imports System.Text.Json
Imports System.Threading.Tasks

Namespace csharp
	Friend Class ReturnContent
		Public Property download_url() As String
		Public Property status() As String
	End Class

	Friend Class Program
		Shared Async Function Main(ByVal args() As String) As Task
			Dim api_key = "a9e4MjA2NTg6MTc3Njk6Uk1ZSzVjTWs1T3d6VE9Mdw="
			Dim template_id = "f4377b23b4aeeed0"
			Dim url = $"https://rest.apitemplate.io/v2/create-image?template_id={template_id}"
			Dim json_content = "{
    ""overrides"": [
        {
            ""name"": ""rect_image_bg"",
            ""stroke"": ""grey"",
            ""src"": ""https://images.unsplash.com/photo-1542401886-65d6c61db217?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxOTc1MDZ8MHwxfHNlYXJjaHwzfHxkZXNlcnR8ZW58MHwwfHx8MTYyMTUxOTI2OA&ixlib=rb-1.2.1&q=80&w=1080""
        },
        {
            ""name"": ""rect_container"",
            ""stroke"": ""grey"",
            ""backgroundColor"": ""rgba(255, 255, 255, 0.62)""
        },
        {
            ""name"": ""text_quote"",
            ""text"": ""Just witnessed the most breathtaking sunset over the Sahara. The way the light dances on the dunes, painting the sky in shades of orange and purple, is truly magical. Nature's artistry at its finest!  #DesertAdventures #SaharaSkies"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#414141""
        },
        {
            ""name"": ""text_footer"",
            ""text"": ""2024-07-30 - Twitter - iPhone 16 Pro"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#666666""
        },
        {
            ""name"": ""circle_profile"",
            ""stroke"": ""grey"",
            ""src"": ""https://images.unsplash.com/photo-1520998116484-6eeb2f72b5b9?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxOTc1MDZ8MHwxfHNlYXJjaHw2Mnx8aGFwcHl8ZW58MHwwfHx8MTYyMTY5MjkwNw&ixlib=rb-1.2.1&q=80&w=1080""
        },
        {
            ""name"": ""text_name"",
            ""text"": ""Sarah Wanderlust"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#4E4E4E""
        },
        {
            ""name"": ""text_twitter"",
            ""text"": ""@sarahexplores"",
            ""textBackgroundColor"": ""rgba(246, 243, 243, 0)"",
            ""color"": ""#4E4E4E""
        }
    ]
}"
			Dim buffer = System.Text.Encoding.UTF8.GetBytes(json_content)
			Dim byteContent = New ByteArrayContent(buffer)
			Console.WriteLine(json_content)
			Dim client = New HttpClient()
			client.DefaultRequestHeaders.Add("X-API-KEY", api_key)
			Dim response = Await client.PostAsync(url, byteContent)
			Dim ret = Await response.Content.ReadAsStringAsync()
			Dim returnContent = JsonSerializer.Deserialize(Of ReturnContent)(ret)
			If returnContent.status = "success" Then
				Console.WriteLine($"Downloading {returnContent.download_url}...")
				Dim download_response = Await client.GetAsync(returnContent.download_url)
				Using stream = Await download_response.Content.ReadAsStreamAsync()
					Dim fileInfo As New FileInfo("image.jpeg")
					Using fileStream = fileInfo.OpenWrite()
						Await stream.CopyToAsync(fileStream)
					End Using
				End Using
			End If
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

APITemplate io和IronPDF C# PDF庫比較:圖14

此示例生成了一張具有動態內容、自定義背景顏色和嵌入式產品圖片的產品促銷圖像。

QR碼生成

APITemplate的內置QR碼生成功能為我的許多項目增色不少。 您可以用數據URL替代QR碼的內容。 這是一個我如何使用它的更複雜的示例:

using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace csharp
{
    class ReturnContent
    {
        public string download_url { get; set; }
        public string status { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var api_key = "API-Key";
            var template_id = "Template-Key";
            var url = $"https://rest.apitemplate.io/v2/create-image?template_id={template_id}";
            var json_content = @"{
    ""overrides"": [
        {
            ""name"": ""background-color"",
            ""stroke"": ""grey"",
            ""backgroundColor"": ""#FFFFFF""
        },
        {
            ""name"": ""qr_1"",
            ""content"": ""http://ironpdf.com/"",
            ""backgroundColor"": ""white"",
            ""color"": ""#000000""
        }
    ]
}";
            var buffer = System.Text.Encoding.UTF8.GetBytes(json_content);
            var byteContent = new ByteArrayContent(buffer);
            //Console.WriteLine(json_content);
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("X-API-KEY", api_key);
            var response = await client.PostAsync(url, byteContent);
            var ret = await response.Content.ReadAsStringAsync();
            var returnContent = JsonSerializer.Deserialize<ReturnContent>(ret);
            Console.WriteLine(returnContent.status);
            if (returnContent.status == "success")
            {
                Console.WriteLine($"Downloading {returnContent.download_url}...");
                var download_response = await client.GetAsync(returnContent.download_url);
                using (var stream = await download_response.Content.ReadAsStreamAsync())
                {
                    var fileInfo = new FileInfo(@"F:/QRimage.jpeg");
                    using (var fileStream = fileInfo.OpenWrite())
                    {
                        await stream.CopyToAsync(fileStream);
                    }
                }
            }
        }
    }
}
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace csharp
{
    class ReturnContent
    {
        public string download_url { get; set; }
        public string status { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var api_key = "API-Key";
            var template_id = "Template-Key";
            var url = $"https://rest.apitemplate.io/v2/create-image?template_id={template_id}";
            var json_content = @"{
    ""overrides"": [
        {
            ""name"": ""background-color"",
            ""stroke"": ""grey"",
            ""backgroundColor"": ""#FFFFFF""
        },
        {
            ""name"": ""qr_1"",
            ""content"": ""http://ironpdf.com/"",
            ""backgroundColor"": ""white"",
            ""color"": ""#000000""
        }
    ]
}";
            var buffer = System.Text.Encoding.UTF8.GetBytes(json_content);
            var byteContent = new ByteArrayContent(buffer);
            //Console.WriteLine(json_content);
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("X-API-KEY", api_key);
            var response = await client.PostAsync(url, byteContent);
            var ret = await response.Content.ReadAsStringAsync();
            var returnContent = JsonSerializer.Deserialize<ReturnContent>(ret);
            Console.WriteLine(returnContent.status);
            if (returnContent.status == "success")
            {
                Console.WriteLine($"Downloading {returnContent.download_url}...");
                var download_response = await client.GetAsync(returnContent.download_url);
                using (var stream = await download_response.Content.ReadAsStreamAsync())
                {
                    var fileInfo = new FileInfo(@"F:/QRimage.jpeg");
                    using (var fileStream = fileInfo.OpenWrite())
                    {
                        await stream.CopyToAsync(fileStream);
                    }
                }
            }
        }
    }
}
Imports System
Imports System.IO
Imports System.Net.Http
Imports System.Text
Imports System.Text.Json
Imports System.Threading.Tasks

Namespace csharp
	Friend Class ReturnContent
		Public Property download_url() As String
		Public Property status() As String
	End Class

	Friend Class Program
		Shared Async Function Main(ByVal args() As String) As Task
			Dim api_key = "API-Key"
			Dim template_id = "Template-Key"
			Dim url = $"https://rest.apitemplate.io/v2/create-image?template_id={template_id}"
			Dim json_content = "{
    ""overrides"": [
        {
            ""name"": ""background-color"",
            ""stroke"": ""grey"",
            ""backgroundColor"": ""#FFFFFF""
        },
        {
            ""name"": ""qr_1"",
            ""content"": ""http://ironpdf.com/"",
            ""backgroundColor"": ""white"",
            ""color"": ""#000000""
        }
    ]
}"
			Dim buffer = System.Text.Encoding.UTF8.GetBytes(json_content)
			Dim byteContent = New ByteArrayContent(buffer)
			'Console.WriteLine(json_content);
			Dim client = New HttpClient()
			client.DefaultRequestHeaders.Add("X-API-KEY", api_key)
			Dim response = Await client.PostAsync(url, byteContent)
			Dim ret = Await response.Content.ReadAsStringAsync()
			Dim returnContent = JsonSerializer.Deserialize(Of ReturnContent)(ret)
			Console.WriteLine(returnContent.status)
			If returnContent.status = "success" Then
				Console.WriteLine($"Downloading {returnContent.download_url}...")
				Dim download_response = Await client.GetAsync(returnContent.download_url)
				Using stream = Await download_response.Content.ReadAsStreamAsync()
					Dim fileInfo As New FileInfo("F:/QRimage.jpeg")
					Using fileStream = fileInfo.OpenWrite()
						Await stream.CopyToAsync(fileStream)
					End Using
				End Using
			End If
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

APITemplate io和IronPDF C# PDF庫比較:圖15

文檔和支持

作為一名經常從事PDF生成和操作的C#開發人員,我發現文檔和支持的質量可能會成為一個項目的成敗關鍵。 讓我們來看看我在IronPDF和APITemplate上的文檔和支持經驗。

IronPDF

文檔

IronPDF的文檔內容詳盡且結構良好,這在我的項目中大有幫助。 這是我經歷的詳細分析: IronPDF文檔可以在https://ironpdf.com/docs/找到,非常全面。以下是我欣賞的一些關鍵方面:

  1. 入門指南: 該文檔以一個清晰的逐步指南開始,介紹如何通過NuGet安裝IronPDF並創建第一個PDF。 這幫助我在最初的項目中迅速上手。

  2. API參考: API參考非常詳細,涵蓋了所有類和方法。 每一項都包括C#示例,這在我實施特定功能時非常有價值。

  3. 代碼示例: 整份文檔中有許多代碼片段和完整示例。 當我需要實施更復雜的PDF操作時,這些對我很有幫助。

  4. 教程和操作指南: IronPDF提供了詳細教程,以完成創建HTML PDF、添加水印或處理表單等常見任務。 這些指導我完成了更高級的用例。

  5. 故障排除部分: 文檔包括一個故障排除部分,解決常見問題。 當出現錯誤或意想不到的行為時,這節省了我不少時間。

支持

IronPDF的聯繫反應迅速,並且支持渠道在我使用中極其有幫助:

  1. 電子郵件支持: 當我有複雜的問題時,我使用了他們的電子郵件支持。 響應時間通常在24小時內,並且支持團隊對產品知識豐富。

  2. 社區論壇: IronPDF開設了一個社區論壇,開發人員可以在此提出問題並共享解決方案。 我既找到了問題的答案,也根據自己的經驗分享了解決方案。

  3. Stack Overflow: IronPDF團隊積極監控Stack Overflow上的[ironpdf]標籤。 我在那裡發布的問題中收到了有幫助的回覆。

  4. 定期更新: IronPDF經常發布包含錯誤修復和新功能的更新。 更新日誌詳細幫助我了解每個版本的新功能或變化。

  5. 升級指南: 當主要版本之間有重大更改時,IronPDF提供了升級指南。 這對於將我的項目升級到新版本的庫至關重要。

APITemplate

APITemplate的文檔和支持結構與IronPDF不同,這反映了其作為一項基於雲的服務的特性。這是我的經驗:

文檔

APITemplate的文檔可以在https://docs.apitemplate.io/reference/api-reference.html找到,主要關注API使用。 以下是關鍵點:

  1. API參考: 文檔提供了明確的API參考,詳細列出所有可用的端點、所需的參數和響應格式。 這一直是我將APITemplate集成到我的C#應用中時的首選資源。

  2. 身份驗證: 有一個專門的部分解釋如何使用API密鑰。 我開始使用該服務時這尤其重要。

支持

APITemplate的支持結構更側重於電子郵件支持:

  1. 電子郵件支持: 當我遇到問題或有疑問時,我使用了他們的電子郵件支持。 響應時間通常為1-2個工作日。

  2. 常見問題部分: 文檔包括一個常見問題部分,解決常見問題。 當我遇到問題時,這常是我先查看的地方。

使用Bootstrap 5和IronPDF進行分析儀表盤設計

IronPDF的Chrome V8渲染引擎在渲染現代Bootstrap 5佈局方面表現出色,這使它成為生成帶有商業指標和數據視覺化的PDF報告的理想選擇。 與APITemplate的API方法不同,IronPDF直接處理HTML並提供完整的CSS3支持,包括flexbox、CSS Grid和自定義屬性。

using IronPdf;

var renderer = new ChromePdfRenderer();

string analyticsDashboard = @"
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <style>
        .metric-card {
            transition: transform 0.2s;
            border-left: 4px solid #0d6efd;
        }
        .metric-card:hover { transform: translateY(-5px); }
        .trend-up { color: #198754; }
        .trend-down { color: #dc3545; }
        @media print {
            .metric-card { page-break-inside: avoid; }
        }
    </style>
</head>
<body class='bg-light'>
    <div class='container py-5'>
        <div class='row mb-4'>
            <div class='col-12'>
                <div class='card shadow-sm'>
                    <div class='card-body'>
                        <h1 class='display-6 mb-0'>Performance Dashboard</h1>
                        <p class='text-muted mb-0'>Q4 2024 Analytics Overview</p>
                    </div>
                </div>
            </div>
        </div>

        <div class='row g-4 mb-4'>
            <div class='col-md-3'>
                <div class='card metric-card shadow-sm h-100'>
                    <div class='card-body'>
                        <h6 class='text-muted text-uppercase mb-2'>Total Revenue</h6>
                        <h2 class='display-6 mb-3'>$2.4M</h2>
                        <div class='progress' style='height: 6px;'>
                            <div class='progress-bar bg-success' style='width: 85%'></div>
                        </div>
                        <small class='trend-up'>↑ 18% from last quarter</small>
                    </div>
                </div>
            </div>
            <div class='col-md-3'>
                <div class='card metric-card shadow-sm h-100'>
                    <div class='card-body'>
                        <h6 class='text-muted text-uppercase mb-2'>Active Users</h6>
                        <h2 class='display-6 mb-3'>48,592</h2>
                        <div class='progress' style='height: 6px;'>
                            <div class='progress-bar bg-primary' style='width: 72%'></div>
                        </div>
                        <small class='trend-up'>↑ 12% growth rate</small>
                    </div>
                </div>
            </div>
            <div class='col-md-3'>
                <div class='card metric-card shadow-sm h-100'>
                    <div class='card-body'>
                        <h6 class='text-muted text-uppercase mb-2'>Conversion Rate</h6>
                        <h2 class='display-6 mb-3'>3.8%</h2>
                        <div class='progress' style='height: 6px;'>
                            <div class='progress-bar bg-warning' style='width: 38%'></div>
                        </div>
                        <small class='trend-down'>↓ 2% needs attention</small>
                    </div>
                </div>
            </div>
            <div class='col-md-3'>
                <div class='card metric-card shadow-sm h-100'>
                    <div class='card-body'>
                        <h6 class='text-muted text-uppercase mb-2'>Satisfaction</h6>
                        <h2 class='display-6 mb-3'>4.7/5</h2>
                        <div class='progress' style='height: 6px;'>
                            <div class='progress-bar bg-success' style='width: 94%'></div>
                        </div>
                        <small class='trend-up'>↑ Excellent rating</small>
                    </div>
                </div>
            </div>
        </div>

        <div class='card shadow-sm'>
            <div class='card-body'>
                <h5 class='card-title mb-3'>Top Performing Products</h5>
                <div class='table-responsive'>
                    <table class='table table-hover'>
                        <thead class='table-light'>
                            <tr>
                                <th>Product</th>
                                <th>Revenue</th>
                                <th>Units</th>
                                <th>Trend</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><strong>Enterprise Suite</strong></td>
                                <td>$1,240,000</td>
                                <td>2,150</td>
                                <td><span class='badge bg-success'>+22%</span></td>
                            </tr>
                            <tr>
                                <td><strong>Professional Plan</strong></td>
                                <td>$820,000</td>
                                <td>4,890</td>
                                <td><span class='badge bg-success'>+15%</span></td>
                            </tr>
                            <tr>
                                <td><strong>Starter Package</strong></td>
                                <td>$340,000</td>
                                <td>8,240</td>
                                <td><span class='badge bg-warning'>+5%</span></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(analyticsDashboard);
pdf.SaveAs("analytics-dashboard.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

string analyticsDashboard = @"
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <style>
        .metric-card {
            transition: transform 0.2s;
            border-left: 4px solid #0d6efd;
        }
        .metric-card:hover { transform: translateY(-5px); }
        .trend-up { color: #198754; }
        .trend-down { color: #dc3545; }
        @media print {
            .metric-card { page-break-inside: avoid; }
        }
    </style>
</head>
<body class='bg-light'>
    <div class='container py-5'>
        <div class='row mb-4'>
            <div class='col-12'>
                <div class='card shadow-sm'>
                    <div class='card-body'>
                        <h1 class='display-6 mb-0'>Performance Dashboard</h1>
                        <p class='text-muted mb-0'>Q4 2024 Analytics Overview</p>
                    </div>
                </div>
            </div>
        </div>

        <div class='row g-4 mb-4'>
            <div class='col-md-3'>
                <div class='card metric-card shadow-sm h-100'>
                    <div class='card-body'>
                        <h6 class='text-muted text-uppercase mb-2'>Total Revenue</h6>
                        <h2 class='display-6 mb-3'>$2.4M</h2>
                        <div class='progress' style='height: 6px;'>
                            <div class='progress-bar bg-success' style='width: 85%'></div>
                        </div>
                        <small class='trend-up'>↑ 18% from last quarter</small>
                    </div>
                </div>
            </div>
            <div class='col-md-3'>
                <div class='card metric-card shadow-sm h-100'>
                    <div class='card-body'>
                        <h6 class='text-muted text-uppercase mb-2'>Active Users</h6>
                        <h2 class='display-6 mb-3'>48,592</h2>
                        <div class='progress' style='height: 6px;'>
                            <div class='progress-bar bg-primary' style='width: 72%'></div>
                        </div>
                        <small class='trend-up'>↑ 12% growth rate</small>
                    </div>
                </div>
            </div>
            <div class='col-md-3'>
                <div class='card metric-card shadow-sm h-100'>
                    <div class='card-body'>
                        <h6 class='text-muted text-uppercase mb-2'>Conversion Rate</h6>
                        <h2 class='display-6 mb-3'>3.8%</h2>
                        <div class='progress' style='height: 6px;'>
                            <div class='progress-bar bg-warning' style='width: 38%'></div>
                        </div>
                        <small class='trend-down'>↓ 2% needs attention</small>
                    </div>
                </div>
            </div>
            <div class='col-md-3'>
                <div class='card metric-card shadow-sm h-100'>
                    <div class='card-body'>
                        <h6 class='text-muted text-uppercase mb-2'>Satisfaction</h6>
                        <h2 class='display-6 mb-3'>4.7/5</h2>
                        <div class='progress' style='height: 6px;'>
                            <div class='progress-bar bg-success' style='width: 94%'></div>
                        </div>
                        <small class='trend-up'>↑ Excellent rating</small>
                    </div>
                </div>
            </div>
        </div>

        <div class='card shadow-sm'>
            <div class='card-body'>
                <h5 class='card-title mb-3'>Top Performing Products</h5>
                <div class='table-responsive'>
                    <table class='table table-hover'>
                        <thead class='table-light'>
                            <tr>
                                <th>Product</th>
                                <th>Revenue</th>
                                <th>Units</th>
                                <th>Trend</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><strong>Enterprise Suite</strong></td>
                                <td>$1,240,000</td>
                                <td>2,150</td>
                                <td><span class='badge bg-success'>+22%</span></td>
                            </tr>
                            <tr>
                                <td><strong>Professional Plan</strong></td>
                                <td>$820,000</td>
                                <td>4,890</td>
                                <td><span class='badge bg-success'>+15%</span></td>
                            </tr>
                            <tr>
                                <td><strong>Starter Package</strong></td>
                                <td>$340,000</td>
                                <td>8,240</td>
                                <td><span class='badge bg-warning'>+5%</span></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(analyticsDashboard);
pdf.SaveAs("analytics-dashboard.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這段代碼生成了一個專業的分析儀表盤PDF,其中包含度量卡、進度條和響應表格。 IronPDF的Chrome引擎完美渲染Bootstrap的flexbox佈局、陰影和懸停效果——這些特性需要使用API服務如APITemplate時進行大量的定製工作。

與APITemplate相比的主要優勢:

  • 直接HTML渲染與完整Bootstrap支持
  • 無需API調用或模板配置
  • 全面CSS3兼容性,包括動畫
  • 離線處理無需外部依賴

欲了解更多有關Bootstrap PDF生成的信息,請參閱HTML到PDF的Bootstrap指南

許可

IronPDF定價和許可

APITemplate io和IronPDF C# PDF庫比較:圖16

IronPDF提供多種定價級別以滿足不同需求:

  1. Lite: 標價$799,適合單個開發人員在單個項目上進行使用。 這是一個一次性費用,使其成為小型項目或個人開發人員的經濟選擇。
  2. Professional: 價格為$1,199,該選項支持最多10開發者、10個地點和10個項目。 這個級別也包含一次性價格,為小型到中型團隊提供更多的靈活性。
  3. Unlimited: 價格為$2,399,此級別允許無限數的開發人員、地點和項目。 這對於需要大範圍使用而無任何限制的包括大型團隊和企業來說是完美的選擇。

IronPDF還為大型組織和需要將PDF功能集成到商業產品中的OEM提供企業許可和重新分發許可。 此外,還提供免費試用以便測試。

APITemplate定價和許可

APITemplate通過其基於API的PDF生成服務提供不同的方法。價格通常基於API調用的次數,對於不同的使用模式非常靈活:

  1. 基本計畫: 通常從更低價格的起點開始,每月限制一定次數的API調用。 這適合於小型項目或生成需求很少的企業。
  2. 標準計畫: 包括更多API調用和附加功能,適用於中型企業。
  3. 企業計畫: 為高流量用戶量身定做,提供最多API調用和高級功能如優先支持和自定義集成。

APITemplate的許可條款簡單明了,通常與每月或每年訂閱模式掛鈎。

主要區別

  1. 定價模型: IronPDF採用一次性費用模型,從長遠來看,尤其是對於持續不斷的高強度使用,這可以是成本效益高的選擇。 而APITemplate採用的是基於訂閱的模型,這在使用方面較為靈活和可擴展。
  2. 支持和更新: IronPDF包括購買後一年期的支持和更新,並提供擴展選項。 APITemplate的訂閱計畫通常將持續的支持和更新包括在內。

為什麼選擇IronPDF?

IronPDF和APITemplate都提供從HTML內容生成PDF的功能,但IronPDF在實現方面更加強大和靈活。 這是一個比較:

IronPDF

using IronPdf;

var renderer = new ChromePdfRenderer();
var html = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; }
        .header { color: #0066cc; font-size: 24px; }
        .content { margin-top: 20px; }
    </style>
</head>
<body>
    <div class='header'>Dynamic Report</div>
    <div class='content'>
        <p>This report was generated on: <script>document.write(new Date().toLocaleString());</script></p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("IronPDF_report.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();
var html = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; }
        .header { color: #0066cc; font-size: 24px; }
        .content { margin-top: 20px; }
    </style>
</head>
<body>
    <div class='header'>Dynamic Report</div>
    <div class='content'>
        <p>This report was generated on: <script>document.write(new Date().toLocaleString());</script></p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("IronPDF_report.pdf");
Imports IronPdf

Private renderer = New ChromePdfRenderer()
Private html = "
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; }
        .header { color: #0066cc; font-size: 24px; }
        .content { margin-top: 20px; }
    </style>
</head>
<body>
    <div class='header'>Dynamic Report</div>
    <div class='content'>
        <p>This report was generated on: <script>document.write(new Date().toLocaleString());</script></p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
</body>
</html>"
Private pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("IronPDF_report.pdf")
$vbLabelText   $csharpLabel

APITemplate

using System.Net.Http;
using System.Text.Json;

var apiKey = "your_api_key";
var templateId = "your_template_id";
var url = $"https://rest.apitemplate.io/v2/create-pdf?template_id={templateId}";
var data = new
{
    header = "Dynamic Report",
    content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    date = DateTime.Now.ToShortDateString()
};
var json = JsonSerializer.Serialize(data);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);
var response = await client.PostAsync(url, content);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
File.WriteAllBytes("APITemplate_report.pdf", pdfBytes);
using System.Net.Http;
using System.Text.Json;

var apiKey = "your_api_key";
var templateId = "your_template_id";
var url = $"https://rest.apitemplate.io/v2/create-pdf?template_id={templateId}";
var data = new
{
    header = "Dynamic Report",
    content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    date = DateTime.Now.ToShortDateString()
};
var json = JsonSerializer.Serialize(data);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);
var response = await client.PostAsync(url, content);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
File.WriteAllBytes("APITemplate_report.pdf", pdfBytes);
Imports System.Net.Http
Imports System.Text.Json

Private apiKey = "your_api_key"
Private templateId = "your_template_id"
Private url = $"https://rest.apitemplate.io/v2/create-pdf?template_id={templateId}"
Private data = New With {
	Key .header = "Dynamic Report",
	Key .content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
	Key .date = DateTime.Now.ToShortDateString()
}
Private json = JsonSerializer.Serialize(data)
Private content = New StringContent(json, System.Text.Encoding.UTF8, "application/json")
Private client = New HttpClient()
client.DefaultRequestHeaders.Add("X-API-KEY", apiKey)
Dim response = Await client.PostAsync(url, content)
Dim pdfBytes = Await response.Content.ReadAsByteArrayAsync()
File.WriteAllBytes("APITemplate_report.pdf", pdfBytes)
$vbLabelText   $csharpLabel

主要區別

  1. JavaScript支持: IronPDF完全支持在HTML內的JavaScript執行,允許動態內容生成(例如示例中的當前日期)。 APITemplate通常要求提前提供所有數據。
  2. CSS靈活性: 使用IronPDF,您可以直接在HTML中完全控制CSS樣式。 APITemplate通常需要預定義模板和有限的自定義選項。
  3. 性能: IronPDF本地處理HTML,對於複雜文檔來說,生成PDF速度更快。 APITemplate的雲端方式可能會引入延遲。
  4. 離線能力: IronPDF可以離線工作,對於網絡連接受限或設有高安全需求的應用尤其有用。 APITemplate始終需要網絡連接。
  5. 動態內容: IronPDF允許更多即時動態內容生成,而APITemplate通常需要預定義的模板結構。
  6. 自定義: IronPDF提供了對PDF生成過程的更細緻控制,包括頁面大小、邊距和其他PDF特定設置的選項。
  7. 一致性:IronPDF 使用其渲染引擎,確保在不同環境下的一致渲染。APITemplate 的輸出可能會因其伺服器配置而有所不同。

結論

在 C# 項目中廣泛使用 IronPDF 和 APITemplate 後,我逐漸欣賞到每個工具的獨特優勢。 然而,對於大多數與 PDF 相關的任務,IronPDF 一直被證明是更優越的選擇。儘管 APITemplate 有其優點,特別是對於簡單的模板文件生成,我發現 IronPDF 的多功能性使其能夠同樣有效地處理這些任務,同時在需要時也能提供處理更複雜 PDF 操作的能力。

總之,雖然這兩個工具都有其適用之處,但 IronPDF 一直被證明是更強大、靈活且具成本效益的 C# 開發中的 PDF 操作解決方案。 其強大的功能集、卓越的性能和全面的支持使其成為我處理任何與 PDF 相關任務的首選,不論是最簡單的文檔生成還是最複雜的 PDF 操作。

請注意APITemplate 是其各自所有者的註冊商標。 本站與 APITemplate 無關,亦未經其認可或贊助。 所有產品名稱、徽標和品牌均為其各自所有者的財產。 比較僅供信息參考,並反映撰寫時公開可用的信息。

常見問題解答

雲端工具和庫工具之間的 PDF 生成工具有何主要差異?

像 APITemplate 這樣的雲端工具通過 API 調用生成 PDF,需要互聯網連接。與此相反,像 IronPDF 這樣的庫工具集成在你的 C# 應用中,允許離線 PDF 操作並提供更多的 PDF 創建和自定義控制。

IronPDF 如何在 C# 應用程序中處理 HTML 到 PDF 的轉換?

IronPDF 允許使用像 RenderHtmlAsPdf 這樣的方法無縫地將 HTML 轉換為 PDF。它完全支持包括 CSS 和 JavaScript 在內的現代網頁標準,確保將網頁內容高質量地呈現在 PDF 中。

我可以使用 IronPDF 來生成 PDF 中的動態內容嗎?

是的,IronPDF 支持 JavaScript 的執行,這讓 PDF 中的動態內容生成成為可能。這在直接從具有動態數據的網頁創建交互式 PDF 時特別有用。

使用 IronPDF 比訂閱服務有什麼優勢?

IronPDF 提供一次性授權費,是一種實惠的長期使用解決方案。它允許離線操作,並提供廣泛的 PDF 操作功能,這可能比像 APITemplate 這樣的訂閱服務更靈活和強大。

IronPDF 為開發人員提供了什麼支持?

IronPDF 通過詳細的文檔提供全面支持,包括指南、API 參考和代碼示例。開發人員還可以通過電子郵件支持、社區論壇以及在 Stack Overflow 等平台上進行監控來尋求幫助。

IronPDF 是否支持跨平台開發?

是的,IronPDF 與 .NET Standard 兼容,支持跨平台開發。這確保了開發人員可以無縫地將 IronPDF 集成到運行於不同操作系統的項目中。

IronPDF 如何確保生成的 PDF 的安全性?

IronPDF 包括 PDF 加密和解密功能,允許開發人員使用密碼和數字簽名來保護文檔。這些功能有助於維護 PDF 文檔的機密性和完整性。

使用 IronPDF 有哪些常見的故障排除提示?

當遇到 IronPDF 的問題時,確保所有依賴項均已正確安裝和更新。檢查文檔以了解兼容性和配置設置,並查看示例代碼以驗證實施方法。如果問題依然存在,支持團隊將提供幫助。

Curtis Chau
技術作家

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

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