首页 > 代码库 > MVC中生成PDF并在web中显示
MVC中生成PDF并在web中显示
最近接到一个新需求,需要将原先下载到用户电脑的PDF报表文件显示在新开的网页页面中,用户自己选择在页面内嵌的PDF上进行另存和打印。
代码如下:
FastReport.Report rpt = MakeProposalReport(xxx,xxx,xxx,xxx,xxx); byte[] buffer = ExportPDFToByteArray(rpt); //刪除旧的PDF文件 DeleteTempPdfFile();
//取档名
string fName = MakeReportFileName();
string newFile = Path.Combine(Server.MapPath("~"), "Newfile", fName);
//创建PDF文件在服务器中,下次产报表前会删除之前的
CreatePDFFile(newFile, buffer); FileStream fs = new FileStream(newFile, FileMode.Open, FileAccess.Read); return File(fs, "application/pdf");
/// <summary> 將報表轉換成PDF格式後序列化到Buffer </summary> /// <param name="rpt"></param> /// <returns></returns> internal static byte[] ExportPDFToByteArray(FastReport.Report rpt, CompressPDFInfo inCompressInfo = null, string Password = null) { MemoryStream memStream = ExportPDFToStream(rpt, inCompressInfo, Password); if (!string.IsNullOrEmpty(Password)) { //encrypt pdf with aes-128 PdfReader reader = new PdfReader(memStream, Encoding.Default.GetBytes(Password)); using (MemoryStream encryptStream = new MemoryStream()) { PdfStamper stamper = new PdfStamper(reader, encryptStream); stamper.SetEncryption(PdfWriter.ENCRYPTION_AES_128, Password, Password, PdfWriter.ALLOW_ASSEMBLY | PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_FILL_IN | PdfWriter.ALLOW_MODIFY_ANNOTATIONS | PdfWriter.ALLOW_MODIFY_CONTENTS | PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS); stamper.Close(); return encryptStream.ToArray(); } } else { long size = memStream.Length; byte[] buffer = new byte[size]; memStream.Read(buffer, 0, (int)size); memStream.Dispose(); return buffer; }
}
public void CreatePDFFile(string newFile, byte[] buffer) { FileStream writeStream = new FileStream(newFile, FileMode.Create, FileAccess.Write); MemoryStream readStream = new MemoryStream(buffer); int Length = buffer.Length; int bytesRead = readStream.Read(buffer, 0, Length); while (bytesRead > 0) { writeStream.Write(buffer, 0, bytesRead); bytesRead = readStream.Read(buffer, 0, Length); } readStream.Close(); writeStream.Close(); }
/// <summary> 删除临时PDF文件 </summary> /// <returns></returns> public void DeleteTempPdfFile() { var fileTempPath = Server.MapPath("~/") + "//Newfile//"; string[] files = Directory.GetFiles(fileTempPath, "*.pdf"); FileInfo fi; foreach (var file in files) { fi = new FileInfo(file); fi.Delete(); } }
重点在于
FileStream fs = new FileStream(newFile, FileMode.Open, FileAccess.Read);
没有这行代码,浏览器上无法显示PDF内容。
MVC中生成PDF并在web中显示
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。