使用Aspose将HTML转换为PDF [英] HTML to PDF conversion using Aspose

查看:2945
本文介绍了使用Aspose将HTML转换为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Aspose并不陌生,但是我已经成功地将几种文件格式转换为PDF,但是我对HTML到PDF的转换感到震惊。我能够将HTML文件成功转换为PDF,但是CSS部分未呈现为生成的PDF。有什么想法吗?我将www.google.com保存为输入HTML文件。这是我的控制器代码。

I am new to Aspose but I have successfully converted several file formats into PDF's but I am struck with HTML to PDF conversion. I am able to convert a HTML file into a PDF successfully but the CSS part is not rendering into the generated PDF. Any idea on this? I saved www.google.com as my input HTML file. Here is my controller code.

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的开发人员。

My name is Tilal Ahmad and I am developer evangelist at Aspose.

请使用新的DOM方法(Aspose.Pdf.Document)将HTML转换为PDF。在这种呈现外部资源(CSS / Images / Fonts)的方法中,您需要将资源路径传递给HtmlLoadOptions()方法。为此,请检查以下文档链接。

Please use new DOM approach(Aspose.Pdf.Document) for HTML to PDF conversion. In this approach to render external resources(CSS/Images/Fonts) you need to pass resources path to HtmlLoadOptions() method. Please check following documentation links for the purpose.

将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);

这篇关于使用Aspose将HTML转换为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