ASP.NET将HTML转换为PDF

ASP.NET将HTML转换为PDF

问题描述:

我已经尝试了多个插件和c#类来尝试将我的asp.net项目上的HTML和CSS转换为pdf,即使使用的代码看起来很好,并且按钮点击适用于其他功能,我似乎无法得到任何HTML到PDF功能工作。有没有其他人遇到过这种情况,或知道是否有什么我错过了解决它?ASP.NET将HTML转换为PDF

这是我在C#中尝试了hiqpdf的最新代码:

protected void Print_Button_Click(object sender, EventArgs e) 
{ 


    HtmlToPdf htmlToPdfConverter = new HtmlToPdf(); 

    // set PDF page size, orientation and margins 
    htmlToPdfConverter.Document.PageSize = PdfPageSize.A4; 
    htmlToPdfConverter.Document.PageOrientation = PdfPageOrientation.Portrait; 
    htmlToPdfConverter.Document.Margins = new PdfMargins(0); 

    // convert HTML to PDF 
    htmlToPdfConverter.ConvertUrlToFile("http://localhost:51091/Printout","mcn.pdf"); 


} 
+0

这是什么意思,它不工作?错误?请更具体一些。 –

+0

Hi @SamiKuhmonen,运行代码时没有任何反应 – kehoewex86

它不是直接的方法theHiQpdf文档中说明,但该方法ConvertUrlToFile()在本地存储所产生的PDF文件在光盘上。在一些示例页面(转换URL和HTML代码以PDF)以下注释,可以发现:

 // ConvertUrlToFile() is called to convert the html document and save the resulted PDF into a file on disk 
     // Alternatively, ConvertUrlToMemory() can be called to save the resulted PDF in a buffer in memory 
     htmlToPdfConverter.ConvertUrlToFile(url, pdfFile); 

由于您的示例显示了一个按钮单击事件处理程序,很可能产生的文件,但不能用在HTTP返回响应。您必须将数据写入响应。方法ConvertToStream()ConvertToMemory应该派上用场。之前不要忘记使用Response.Clear()Response.ClearContent()Response.ClearHeader(),然后使用Flush() and Close()

您可能想要使用PDF pro lib HTML to PDF converter