c# - 使用 Aspose 将 HTML 转换为 PDF

标签 c# asp.net .net

我是 Aspose 的新手,但我已经成功地将几种文件格式转换为 PDF,但我对 HTML 到 PDF 的转换感到震惊。我能够成功地将 HTML 文件转换为 PDF,但 CSS 部分未呈现为生成的 PDF。对此有任何想法吗?我将 www.google.com 保存为我的输入 HTML 文件。这是我的 Controller 代码。

using Aspose.Pdf.Generator


Pdf pdf = new Pdf();
pdf.HtmlInfo.CharSet = "UTF-8";
Section section = pdf.Sections.Add();
StreamReader r = File.OpenText(@"Local HTML File Path");
Text text2 = new Aspose.Pdf.Generator.Text(section, r.ReadToEnd());
pdf.HtmlInfo.ExternalResourcesBasePath = "Local HTML File Path";
text2.IsHtmlTagSupported = true;
text2.IsFitToPage = true;
section.Paragraphs.Add(text2);
pdf.Save(@"Generated PDF File Path");

我错过了什么吗?非常感谢任何形式的帮助。

谢谢

最佳答案

我叫 Tilal Ahmad,是 Aspose 的开发人员布道师。

请使用新的 DOM 方法(Aspose.Pdf.Document)进行 HTML 到 PDF 的转换。在这种渲染外部资源(CSS/图像/字体)的方法中,您需要将资源路径传递给 HtmlLoadOptions() 方法。请检查以下文档链接。

将 HTML 转换为 PDF(新 DOM)

HtmlLoadOptions options = new HtmlLoadOptions(resourcesPath);
Document pdfDocument = new Document(inputPath, options);
pdfDocument.Save("outputPath");

网页转PDF(新DOM)
// Create a request for the URL.
WebRequest request = WebRequest.Create("https:// En.wikipedia.org/wiki/Main_Page");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Time out in miliseconds before the request times out
// Request.Timeout = 100;

// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
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/");


// Load HTML file
Document pdfDocument = new Document(stream, options);

options.PageInfo.IsLandscape = true;
// Save output as PDF format
pdfDocument.Save(outputPath);

关于c# - 使用 Aspose 将 HTML 转换为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36629173/

相关文章:

c# - 使用 XML 获取所有同名元素的内容?

c# - 重复执行一段代码而没有超时。窗口服务

c# - string.Empty 与 ""- 这改变了吗?

c# - 智能 ASCII 字符串表示

asp.net - 可以在 Web 应用程序中使用 WPF 程序集吗?

c# - 无法再在 visual studio 2019 中添加 C# 类 - 不会链接到主文件

c# - XNA 游戏启动的表单中带有 RichTextBox.ScrollToCaret 的 AccessViolationException

c# - 使用云服务对 Web 应用程序进行压力测试

c# - 如何使用 Angular 取消 .Net Core Web API 请求?

javascript - 如何使用 jquery 为下拉列表赋值