製品比較

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への変換

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

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

HTML文字列をPDFに変換

HTMLからの変換文字列をPDFに変換IronPDFで簡単です。 このアプローチは、動的コンテンツ生成や小さい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
VB   C#

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

説明:

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

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

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

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

アプリケーションで変換が必要な場合ローカルHTMLファイル (CSSやJavaScriptのような外部リソースで)、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
VB   C#

入力HTMLファイル

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

出力

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

**説明

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

URLをPDFに変換

IronPDFは、動的なWebコンテンツを変換する際に特に強力です。URL、JavaScriptを使用するページを含めて。

例:

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
VB   C#

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

**説明

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

Aspose: HTMLからPDFへの変換

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")
VB   C#

**説明

  • Document doc: 変換されたHTML文字列を保存するための新しいドキュメントを作成します。
  • ページページ: この行は、作成した空のドキュメントに新しいページを追加します。
  • HtmlFragment htmlFragment: これは変換しているHTML文字列です。
  • page.getParagraphs()追加(HTMLフラグメント): ドキュメントに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")
VB   C#

**説明

  • 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")
VB   C#

**説明

  • 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))
VB   C#

ローカル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
VB   C#

**説明

  • 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
VB   C#

**説明

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

wkhtmltopdf: HTMLをPDFに変換

C#でHTMLをPDFに変換 (.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
VB   C#

**説明

  • 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
VB   C#

**説明

  • この例では、ローカル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
VB   C#

**説明

  • この例では、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
VB   C#

**説明

  • 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
VB   C#

**説明

  • 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
VB   C#

**説明

  • 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 ドキュメントに変換するための優れたソリューションを提供します。 ただし、プロジェクトに適したツールを選択するには、統合のしやすさ、動的コンテンツのサポート、パフォーマンス、柔軟性といった要因に依存します。

C#での.NET開発者向け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強力な機能を自分で体験するために今日お試しください。

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

< 以前
C# PDF SDK比較(無料&有料ツール)
次へ >
APITemplate ioとIronPDFのC# PDFライブラリの比較