C# を使用して URL を PDF に変換する

この記事では、C# を使用して URL を PDF に変換する 方法について説明します。ここの手順に従って、環境を設定し、C# を使用して URL を PDF に変換する ための手順の一覧とサンプル コードを取得できます。目的の出力を作成するために、出力 PDF ページのカスタム設定も共有されます。

C#を使用してURLをPDFに変換する手順

  1. Aspose.PDF for .NET を使用して URL を PDF に変換するように環境を設定します
  2. PDFへの変換用のURLと出力PDFページを構成するためのHtmlLoadOptionsを定義します。
  3. HTTPリクエストを行うためのHttpClientオブジェクトを作成する
  4. URLにGetリクエストを送信し、応答を待ちます。
  5. リクエストが成功したことを確認し、応答コンテンツをストリームとして取得します。
  6. ストリームからPDF文書を作成し、ディスクにsave保存します

これらの手順では、C# を使用して Web サイトのページを PDF に変換するプロセスについて説明します。出力 PDF ページ設定を定義し、HttpClient クラスのインスタンスを作成し、URL に Get 要求を送信し、応答ストリームを取得して、ページ設定を使用して Document オブジェクトに渡します。最後に、URL コンテンツから生成された出力 PDF をディスクに保存します。

C#を使用したURLリンクからPDFへの変換コード

// Importing required namespaces
using System;
using System.IO;
using System.Net.Http;
using Aspose.Pdf;
// Defining a namespace for the project
namespace HtmlToPdfConverter
{
// Main class of the program
class ConverterApp
{
// Entry point of the program
static void Main(string[] args)
{
// Initialize and apply Aspose.PDF license
License pdfLicense = new License();
pdfLicense.SetLicense("Aspose_License.lic");
// Convert an online HTML page to PDF
GeneratePdfFromWebPage();
}
// Method to fetch and convert an HTML webpage to a PDF document
private static void GeneratePdfFromWebPage()
{
// Define the webpage URL to be converted
const string webpageUrl = "https://docs.aspose.com/";
// Configure PDF page settings for conversion
var pdfOptions = new HtmlLoadOptions(webpageUrl)
{
PageInfo =
{
Width = 1200, // Setting custom page width
Height = 850, // Setting custom page height
IsLandscape = false // Keeping portrait orientation
}
};
// Fetch the webpage content and create a PDF document
using (var pdfDocument = new Document(FetchWebContentAsStream(webpageUrl), pdfOptions))
{
// Save the generated PDF file
pdfDocument.Save("Converted_WebPage.pdf");
}
}
// Method to retrieve the content of a webpage as a stream
static Stream FetchWebContentAsStream(string webpageUrl)
{
// Initialize HTTP client to make web requests
HttpClient httpClient = new HttpClient();
// Send a GET request and retrieve the response
HttpResponseMessage webResponse = httpClient.GetAsync(webpageUrl, HttpCompletionOption.ResponseHeadersRead).Result;
// Ensure the response was successful
webResponse.EnsureSuccessStatusCode();
// Return the webpage content as a stream
return webResponse.Content.ReadAsStreamAsync().Result;
}
}
}

このコードは、C# を使用して Web ページの リンク を PDF に変換する方法を示しています。HtmlLoadOptions クラスを使用して、フォントを埋め込むフラグ、入力エンコードの設定、ページ レイアウト オプション、ページ マージンなどの設定をさらに適用できます。WarningHandler を使用して、警告を処理するためのコールバックを設定できます。

このチュートリアルでは、C# を使用して PDF ドキュメントへのリンクを変更する 方法について説明しました。PDF ファイルにハイパーリンクを追加するには、C# を使用して PDF にハイパーリンクを追加する方法 の記事を参照してください。

 日本語