aspose转pdf横版_使用Aspose将HTML转换为PDF

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

Am i missing something? Any kind of help is greatly appreciated.

Thanks

解决方案

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

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.

Convert HTML to PDF (new DOM)

HtmlLoadOptions options = new HtmlLoadOptions(resourcesPath);

Document pdfDocument = new Document(inputPath, options);

pdfDocument.Save("outputPath");

Convert Webpage to PDF(new 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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值