透かしなしで本番環境でテストしてください。
必要な場所で動作します。
30日間、完全に機能する製品をご利用いただけます。
数分で稼働させることができます。
製品トライアル期間中にサポートエンジニアリングチームへの完全アクセス
HTMLをPDFに変換することは、多くのソフトウェアアプリケーションで一般的な要件であり、レポートの生成、請求書の発行、ウェブページをPDFとして保存する場合などに使用されます。 この記事では、C#でのHTMLからPDFへの変換における3つの人気のあるオープンソースライブラリを紹介し、それらの強みと制約を確認し、なぜIronPDFが多くの場面でより良い選択肢であるかについて議論します。
Pixabay から追加アップロード
またはここに画像をドラッグアンドドロップします
画像の代替テキストを追加
PuppeteerSharpは、ヘッドレスChromiumブラウザであるPuppeteerの.NETラッパーです。 それにより、開発者はChromiumレンダリングエンジンを活用してHTMLドキュメントをPDFに変換できます。
PuppeteerSharpはレンダリングプロセスに対して正確な制御を提供します。 Here's an example: 例があります。
using PuppeteerSharp;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download Chromium
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
// Launch Browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
{
// Open a new page
var page = await browser.NewPageAsync();
// Set HTML content
await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
// Generate PDF
await page.PdfAsync("output.pdf");
Console.WriteLine("PDF Generated Successfully!");
}
}
}
using PuppeteerSharp;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download Chromium
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
// Launch Browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
{
// Open a new page
var page = await browser.NewPageAsync();
// Set HTML content
await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
// Generate PDF
await page.PdfAsync("output.pdf");
Console.WriteLine("PDF Generated Successfully!");
}
}
}
Imports PuppeteerSharp
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
' Download Chromium
Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultChromiumRevision)
' Launch Browser
Using browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
' Open a new page
Dim page = Await browser.NewPageAsync()
' Set HTML content
Await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>")
' Generate PDF
Await page.PdfAsync("output.pdf")
Console.WriteLine("PDF Generated Successfully!")
End Using
End Function
End Class
Chromiumのダウンロード: PuppeteerSharpは互換性を確保するために必要なChromiumのバージョンを自動的にダウンロードします。
ブラウザーを起動: Puppeteer.LaunchAsync()を使用してChromiumのヘッドレスインスタンスを開始します。
HTMLコンテンツを設定する: 目的のHTMLをpage.SetContentAsync()を使用してブラウザページに読み込みます。
PDFを生成: レンダリングされたコンテンツからPDFを生成するには、page.PdfAsync()メソッドを使用します。
結果は、HTMLの構造とデザインを正確に再現した高品質なPDF(output.pdf)です。
Pixabay から追加アップロード
またはここに画像をドラッグアンドドロップします
画像の代替テキストを追加
PdfSharpは、C#でPDFファイルを作成および操作するための強力なオープンソースライブラリです。 直接的にHTMLレンダリングをサポートするわけではありませんが、PDFドキュメントをプログラム的に生成および編集するためのツールを開発者に提供する点で優れています。
PDF作成: PdfSharpは、開発者がページサイズを定義し、テキスト、形状、画像などを追加することで、新しいPDFファイルをゼロから生成できるようにします。
既存のPDFの操作: 既存のPDFドキュメントを変更することができます。例えば、結合、分割、またはコンテンツの抽出などです。
描画機能: PdfSharpは、XGraphicsクラスを使用してPDFファイルにカスタムデザインを追加するための強力なグラフィックス機能を提供します。
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// Example HTML content
string htmlContent = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>";
// Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
// Create a new PDF document
PdfDocument pdfDocument = new PdfDocument();
pdfDocument.Info.Title = "HTML to PDF Example";
// Add a new page to the document
PdfPage page = pdfDocument.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont titleFont = new XFont("Arial", 20, XFontStyle.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyle.Regular);
// Draw the parsed HTML content
int yPosition = 50; // Starting Y position
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//h1
//p"))
{
if (node.Name == "h1")
{
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 30; // Adjust spacing
}
else if (node.Name == "p")
{
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 20; // Adjust spacing
}
}
// Save the PDF document
string outputFilePath = "HtmlToPdf.pdf";
pdfDocument.Save(outputFilePath);
System.Console.WriteLine($"PDF file created: {outputFilePath}");
}
}
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// Example HTML content
string htmlContent = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>";
// Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
// Create a new PDF document
PdfDocument pdfDocument = new PdfDocument();
pdfDocument.Info.Title = "HTML to PDF Example";
// Add a new page to the document
PdfPage page = pdfDocument.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont titleFont = new XFont("Arial", 20, XFontStyle.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyle.Regular);
// Draw the parsed HTML content
int yPosition = 50; // Starting Y position
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//h1
//p"))
{
if (node.Name == "h1")
{
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 30; // Adjust spacing
}
else if (node.Name == "p")
{
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 20; // Adjust spacing
}
}
// Save the PDF document
string outputFilePath = "HtmlToPdf.pdf";
pdfDocument.Save(outputFilePath);
System.Console.WriteLine($"PDF file created: {outputFilePath}");
}
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports HtmlAgilityPack
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Example HTML content
Dim htmlContent As String = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>"
' Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
Dim htmlDoc = New HtmlDocument()
htmlDoc.LoadHtml(htmlContent)
' Create a new PDF document
Dim pdfDocument As New PdfDocument()
pdfDocument.Info.Title = "HTML to PDF Example"
' Add a new page to the document
Dim page As PdfPage = pdfDocument.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
Dim titleFont As New XFont("Arial", 20, XFontStyle.Bold)
Dim textFont As New XFont("Arial", 12, XFontStyle.Regular)
' Draw the parsed HTML content
Dim yPosition As Integer = 50 ' Starting Y position
'INSTANT VB TODO TASK: The following line uses invalid syntax:
' foreach(var node in htmlDoc.DocumentNode.SelectNodes("//h1 { if (node.Name == "h1") { gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft); yPosition += 30; } else if (node.Name == "p") { gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft); yPosition += 20; } } string outputFilePath = "HtmlToPdf.pdf"; pdfDocument.Save(outputFilePath); System.Console.WriteLine(string.Format("PDF file created: {0}", outputFilePath)); } }
HTML 解析: この例では、HtmlAgilityPack(HTML の解析と操作のためのオープンソースライブラリ)を使用して、
タグからテキストコンテンツを抽出します。
描画コンテンツ: PdfSharp の XGraphics クラスは、解析された HTML コンテンツを PDF ページ上のテキストとしてレンダリングするために使用されます。
Pixabay から追加アップロード
またはここに画像をドラッグアンドドロップします
画像の代替テキストを追加
Pdfium.NET は、オープンソースのPDFiumプロジェクトに基づいた包括的なライブラリであり、.NETアプリケーションでPDFファイルを表示、編集、操作するために設計されています。 それは、開発者にPDFからコンテンツを作成、編集、抽出するための強力なツールを提供し、幅広い用途に適しています。 それは基本的に無料のHTMLからPDFへのコンバーターライブラリです。
PDFの作成と編集:
テキストと画像の抽出:
PDFビューアコントロール:
互換性:
高度な機能:
using Pdfium.Net.SDK;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize Pdfium.NET SDK
PdfCommon.Initialize();
// Create a new PDF document
PdfDocument pdfDocument = PdfDocument.CreateNew();
// Add a page to the document
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842); // A4 size in points (8.27 x 11.69 inches)
// Add HTML content (example: parsed manually)
var htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>";
// Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
var font = PdfFont.CreateFont(pdfDocument, "Arial");
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!");
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.");
// Save the document
string outputFilePath = "HtmlToPdfExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.Default);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
using Pdfium.Net.SDK;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize Pdfium.NET SDK
PdfCommon.Initialize();
// Create a new PDF document
PdfDocument pdfDocument = PdfDocument.CreateNew();
// Add a page to the document
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842); // A4 size in points (8.27 x 11.69 inches)
// Add HTML content (example: parsed manually)
var htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>";
// Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
var font = PdfFont.CreateFont(pdfDocument, "Arial");
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!");
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.");
// Save the document
string outputFilePath = "HtmlToPdfExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.Default);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
Imports Pdfium.Net.SDK
Imports System
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Initialize Pdfium.NET SDK
PdfCommon.Initialize()
' Create a new PDF document
Dim pdfDocument As PdfDocument = PdfDocument.CreateNew()
' Add a page to the document
Dim page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842) ' A4 size in points (8.27 x 11.69 inches)
' Add HTML content (example: parsed manually)
Dim htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>"
' Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
Dim font = PdfFont.CreateFont(pdfDocument, "Arial")
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!")
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.")
' Save the document
Dim outputFilePath As String = "HtmlToPdfExample.pdf"
pdfDocument.Save(outputFilePath, SaveFlags.Default)
Console.WriteLine($"PDF created successfully: {outputFilePath}")
End Sub
End Class
SDKの初期化: PdfCommon.Initialize() メソッドはPdfium.NETの機能を初期化します。
PDFの作成: 新しいPDFドキュメントはPdfDocument.CreateNew()を使用して作成されます。
ページを追加する: ページは指定された寸法(例:A4サイズ)でPDFに挿入されます。
HTMLコンテンツのレンダリング: Pdfium.NET SDKはネイティブでHTMLレンダリングをサポートしていないため、HTML要素を手動でテキスト、形状、または画像として解析してレンダリングする必要があります。
Pixabay から追加アップロード
またはここに画像をドラッグアンドドロップします
画像の代替テキストを追加
IronPDFは、HTMLコンテンツを高品質なPDFに簡単に変換するために設計されたプロフェッショナルグレードのライブラリで、.NET開発者向けです。 その信頼性、先進的な機能、使いやすさで知られるIronPDFは、正確なレンダリングと強力な機能を提供しながら開発プロセスを簡略化します。 ここで、IronPDFが際立っている理由をご紹介します:
HTMLからPDFへの直接変換: IronPDFを使用して、CSSやJavaScriptを含むHTMLコンテンツを完全にフォーマットされたPDFに直接変換します。 わずか数行のコードで、開発者はウェブページ、生のHTML文字列、またはローカルHTMLファイルからPDFを生成できます。
最新のレンダリング機能: 最新のWeb標準に対応しているIronPDFは、複雑なレイアウト、スタイル、およびインタラクティブ要素を正確にレンダリングし、HTMLページをPDFに変換します。
高度なPDF機能:IronPDFは、ヘッダー、フッター、透かし、注釈、ブックマークを追加するなど、広範なカスタマイズオプションを提供します。 既存のPDFの結合、分割、編集もサポートしています。 PDFドキュメントを分割する
パフォーマンスとスケーラビリティ:小規模なアプリケーションとエンタープライズ環境の両方に最適化されたIronPDFは、あらゆる規模のプロジェクトに対して迅速で信頼性のあるパフォーマンスを提供します。
IronPDFは、機能の組み合わせ、開発者サポート、パフォーマンスにより他のソリューションの中で際立っています。 オープンソースの代替品がしばしば広範な設定や外部依存を必要とするのとは異なり、IronPDFは機能性を損なうことなく開発を簡素化する自己完結型のソリューションです。 請求書、レポートの作成、またはウェブコンテンツのアーカイブに関して、IronPDFは開発者にプロフェッショナルな結果を迅速かつ効率的に達成するために必要なツールを提供します。
IronPDFは、HTMLからPDFへのワークフローで信頼性、スケーラビリティ、使いやすさを重視する開発者にとって実用的な選択肢です。
class Program
{
static void Main()
{
// Specify license key
License.LicenseKey = "Yoour Key";
// Create a new HtmlToPdf object
var Renderer = new ChromePdfRenderer();
// Define the HTML string/ HTML code to be converted, can use html document
string htmlContent = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>";
// Convert pdf simple HTML string to a PDF document
var document = Renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf"); // path to pdf file generated
}
}
class Program
{
static void Main()
{
// Specify license key
License.LicenseKey = "Yoour Key";
// Create a new HtmlToPdf object
var Renderer = new ChromePdfRenderer();
// Define the HTML string/ HTML code to be converted, can use html document
string htmlContent = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>";
// Convert pdf simple HTML string to a PDF document
var document = Renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf"); // path to pdf file generated
}
}
Friend Class Program
Shared Sub Main()
' Specify license key
License.LicenseKey = "Yoour Key"
' Create a new HtmlToPdf object
Dim Renderer = New ChromePdfRenderer()
' Define the HTML string/ HTML code to be converted, can use html document
Dim htmlContent As String = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>"
' Convert pdf simple HTML string to a PDF document
Dim document = Renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf") ' path to pdf file generated
End Sub
End Class
プログラムは、ライブラリの完全な機能を解放するために必要なIronPDF ライセンス キーを設定することから始まります。
ChromePdfRendererのインスタンスが初期化されます。 このコンポーネントはHTMLコンテンツをPDFドキュメントに変換する役割を担い、生のHTMLと最終的な出力の間の橋渡しをします。
文字列変数、htmlContent が作成され、PDF に変換されるHTML構造を格納します。 この例では、シンプルな見出しが含まれています。
RenderHtmlAsPdf() メソッドは、ChromePdfRenderer インスタンスで呼び出され、HTML 文字列を入力として渡します。 この関数はコンテンツを処理し、PDFドキュメントに変換します。
最後に、生成されたPDFはSaveAs()メソッドを使用して「html2Pdf.pdf」という名前のファイルに保存され、将来アクセスできるようディスクに保管されます。
Pixabay から追加アップロード
またはここに画像をドラッグアンドドロップします
画像の代替テキストを追加
IronPDFは、有効なライセンスキーが必要です。 公式ウェブサイトから試用ライセンスを取得できます。IronPDFライブラリを使用する前に、次のようにライセンスキーを設定してください。
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key"
これは、ライブラリが制限なく動作することを保証します。
PuppeteerSharpは、HTMLをPDFに正確にレンダリングする必要がある開発者にとって、特に複雑なウェブページを扱う際に優れた選択肢です。 しかし、高度なPDF特有の機能、パフォーマンスの最適化、統合の容易さが必要なアプリケーションには、IronPDFのようなプロフェッショナルツールがより良い選択肢であることが多いです。
PdfSharpは、軽量でプログラムによるPDFの作成と操作に優れており、特にシンプルな要件を持つプロジェクトに最適です。 ただし、アプリケーションがHTMLをPDFに変換する必要がある場合や、高度なPDF機能を必要とする場合、IronPDFはより効率的で多機能なソリューションを提供します。
Pdfium.NET SDK は PDF 操作のための堅牢なツールですが、IronPDF は現代的な HTML、CSS、および JavaScript のレンダリングを含め、直接 HTML から PDF に変換するためのネイティブサポートを提供します。 IronPDFは、HtmlToPdf.RenderHtmlAsPdf()のような組み込みメソッドを使用してワークフローを簡素化し、開発者にとってより迅速かつ効率的にします。
請求書、レポートの作成、またはウェブコンテンツのアーカイブに関して、IronPDFは開発者にプロフェッショナルな結果を迅速かつ効率的に達成するために必要なツールを提供します。
IronPDF は、HTML から PDF へのワークフローで信頼性、スケーラビリティ、および使いやすさを重視する開発者にとって実用的な選択肢です。