HTML を PDF に変換する(.NET)

概要

この記事では、C# を使用して HTML を PDF に変換する方法を説明します。以下のトピックをカバーしています。

以下のコードスニペットは、Aspose.PDF.Drawing ライブラリでも動作します。

Aspose.PDF for .NET は、既存の HTML ドキュメントをシームレスに PDF に変換できる PDF 操作 API です。HTML を PDF に変換するプロセスは柔軟にカスタマイズできます。

HTML を PDF に変換

以下の C# コードサンプルは、HTML ドキュメントを PDF に変換する方法を示しています。

HTML を PDF に変換

  1. HtmlLoadOptions クラスのインスタンスを作成します。
  2. Document オブジェクトを初期化します。
  3. Document.Save() メソッドを呼び出して、出力 PDF ドキュメントを保存します。
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDF()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Load the HTML file into a document using HtmlLoadOptions
    var options = new Aspose.Pdf.HtmlLoadOptions();

    // Open HTML document
    using (var document = new Aspose.Pdf.Document(dataDir + "test.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "ConvertHTMLtoPDF_out.pdf");
    }
}

HTML から PDF への高度な変換

HTML 変換エンジンには、変換プロセスを制御できるいくつかのオプションがあります。

メディアクエリのサポート

メディアクエリは、異なるデバイス向けにカスタマイズされたスタイルシートを提供する一般的な手法です。デバイスタイプは、HtmlMediaType プロパティで設定できます。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFAdvancedMediaType()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Load the HTML file into a document using HtmlLoadOptions with Print media type
    var options = new HtmlLoadOptions
    {
        // Set Print or Screen mode
        HtmlMediaType = Aspose.Pdf.HtmlMediaType.Print
    };

    // Open HTML document
    using (var document = new Aspose.Pdf.Document(dataDir + "test.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "ConvertHTMLtoPDFAdvancedMediaType_out.pdf");
    }
}

フォント埋め込みの有効化(無効化)

HTML ページはしばしばフォント(ローカルフォルダーのフォント、Google フォントなど)を使用します。IsEmbedFonts プロパティを使用して、ドキュメントへのフォント埋め込みを制御できます。

 // For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
 private static void ConvertHTMLtoPDFAdvancedEmbedFonts()
 {
     // The path to the documents directory
     var dataDir = RunExamples.GetDataDir_AsposePdf();

     // Load the HTML file into a document using HtmlLoadOptions with the font embedding option set
     var options = new Aspose.Pdf.HtmlLoadOptions
     {
         // Disable font embedding
         IsEmbedFonts = false
     };

     // Open HTML document
     using (var document = new Aspose.Pdf.Document(dataDir + "test_fonts.html", options))
     {
         // Save PDF document
         document.Save(dataDir + "ConvertHTMLtoPDFAdvanced_EmbedFonts_out.pdf");
     }
 }

外部リソースの読み込み管理

変換エンジンは、HTML ドキュメントに関連する特定のリソースの読み込みを制御できる仕組みを提供します。
HtmlLoadOptions クラスには、リソースローダーの動作を定義できる CustomLoaderOfExternalResources プロパティがあります。
すべての PNG 画像を単一の画像 test.jpg に置き換え、他のリソースの外部 URL を内部のものに置き換える必要があるとします。
このためにカスタムローダー SamePictureLoader を定義し、CustomLoaderOfExternalResources にその名前を指定します。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFAdvanced_DummyImage()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Load the HTML file into a document with a custom resource loader for external images
    var options = new Aspose.Pdf.HtmlLoadOptions
    {
        CustomLoaderOfExternalResources = SamePictureLoader
    };

    // Open HTML document
    using (var document = new Aspose.Pdf.Document(dataDir + "test.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "html_test.pdf");
    }
}

