Display PDF in Web Application

前端 未结 5 695
轮回少年
轮回少年 2021-01-03 01:46

I have googled this, searched this, looked through SO and other sites (I\'ve been trying to read on this issue for hours now), but I still can\'t seem to find a satisfactory

5条回答
  •  生来不讨喜
    2021-01-03 02:19

    ASP.Net has a ReportViewer server control that can be used to display PDF files.

    Much of the documentation about this feature is about how to generate a report and export it to PDF. MSDN really isn't very helpful. I suppose everyone is relying on Adobe Reader and not looking for an alternative?

    But it is possible also to import and display a PDF. This code seemed to work for 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();
    }
    

提交回复
热议问题