2016-04-14 105 views
1

我是Aspose的新手,但我已经成功地将几种文件格式转换为PDF格式,但我对HTML转换为PDF格式非常感兴趣。我能够成功将HTML文件转换为PDF,但CSS部分不会渲染到生成的PDF中。对此有何想法?我将www.google.com保存为我的输入HTML文件。这是我的控制器代码。使用Aspose进行HTML到PDF转换

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

我错过了什么吗?任何形式的帮助,不胜感激。

感谢

回答

0

尝试在每个样式标签

<style media="print"> 

使用媒体属性,然后提供的HTML文件到您的Aspose.Pdf发电机。

+0

感谢您的答复,但没有帮助。 –

3

我的名字是Tilal Ahmad,我是Aspose的开发者传道人。

请使用新的DOM方法(Aspose.Pdf.Document)进行HTML到PDF的转换。在这种渲染外部资源(CSS/Images/Fonts)的方法中,您需要将资源路径传递给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); 
+0

它会将XHTML转换为PDF吗? –

+1

@Mike,是的新DOM方法支持XHTML转PDF。您需要传递XHTML文件,而不是HTML/HTM。如果您的文件正在使用某些外部资源,则将该路径传递给HtmlLoadOptions()。 –

+0

@TilalAhmad:请你更新你的答案。链接被破坏。 – Grevling