private static Aspose.Pdf.LoadOptions.ResourceLoadingResult SamePictureLoader(string resourceURI)
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();
    Aspose.Pdf.LoadOptions.ResourceLoadingResult result;

    if (resourceURI.EndsWith(".png"))
    {
        byte[] resultBytes = File.ReadAllBytes(dataDir + "test.jpg");
        result = new Aspose.Pdf.LoadOptions.ResourceLoadingResult(resultBytes)
        {
            // Set MIME Type
            MIMETypeIfKnown = "image/jpeg"
        };
    }
    else
    {
        result = new Aspose.Pdf.LoadOptions.ResourceLoadingResult(GetContentFromUrl(resourceURI));
    }
    return result;
}

private static byte[] GetContentFromUrl(string url)
{
    var httpClient = new System.Net.Http.HttpClient();
    return httpClient.GetByteArrayAsync(url).GetAwaiter().GetResult();
}

すべての HTML コンテンツを単一ページにレンダリング

Aspose.PDF for .NET は、HTML ファイルを PDF 形式に変換する際に、すべてのコンテンツを単一ページにレンダリングする機能を提供します。たとえば、出力サイズが 1 ページを超える HTML コンテンツがある場合、出力データを単一の PDF ページにレンダリングするオプションを使用できます。
このオプションを有効にするために、HtmlLoadOptions クラスに IsRenderToSinglePage フラグが追加されました。
以下のコードスニペットは、この機能の使用方法を示しています。

 // For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
 private static void ConvertHTMLtoPDFAdvancedSinglePageRendering()
 {
     // The path to the documents directory
     var dataDir = RunExamples.GetDataDir_AsposePdf();

     // Initialize HtmlLoadOptions
     var options = new Aspose.Pdf.HtmlLoadOptions
     {
         // Set Render to single page property
         IsRenderToSinglePage = true
     };

     // Open PDF document
     using (var document = new Aspose.Pdf.Document(dataDir + "HTMLToPDF.html", options))
     {
         // Save PDF document
         document.Save(dataDir + "RenderContentToSamePage_out.pdf");
     }
 }

SVG データを含む HTML のレンダリング

Aspose.PDF for .NET は、HTML ページを PDF ドキュメントに変換する機能を提供します。HTML ではページに SVG グラフィック要素をタグとして追加できるため、Aspose.PDF もそのようなデータを結果の PDF ファイルに変換することをサポートしています。以下のコードスニペットは、SVG グラフィックタグを含む HTML ファイルをタグ付き PDF ドキュメントに変換する方法を示しています。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFWithSVG()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Initialize HtmlLoadOptions
    var options = new Aspose.Pdf.HtmlLoadOptions(Path.GetDirectoryName(dataDir + "HTMLSVG.html"));

    // Initialize Document object
    using (var document = new Aspose.Pdf.Document(dataDir + "HTMLSVG.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "RenderHTMLwithSVGData_out.pdf");
    }
}

HTML タグから論理構造を作成

アクセシビリティ要件を満たすために、PDF ドキュメントには、読み順を定義し、スクリーンリーダー向けに文書の図示部分を説明する代替テキストを提供し、コンテンツの階層構造をマークアップする論理構造要素が含まれるべきです。
多くの HTML ドキュメントはすでにこの種の論理構造を含んでいます。Aspose.PDF は、HTML‑to‑PDF 変換時にそれを保持し、PDF に転送できます。
HtmlLoadOptions.CreateLogicalStructure プロパティを true に設定すると、PDF の論理構造要素を使用して元の HTML ドキュメントの構造を再現できます。

Web ページを PDF に変換

Web ページの変換は、ローカルの HTML ドキュメントを変換する場合とは若干異なります。Web ページの内容を PDF 形式に変換するには、まず HttpClient インスタンスを使用して HTML ページの内容を取得し、Stream オブジェクトを作成してその内容を Document オブジェクトに渡し、PDF 形式で出力をレンダリングします。

Web サーバー上でホストされている Web ページを PDF に変換する場合:

