本文将指导如何使用 C# 将 URL 转换为 PDF。您可以按照此处的说明设置环境、获取步骤列表和示例代码,以使用 C# 将 URL 转换为 PDF。还共享了输出 PDF 页面的自定义设置,以创建所需的输出。
使用C#将URL转换为PDF的步骤
- 设置环境使用 Aspose.PDF for .NET 将 URL 转换为 PDF
- 定义转换为 PDF 的 URL 和 HtmlLoadOptions 用于配置输出 PDF 页面
- 创建用于发出 HTTP 请求的 HttpClient 对象
- 向 URL 发送 Get 请求并等待响应
- 确保请求成功并以流的形式获取响应内容
- 从流中创建 PDF 文档并将其保存在磁盘上
这些步骤描述了使用 C# 将网站页面转换为 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# 将网页链接转换为 PDF。您可以使用 HtmlLoadOptions 类应用更多设置,例如嵌入字体的标志、设置输入编码、页面布局选项、页边距等。您可以使用 WarningHandler 设置回调来处理警告。
本教程指导我们使用 C# 更改 PDF 文档链接。若要在 PDF 文件中添加超链接,请参阅有关 如何使用 C# 在 PDF 中添加超链接 的文章。