IRON SUITEの使用

C# における .NET 開発者向けの HTML から PDF への変換 (究極のガイド)

2024年12月15日
共有:

イントロダクション

現代のウェブ主導の世界では、HTMLコンテンツをPDFドキュメントに変換する機能は、多くのアプリケーションにとって重要な特徴です。 レポートや請求書の作成、ウェブページのオフライン保存など、HTMLをPDFに変換することは、ワークフローの効率化やユーザーエクスペリエンスの向上において重要な役割を果たします。 .NET開発者にとって、この変換を処理するための適切なツールを選択することは、アプリケーションの効率と品質に大きな影響を与える可能性があります。

この記事では、C#でHTMLをPDFに変換する方法を次のトピックで説明します。

  1. なぜHTMLからPDFへのツールを比較するのか?

  2. IronPDF: HTML から PDF への変換

  3. Aspose: HTMLからPDFへの変換

  4. iText7: HTMLからPDFへの変換

  5. wkhtmltopdf: HTMLからPDFへの変換

  6. PuppeteerSharp: HTMLからPDFへの変換

  7. 結論 IronPDFを選ぶ理由

    最終的には、IronPDFが開発者にとって使いやすく、効率的なHTMLからPDFへのコンバーターとして際立っている理由が理解できるでしょう。

なぜHTMLをPDFツールと比較するのか?

適切なHTMLからPDFへの変換ツールを選択することは、アプリケーションがパフォーマンス、品質、およびコストの要件を満たすために不可欠です。 さまざまな機能や能力を提供する多数のオプションが利用可能であるため、十分な比較を行うことで、情報に基づいた意思決定を助けます。 以下は考慮すべき主要な評価基準です:

  • 統合の複雑さ: ライブラリが既存の.NETプロジェクトにどれだけ容易に統合できるか。
  • コードの簡潔さ: ライブラリを使用してコードを記述および保守することの容易さ。
  • レンダリングの精度: 複雑なHTML、CSS、およびJavaScriptを正確にレンダリングする能力。
  • スケールでのパフォーマンス: ライブラリが高負荷と大規模なPDF生成時にどのようにパフォーマンスを発揮するか。
  • ライセンスとコスト効果: プロジェクトの予算に適した価格モデルとライセンス条件。

    これらの要素を評価することで、技術要件に合うだけでなく、プロジェクトの予算制約にも合ったツールを選択することができます。

IronPDF: HTMLからPDFへの変換

.NET開発者向けHTML to PDFのC#での使用法(究極ガイド):図1

IronPDFは、HTMLをPDFに変換するためのフル機能の.NETライブラリです。 HTML文字列、ローカルHTMLファイル、URLをサポートしており、幅広いユースケースに対応しています。 以下は、IronPDF が各シナリオを処理する方法です。

HTML文字列をPDFに変換

IronPDF を使用すれば、文字列から PDF への変換は簡単です。 このアプローチは、動的コンテンツ生成や小さいHTMLスニペットに理想的です。

例:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        PDF.SaveAs("output.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        PDF.SaveAs("output.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>")
		PDF.SaveAs("output.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

C#でのHTMLからPDFへの変換(.NET開発者向け: 最終ガイド):図2

説明:

  1. ChromePdfRenderer: ChromePdfRendererクラスは、IronPDFでHTMLをPDFに変換するための主要なツールです。 ほとんどのユースケースを最小限の設定で処理するように事前設定されています。

  2. RenderHtmlAsPdf: このメソッドは、HTML文字列を入力として受け取り、PDFドキュメントを生成します。

  3. SaveAs: 生成されたPDFは指定されたパス(output.pdf)に保存されます。

ローカルHTMLファイルをPDFに変換

外部リソース(CSSやJavaScriptなど)を含むローカルHTMLファイルを変換する必要があるアプリケーションには、IronPDFが便利です。

例:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
        pdf.SaveAs("report.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
        pdf.SaveAs("report.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("template.html")
		pdf.SaveAs("report.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

HTMLファイルを入力

C#でのHTMLからPDFへの変換(.NET開発者向け究極のガイド): 図3

出力

C#でHTMLをPDFに変換する .NET開発者向け (究極のガイド): 図4

説明:

  • RenderHtmlFileAsPdf: ローカルのHTMLファイルを取り込み、PDFに変換します。
  • 外部のCSSやJavaScriptファイルなど、リンクされたリソースを自動的に処理します。

URLをPDFに変換

IronPDF は、特に JavaScript を使用するページを含む URL から動的なウェブコンテンツを変換する際に非常に強力です。

例:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com")
		pdf.SaveAs("url-to-pdf.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

.NET開発者のためのC#でHTMLをPDFに変換(究極のガイド):図5

説明:

  • RenderUrlAsPdf: URLコンテンツを取得し、JavaScriptでレンダリングされた要素を含めてPDFに変換します。

Aspose: HTMLからPDFへの変換

.NET開発者のためのC#でのHTMLからPDFへの変換(究極のガイド):図6

Aspose.PDFは、PDF操作のためのもう一つの強力なライブラリで、HTMLをPDFに変換する機能をサポートしています。 Asposeが各変換シナリオをどのように処理するか見てみましょう。

HTML文字列をPDFに変換

Asposeは、HTML文字列を変換する際にIronPDFと比較してもう少しセットアップが必要です。

例:

using Aspose.Html;
Document doc = new Document();
Page page = doc.getPages().add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().add(htmlFragment);
doc.save(dataDir + "HTMLStringUsingDOM.pdf");
using Aspose.Html;
Document doc = new Document();
Page page = doc.getPages().add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().add(htmlFragment);
doc.save(dataDir + "HTMLStringUsingDOM.pdf");
Imports Aspose.Html
Private doc As New Document()
Private page As Page = doc.getPages().add()
Private htmlFragment As New HtmlFragment("<h1>HTML String</h1>")
page.getParagraphs().add(htmlFragment)
doc.save(dataDir & "HTMLStringUsingDOM.pdf")
$vbLabelText   $csharpLabel

説明:

  • Document doc: 変換されたHTML文字列を保存する新しいドキュメントを作成します。
  • ページ page: この行は、作成した空のドキュメントに新しいページを追加します。
  • HtmlFragment htmlFragment: これは、変換しているHTML文字列です。
  • page.getParagraphs().add(htmlFragment): HTMLをドキュメントに追加します
  • doc.save: HTMLコンテンツをPDFドキュメントとして保存します。

ローカルHTMLファイルをPDFに変換

AsposeもローカルHTMLファイルをPDFに変換できますが、IronPDFよりも設定が多く必要です。

例:

using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
    using var document = new HTMLDocument("document.html");
    var options = new PdfSaveOptions();
    Converter.ConvertHTML(document, options, "output.pdf");
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
    using var document = new HTMLDocument("document.html");
    var options = new PdfSaveOptions();
    Converter.ConvertHTML(document, options, "output.pdf");
Imports Aspose.Html
Imports Aspose.Html.Converters
Imports Aspose.Html.Saving
	Private document = New HTMLDocument("document.html")
	Private options = New PdfSaveOptions()
	Converter.ConvertHTML(document, options, "output.pdf")
$vbLabelText   $csharpLabel

説明:

  • using var document = new HTMLDocument("document.html"): HTMLファイルをロードします。
  • var options: 新しい PdfSaveOptions オブジェクトを作成します
  • Converter.ConvertHTML(): HTMLをPDFに変換します。

URLをPDFに変換

AsposeはURLに対して同様の機能を提供していますが、追加の設定が必要です。

例:

using System.IO;
using System;
using System.Net;
using Aspose.Pdf;
string dataDir = "YOUR DOCUMENT DIRECTORY"; // Replace with your path
WebRequest request = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://en.wikipedia.org/wiki/");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf");
using System.IO;
using System;
using System.Net;
using Aspose.Pdf;
string dataDir = "YOUR DOCUMENT DIRECTORY"; // Replace with your path
WebRequest request = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://en.wikipedia.org/wiki/");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf");
Imports System.IO
Imports System
Imports System.Net
Imports Aspose.Pdf
Private dataDir As String = "YOUR DOCUMENT DIRECTORY" ' Replace with your path
Private request As WebRequest = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page")
request.Credentials = CredentialCache.DefaultCredentials
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Dim stream As New MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer))
Dim options As New HtmlLoadOptions("https://en.wikipedia.org/wiki/")
Dim pdfDocument As New Document(stream, options)
pdfDocument.Save(dataDir & "WebPageToPDF_out.pdf")
$vbLabelText   $csharpLabel

説明:

  • dataDir変数は、生成されたPDFが保存されるディレクトリを保持します。
  • WebRequestを作成してWikipediaのメインページURLにアクセスし、デフォルトの資格情報をリクエストに使用します。
  • GetResponse() メソッドはリクエストを送信し、HttpWebResponse としてレスポンスを取得します。
  • ストリームはレスポンスから取得され、StreamReaderがページのすべてのHTMLコンテンツをresponseFromServer文字列に読み込みます。
  • responseFromServerのHTMLコンテンツはバイト配列に変換され、その後MemoryStreamにロードされます。
  • HtmlLoadOptionsは、相対リンクやその他の設定のための基本URLを指定するために使用されます。
  • Aspose.Pdf.DocumentがHTMLを含むメモリストリームから作成され、ドキュメントは指定されたディレクトリにPDFとして保存されます。

iText7: HTMLからPDFへの変換

C#でHTMLをPDFに変換する .NET開発者向け(究極のガイド):図7

iText7は、HTMLからPDFへの変換もサポートする包括的なPDFライブラリです。 以下にiText7がさまざまなシナリオでどのように機能するかを示します。

HTML文字列をPDFに変換

iText7は、HTML文字列をPDF形式に変換するためにhtmlConverterクラスを使用します。

例:

public static String DEST = String.Format("{0}test-03.pdf", TARGET);
var html = "<h1>Hello World</h1>";
HtmlConverter.ConvertToPdf(html, new FileStream(dest, FileMode.Create));
public static String DEST = String.Format("{0}test-03.pdf", TARGET);
var html = "<h1>Hello World</h1>";
HtmlConverter.ConvertToPdf(html, new FileStream(dest, FileMode.Create));
Public Shared DEST As String = String.Format("{0}test-03.pdf", TARGET)
Private html = "<h1>Hello World</h1>"
HtmlConverter.ConvertToPdf(html, New FileStream(dest, FileMode.Create))
$vbLabelText   $csharpLabel

ローカルHTMLファイルをPDFに変換

iText7 は HtmlConverter.ConvertToPdf クラスを使用して HTML ファイルタイプを PDF に変換できます。

例:

using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("template.html", new FileStream("html-file-to-pdf.pdf", FileMode.Create));
    }
}
using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("template.html", new FileStream("html-file-to-pdf.pdf", FileMode.Create));
    }
}
Imports iText.Html2pdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		HtmlConverter.ConvertToPdf("template.html", New FileStream("html-file-to-pdf.pdf", FileMode.Create))
	End Sub
