HTMLをPDFに変換する .NET

概要

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

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

形式: HTML

形式: MHTML

形式: Webページ

C# HTMLをPDFに変換

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

HTMLをPDFに変換

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

手順: C#で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 Fontsなど)を使用することがよくあります。ドキュメント内のフォントの埋め込みを制御するために、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();
}

ウェブページをPDFに変換

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

ウェブサーバーにホストされているウェブページをPDFに変換する場合:

手順: C#で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();
    }
}

ウェブページをPDFに変換するための資格情報を提供する

時々、認証とアクセス権が必要なHTMLファイルの変換を行う必要があります。これにより、認証されたユーザーのみがページの内容を取得できるようになります。また、HTML内で参照されるリソースやデータが外部サーバーから取得されるシナリオも含まれます。これに対応するために、HtmlLoadOptionsクラスにExternalResourcesCredentialsプロパティが追加されました。以下のコードスニペットは、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();
    }
}

すべての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");
    }
}

MHTMLをPDFに変換

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

手順: C#で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");
    }
}

参照

この記事では、これらのトピックもカバーしています。コードは上記と同じです。

形式: HTML

形式: MHTML

形式: ウェブページ