Web ページを PDF に変換

  1. HttpClient オブジェクトを使用してページの内容を読み取ります。
  2. HtmlLoadOptions オブジェクトをインスタンス化し、ベース URL を設定します。
  3. ストリームオブジェクトを渡しながら Document オブジェクトを初期化します。
  4. 必要に応じて、ページサイズや向きを設定します。
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFAdvanced_WebPage()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    const string url = "https://en.wikipedia.org/wiki/Aspose_API";

    // Set page size A3 and Landscape orientation;   
    var options = new Aspose.Pdf.HtmlLoadOptions(url)
    {
        PageInfo =
        {
            Width = 842,
            Height = 1191,
            IsLandscape = true
        }
    };

    // Load the web page content as a stream and create a PDF document
    using (var document = new Aspose.Pdf.Document(GetContentFromUrlAsStream(url), options))
    {
        // Save PDF document
        document.Save(dataDir + "html_test.pdf");
    }
}

private static Stream GetContentFromUrlAsStream(string url, System.Net.ICredentials credentials = null)
{
    using (var handler = new System.Net.Http.HttpClientHandler { Credentials = credentials })
    using (var httpClient = new System.Net.Http.HttpClient(handler))
    {
        return httpClient.GetStreamAsync(url).GetAwaiter().GetResult();
    }
}

Web ページから PDF への変換のための認証情報の提供

場合によっては、認証とアクセス権が必要な HTML ファイルの変換を行う必要があります。これにより、認可されたユーザーのみがページ内容を取得できます。また、HTML 内で参照されているリソース/データが認証を必要とする外部サーバーから取得されるシナリオも含まれます。この要件に対応するため、ExternalResourcesCredentials プロパティが HtmlLoadOptions クラスに追加されました。以下のコードスニペットは、HTML ファイルを PDF に変換する際に、HTML とその関連リソースのリクエストに認証情報を渡す手順を示しています。

 // For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
 private static void ConvertHTMLtoPDFAdvancedAuthorized()
 {
     // The path to the documents directory
     var dataDir = RunExamples.GetDataDir_AsposePdf();

     const string url = "http://httpbin.org/basic-auth/user1/password1";
     var credentials = new System.Net.NetworkCredential("user1", "password1");

     var options = new Aspose.Pdf.HtmlLoadOptions(url)
     {
         ExternalResourcesCredentials = credentials
     };

     using (var document = new Aspose.Pdf.Document(GetContentFromUrlAsStream(url, credentials), options))
     {
         // Save PDF document
         document.Save(dataDir + "HtmlTest_out.pdf");
     }
 }

private static Stream GetContentFromUrlAsStream(string url, System.Net.ICredentials credentials = null)
{
    using (var handler = new System.Net.Http.HttpClientHandler { Credentials = credentials })
    using (var httpClient = new System.Net.Http.HttpClient(handler))
    {
        return httpClient.GetStreamAsync(url).GetAwaiter().GetResult();
    }
}

MHTML を PDF に変換

MHTML は、MIME HTML の略で、画像、Flash アニメーション、Java アプレット、音声ファイルなど、通常は外部リンクで表されるリソースと HTML コードを単一ファイルに結合するために使用されるウェブページアーカイブ形式です。MHTML ファイルの内容は、MIME タイプ multipart/related を使用して、HTML 電子メールメッセージのようにエンコードされます。Aspose.PDF for .NET は HTML ファイルを PDF 形式に変換でき、バージョン 9.0.0 のリリースに伴い、MHTML ファイルを PDF 形式に変換する新機能を導入しました。次のコードスニペットは、C# で MHTML ファイルを PDF 形式に変換する方法を示しています。

MHTML を PDF に変換

  1. MhtLoadOptions クラスのインスタンスを作成します。
  2. Document オブジェクトを初期化します。
  3. Document.Save() メソッドを呼び出して、出力 PDF ドキュメントを保存します。
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertMHTtoPDF()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Initialize MhtLoadOptions with page setup
    var options = new Aspose.Pdf.MhtLoadOptions()
    {
        PageInfo = { Width = 842, Height = 1191, IsLandscape = true }
    };

    // Initialize Document object using the MHT file and options
    using (var document = new Aspose.Pdf.Document(dataDir + "fileformatinfo.mht", options))
    {
        // Save PDF document
        document.Save(dataDir + "MhtmlTest_out.pdf");
    }
}