Recently received a new demand, the original download to the user's computer PDF report file is displayed in the new page page, the user chooses to save and print on the page embedded PDF.
The code is as follows:
Fastreport.report rpt = Makeproposalreport (xxx,xxx,xxx,xxx,xxx); byte[] buffer = Exportpdftobytearray (rpt);// Delete the old PDF file Deletetemppdffile ();
Take file name
String fName = Makereportfilename ();
String newFile = Path.Combine (Server.MapPath ("~"), "NewFile", fName);
Create PDF files in the server, before the next production report will be deleted before the
Createpdffile (newFile, buffer); FileStream fs = new FileStream (NewFile, FileMode.Open, FileAccess.Read); return File (FS, "Application/pdf");
<summary> convert the report to PDF format and serialize to 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.def Ault. GetBytes (Password)); using (MemoryStream encryptstream = new MemoryStream ()) {Pdfstamper Stamper = new Pdfstamper (Reader, encrypt Stream); 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> Delete temporary PDF file </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 ();} }
The point is
FileStream fs = new FileStream (NewFile, FileMode.Open, FileAccess.Read);
Without this line of code, the PDF content cannot be displayed on the browser.
Generate PDFs in MVC and display them in the Web