End Class
$vbLabelText   $csharpLabel

説明:

  • HtmlConverter: HTMLファイルを直接PDFに変換します。

URLをPDFに変換

iText7は、URLからのコンテンツ変換もサポートしています。

例:

using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("https://example.com", new FileStream("url-to-pdf.pdf", FileMode.Create));
    }
}
using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("https://example.com", new FileStream("url-to-pdf.pdf", FileMode.Create));
    }
}
Imports iText.Html2pdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		HtmlConverter.ConvertToPdf("https://example.com", New FileStream("url-to-pdf.pdf", FileMode.Create))
	End Sub
End Class
$vbLabelText   $csharpLabel

説明:

  • HtmlConverter: URLコンテンツを管理し、それをPDFに変換します。

wkhtmltopdf: HTMLをPDFに変換

HTML を PDF に変換 - C# for .NET 開発者向け(究極のガイド):図8

wkhtmltopdfは、Webkitレンダリングを使用してHTMLファイルをPDFに変換するコマンドラインツールです。 異なるシナリオでの動作方法は次のとおりです。

HTML文字列をPDFに変換

wkhtmltopdf は、HTML 文字列を最初にファイルに書き込むことで変換する必要があります。

例:

using System;
using System.IO;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // HTML string to be converted to PDF
        string html = "<html><body><h1>Hello, World!</h1></body></html>";
        // Write HTML string to temporary file
        string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
        File.WriteAllText(tempHtmlFile, html);
        // Set output PDF path
        string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        // Clean up the temporary HTML file
        File.Delete(tempHtmlFile);
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.IO;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // HTML string to be converted to PDF
        string html = "<html><body><h1>Hello, World!</h1></body></html>";
        // Write HTML string to temporary file
        string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
        File.WriteAllText(tempHtmlFile, html);
        // Set output PDF path
        string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        // Clean up the temporary HTML file
        File.Delete(tempHtmlFile);
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
Imports System
Imports System.IO
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' HTML string to be converted to PDF
		Dim html As String = "<html><body><h1>Hello, World!</h1></body></html>"
		' Write HTML string to temporary file
		Dim tempHtmlFile As String = Path.Combine(Path.GetTempPath(), "temp.html")
		File.WriteAllText(tempHtmlFile, html)
		' Set output PDF path
		Dim outputPdfFile As String = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf")
		' Execute wkhtmltopdf command
		Dim process As New Process()
		process.StartInfo.FileName = "wkhtmltopdf"
		process.StartInfo.Arguments = $"""{tempHtmlFile}"" ""{outputPdfFile}"""
		process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
		process.Start()
		process.WaitForExit()
		' Clean up the temporary HTML file
		File.Delete(tempHtmlFile)
		Console.WriteLine($"PDF saved to: {outputPdfFile}")
	End Sub
