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内容。

转载于:https://www.cnblogs.com/EleMMent/p/6950805.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值