我正在寻找最简单的方法,使用iTextSharp将当前查看的asp.net网页导出到PDF文档 - 它可以是它的截图或传递url来生成文档。示例代码将不胜感激。提前谢谢了!ASP.NET网页到PDF
1
A
回答
0
增加Darin在他的评论中所说的话。
您可以尝试使用wkhtmltopdf生成PDF文件。它将URL作为输入。这是我用于我的SO应用程序so2pdf。
0
这不是那么容易(或者我认为是这样),我有同样的问题,我不得不编写代码来生成PDF格式的确切页面。它取决于页面和使用的样式等,所以我创建每个元素的绘图。
对于一些项目我使用Winnovative HTML to PDF转换器,但它不是免费的。
0
给人以PDFSharp一试(在运行时生成的PDF文件),它是开源的库: http://pdfsharp.com/PDFsharp/index.php?option=com_content&task=view&id=27&Itemid=1
替代解决方案:http://www.bratched.com/en/component/content/article/76-how-to-convert-xhtml-to-pdf-in-c.html
1
在过去的项目中,我们使用Supergoo ABCPDF 来做你需要的东西,它工作得很好。您基本上为它提供一个url,并将HTML页面处理为PDF。
缺点是,它是一个授权软件,其成本与其相关,当同时导出大量大型PDF时,我们遇到了一些性能问题。
希望这会有所帮助!
0
WInnovative网站上有一个示例Convert the Current HTML Page to PDF,它正是这样做的。将当前查看的asp.net网页转换为PDF文档的相关C#代码是:
// Controls if the current HTML page will be rendered to PDF or as a normal page
bool convertToPdf = false;
protected void convertToPdfButton_Click(object sender, EventArgs e)
{
// The current ASP.NET page will be rendered to PDF when its Render method will be called by framework
convertToPdf = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (convertToPdf)
{
// Get the current page HTML string by rendering into a TextWriter object
TextWriter outTextWriter = new StringWriter();
HtmlTextWriter outHtmlTextWriter = new HtmlTextWriter(outTextWriter);
base.Render(outHtmlTextWriter);
// Obtain the current page HTML string
string currentPageHtmlString = outTextWriter.ToString();
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";
// Use the current page URL as base URL
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;
// Convert the current page HTML string a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(currentPageHtmlString, baseUrl);
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Convert_Current_Page.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
}
else
{
base.Render(writer);
}
}
为什么要使用iTextSharp执行此操作? iTextSharp无法将ASP.NET页面转换为PDF,也无法将HTML转换为PDF。这不是它的意思。它是为了从头开始创建PDF文件,你知道,你从一个新的文档开始,添加文本,图像等......因此,一种技术可能在于捕获页面的屏幕截图(询问关于如何做到这一点的另一个问题,这可能会由于重复的数量而关闭),然后使用iTextSharp生成一个PDF,其中包含表示页面渲染输出的.jpeg图像。 – 2011-03-02 19:10:24