End Class
$vbLabelText   $csharpLabel

説明:

  • wkhtmltopdf は入力ファイルを必要とするため、まずHTML文字列を一時ファイル (temp.html) に書き込みます。
  • その後、Processクラスを使用してwkhtmltopdfコマンドを実行し、一時HTMLファイルのファイルパスと目的の出力PDFパスを引数として渡します。
  • 変換後、クリーンアップのために一時的なHTMLファイルを削除します。

ローカルHTMLファイルをPDFに変換

ローカルHTMLファイルをPDFに変換するために、wkhtmltopdfを使用する場合、HTMLファイルのファイルパスを直接指定することができます。

例:

using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // Path to the local HTML file
        string htmlFilePath = @"C:\path\to\your\template.html";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // Path to the local HTML file
        string htmlFilePath = @"C:\path\to\your\template.html";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
Imports System
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Path to the local HTML file
		Dim htmlFilePath As String = "C:\path\to\your\template.html"
		' Path for the output PDF file
		Dim outputPdfFile As String = "C:\path\to\output\html-file-to-pdf.pdf"
		' Execute wkhtmltopdf command
		Dim process As New Process()
		process.StartInfo.FileName = "wkhtmltopdf"
		process.StartInfo.Arguments = $"""{htmlFilePath}"" ""{outputPdfFile}"""
		process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
		process.Start()
		process.WaitForExit()
		Console.WriteLine($"PDF saved to: {outputPdfFile}")
	End Sub
End Class
$vbLabelText   $csharpLabel

説明:

  • この例では、単にローカルのHTMLファイル(template.html)のパスとPDFの出力パスを提供しています。
  • wkhtmltopdf はローカルファイルを直接処理するため、コマンドが簡単です。

URLをPDFに変換

URLをPDFに変換するのは、wkhtmltopdfを使えば簡単です。 コマンドにURLを直接渡すだけです。

例:

using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://example.com";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://example.com";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
Imports System
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' URL to be converted to PDF
		Dim url As String = "https://example.com"
		' Path for the output PDF file
		Dim outputPdfFile As String = "C:\path\to\output\url-to-pdf.pdf"
		' Execute wkhtmltopdf command
		Dim process As New Process()
		process.StartInfo.FileName = "wkhtmltopdf"
		process.StartInfo.Arguments = $"""{url}"" ""{outputPdfFile}"""
		process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
		process.Start()
		process.WaitForExit()
		Console.WriteLine($"PDF saved to: {outputPdfFile}")
	End Sub
End Class
$vbLabelText   $csharpLabel

説明:

  • この例では、wkhtmltopdf は直接URLを入力として受け入れます。
  • URLはwkhtmltopdfに引数として渡され、出力は指定されたパスにPDFとして保存されます。

PuppeteerSharp:HTMLからPDFへの変換

C#でのHTMLからPDFへの変換: .NET開発者向け究極のガイド: 図9

PuppeteerSharpは、ヘッドレスChromeまたはChromiumを自動化するための強力なツールであり、ウェブスクレイピングや複雑なウェブページのレンダリングに頻繁に使用されます。 以下は、PuppeteerSharpを使用してHTMLをPDFに変換する例です。

HTML文字列をPDFに変換

Puppeteerは完全なページをレンダリングするために設計されているため、HTML文字列を変換するには、ファイルに書き込むか、ブラウザで直接レンダリングする必要があります。

例:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
        await page.SetContentAsync(htmlContent);
        // Save the page as a PDF
        await page.PdfAsync("html-string-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
        await page.SetContentAsync(htmlContent);
        // Save the page as a PDF
        await page.PdfAsync("html-string-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()
		Dim htmlContent As String = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>"
		Await page.SetContentAsync(htmlContent)
		' Save the page as a PDF
		Await page.PdfAsync("html-string-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
$vbLabelText   $csharpLabel

説明:

  • Puppeteer.LaunchAsync: ヘッドレスモードで新しいChromiumインスタンスを起動します。
  • page.SetContentAsync: HTML文字列をブラウザページにロードします。
  • page.PdfAsync: 読み込んだHTMLをPDFに変換し、ファイルに保存します。

ローカルHTMLファイルをPDFに変換

PuppeteerSharpを使用してローカルHTMLファイルをPDFに変換するには、ファイルをヘッドレスブラウザにロードしてPDFを生成できます。

例:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Load the local HTML file
        await page.GoToAsync("file:///path/to/your/template.html");
        // Save the page as a PDF
        await page.PdfAsync("html-file-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Load the local HTML file
        await page.GoToAsync("file:///path/to/your/template.html");
        // Save the page as a PDF
        await page.PdfAsync("html-file-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()
		' Load the local HTML file
		Await page.GoToAsync("file:///path/to/your/template.html")
		' Save the page as a PDF
		Await page.PdfAsync("html-file-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
$vbLabelText   $csharpLabel

説明:

  • page.GoToAsync: ローカルHTMLファイルをロードします(正しい[file://]()パスを使用してください)。
  • page.PdfAsync: ローカルHTMLファイルの内容をPDFに変換します。

URLをPDFに変換

URLをPDFに変換することは、PuppeteerSharpの主要機能の1つであり、JavaScriptを含む複雑なページを処理できる能力を備えています。

例:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Navigate to the URL
        await page.GoToAsync("https://example.com");
        // Save the page as a PDF
        await page.PdfAsync("url-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Navigate to the URL
        await page.GoToAsync("https://example.com");
        // Save the page as a PDF
        await page.PdfAsync("url-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()
		' Navigate to the URL
		Await page.GoToAsync("https://example.com")
		' Save the page as a PDF
		Await page.PdfAsync("url-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
$vbLabelText   $csharpLabel

説明:

  • page.GoToAsync: 指定されたURLに移動します。
  • page.PdfAsync: URLのウェブページをPDFに変換して保存します。

IronPDFを選ぶ理由

IronPDFは、その使いやすさ、柔軟性、および.NETアプリケーションとのシームレスな統合によって際立っています。 実装は簡単で、HTML、CSS、およびJavaScriptのレンダリングをサポートし、追加の設定や外部依存関係を必要としません。 HTMLからPDFへの変換を超えて、IronPDFはさまざまなファイルタイプからPDFドキュメントを作成し、既存のPDFドキュメントを編集および追加し、透かしを入れ、PDFファイルのセキュリティなど、幅広い機能を提供します! このライブラリの実際の動作を見るには、その機能を実演する使用ガイドをぜひご覧ください。

結論

C#でHTMLをPDFファイルに変換する際には、独自の機能と能力を提供する強力なツールがいくつか利用可能です。 IronPDFAsposeiText7wkhtmltopdf、およびPuppeteerSharpはすべて、HTMLコンテンツをプロフェッショナルグレードのPDFドキュメントに変換するための強力なソリューションを提供します。 ただし、プロジェクトに適したツールを選択するには、統合のしやすさ、動的コンテンツのサポート、パフォーマンス、柔軟性といった要因に依存します。

.NET開発者向けのC#でのHTMLからPDFへの変換(究極のガイド):図10

  • IronPDF は、そのシンプルさ、.NET との直接統合、および JavaScript レンダリング ページを含む複雑な HTML を処理する能力で際立っています。 開発者が簡単に使えるソリューションを求めている場合には、最小限のセットアップで完璧です。
  • Aspose は広範なPDF操作機能を提供しますが、HTMLからPDFへの変換機能には、特にローカルファイルや外部リソースの処理において、より多くの設定が必要です。
  • iText7は、PDFドキュメントを作成しようとする人々にとって堅実な基盤を提供しますが、特に動的コンテンツのHTMLをPDFに変換するには追加のコーディングが必要な場合があります。 カスタムPDF操作が必要なプロジェクトにとっては素晴らしい選択です。
  • wkhtmltopdfは、コマンドラインインターフェースを使用した基本的なHTMLからPDFへの変換に最適ですが、完全な.NETライブラリの統合性と柔軟性に欠けています。
  • PuppeteerSharpは、ヘッドレスChromeを活用して複雑で動的なウェブページをレンダリングし、特にJavaScriptを多用するコンテンツをPDFに変換する際に最適なツールです。

    ほとんどの.NET開発者がオールインワンでわかりやすいソリューションを求めている場合、IronPDFを体験して、その強力な機能をご自身で体感してください。

    最終的に、適切なツールはあなたの特定の要件に依存しますが、ここで議論されたオプションがあれば、プロジェクトに最適なソリューションを見つけるための十分な準備が整っています。

< 以前
HTML から PDF への C# - IronPDF を用いた完全ガイド
次へ >
C#でCSHTMLをPDFに変換する方法