最近接到一个新需求,需要将原先下载到用户电脑的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内容。