ASP.Net有ReportViewer
可用于显示PDF文件的服务器控件。
有关此功能的大部分文档都是关于如何生成报告并将其导出到PDF。 MSDN确实不是很有帮助。我想每个人都依靠Adobe Reader而不是寻找替代品?
但是它也有可能导致导入并显示PDF。此代码似乎为this user工作:
public static void RenderToPdf(ReportViewer reportViewer, Boolean forceDownload)
{
string path = (string.IsNullOrEmpty(reportViewer.LocalReport.ReportPath)) ? reportViewer.ServerReport.ReportPath : reportViewer.LocalReport.ReportPath;
RenderToPdf(reportViewer, forceDownload, System.IO.Path.GetFileNameWithoutExtension(path));
}
public static void RenderToPdf(ReportViewer reportViewer, Boolean forceDownload, string fileNameWithoutExtension)
{
HttpContext context = HttpContext.Current;
if (!context.Response.Buffer)
{
return; //can not clear the buffer, so exit
}
//define out properties
Warning[] warnings;
string mimeType, encoding, fileNameExtension;
string[] streams;
//get pdf content
Byte[] pdfContent = reportViewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
//cancel and clear the existing output!
context.Response.Clear();
context.Response.ContentType = "application/pdf";
//add a header so that the user can save the target as a downloaded file
if (forceDownload)
{
context.Response.AddHeader("Content-disposition", string.Format("attachment; filename={0}.pdf", fileNameWithoutExtension));
}
context.Response.BinaryWrite(pdfContent);
context.Response.End();
}
来源
2012-03-10 15:45:55
DOK
我不知道ASP.NET,但我认为你使用Server.Transfer时得到乱码的原因可能是你没有将响应的内容类型头设置为'application/pdf' - 或者您? :) – Daan 2012-03-10 15:30:40
我明白你的意思(从概念的角度来看),但对我来说(从功能的角度来看)是没有意义的。点击指向PDF的标签并执行Server.Transfer('/ file.pdf')之间的区别是什么?第一个似乎有效,但第二个不行。如果我告诉浏览器加载PDF文件,它不应该从文件扩展名中找出MIME类型吗?另外,在执行Server.Transfer时何时/如何设置内容类型标题? (如果你不是ASP.NET开发人员,你可能不知道。) – mbm29414 2012-03-10 21:17:00
啊,你正在做一个Server.Transfer到.PDF文件?我以为你正在转移到另一个显示PDF内联的ASP.NET脚本,就像下面Rich Andrews的回答一样。在这种情况下,您需要在脚本中设置内容类型,如您在答案中所看到的那样:) – Daan 2012-03-10 21:31:45