locked
How to directly export a Report Viewer to PDF ? RRS feed

  • Question

  • User539757411 posted

    So I have a normal report viewer as below:

    <asp:LinkButton ID="btnGerarCertificado" runat="server" OnClick="btnGerarCertificado_Click" CssClass="btn btn-info" Visible="false">
                                <span class="glyphicon glyphicon-eye-open"></span> Ver meu certificado
                            </asp:LinkButton>

    And in code behind :

    private DataSet GetData(int idInscricao)
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PortalCursosConnectionString"].ToString());
                con.Open();
                SqlCommand cmd = new SqlCommand(@"
                    SET LANGUAGE Português
                    SELECT 
                    i.id, 
                    i.nome, 
                    i.evento_id, 
                    e.titulo as evento, 
                    DAY(e.data) AS dia_realizacao_evento,
                    DateName( month , DateAdd(month,MONTH(e.data) , -1 ) ) AS mes_realizacao_evento,
                    YEAR(e.data) AS ano_realizacao_evento,
                    DAY(GETDATE()) AS dia_atual,
                    DateName( month , DateAdd(month,MONTH(GETDATE()) , -1 ) ) AS mes_atual,
                    YEAR(GETDATE()) AS ano_atual
                    FROM inscricoes i
                    INNER JOIN eventos e ON i.evento_id = e.id
                    WHERE i.id = " + idInscricao);
    
                using (con)
                {
                    using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        da.SelectCommand = cmd;
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        return (ds);
                    }
                }
            }
    
            protected void btnGerarCertificado_Click(object sender, EventArgs e)
            {
                rvCertificados.Visible = true;
                int idInscricao = Convert.ToInt32(ddlInscricoes.SelectedValue); // DRopdownlist com os Eventos
                rvCertificados.ProcessingMode = ProcessingMode.Local;
                rvCertificados.LocalReport.ReportPath = Server.MapPath("~/Relatorios/RelatorioCertificados.rdlc");
                DataSet ds = new DataSet();
                ds = GetData(idInscricao);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ReportDataSource rds = new ReportDataSource("CertificadosRelatorioDataSet", ds.Tables[0]);
                    rvCertificados.LocalReport.DataSources.Clear();
                    rvCertificados.LocalReport.DataSources.Add(rds);
                }
            }

    Now I have to directly download the PDF without generating the report on screen.

    I have tried the following code:

    <asp:LinkButton ID="btnGerarCertificadoPDF" Text="Gerar PDF" runat="server" OnClick="btnGerarCertificadoPDF_Click" />
    protected void btnGerarCertificadoPDF_Click(object sender, EventArgs e)
            {
                rvCertificados.ProcessingMode = ProcessingMode.Local;
                rvCertificados.LocalReport.ReportPath = Server.MapPath("~/Relatorios/RelatorioCertificados.rdlc");
    
                int idInscricao = Convert.ToInt32(ddlInscricoes.SelectedValue);
                DataSet ds = GetData(idInscricao);
                ReportDataSource datasource = new ReportDataSource("CertificadosRelatorioDataSet", ds.Tables[0]);
                rvCertificados.LocalReport.DataSources.Clear();
                rvCertificados.LocalReport.DataSources.Add(datasource);
                //rvCertificados.AsyncRendering = false;
                //rvCertificados.LocalReport.Refresh();
    
                //Code For Download Direct PDF    
    
                Warning[] warnings;
                string[] streamIds;
                string mimeType = string.Empty;
                string encoding = string.Empty;
                string extension = string.Empty;
    
                byte[] bytes = rvCertificados.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
    
    
                // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.    
                //Response.Buffer = true;
                //Response.Clear();
                //Response.ContentType = mimeType;
                //Response.AddHeader("content-disposition", "attachment; filename= barcode.pdf");
                //Response.BinaryWrite(bytes); // create the file    
                //Response.Flush();
    
                byte[] file = rvCertificados.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
    
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "inline;filename=Test.pdf");
                Response.Buffer = true;
                Response.Clear();
                Response.BinaryWrite(file);
                Response.End();
            }




    But i got the error:

    Uncaught Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.
        at Function.Error$create [as create] (ScriptResource.axd?d=oBXqCa_O3M6G3VgJWENhH_S1d4gF60IBZmTFW2d2gSfZxevIk8F7E5bXPNFb3AYTI0vmcQ8A74iqeK3fs0EGC6FFe1yKPOM8XBXCIJFaibLkt1rdzXQRl9bRqQXAM1MNzwSUNQJoo_mZFOlx40CEKtxX9OiXTJCeFxBWYAQsnjChIGiebbPocg46cAhQx4_G0&t=ffffffffcc58dd65:237)
        at Sys$WebForms$PageRequestManager$_createPageRequestManagerParserError [as _createPageRequestManagerParserError] (ScriptResource.axd?d=l7OHiyaL9Tzd3pkxh3pWipTXx977JiTkwmjmTXxKTxw8K3idJpn9OD99Ou1e6TeiVz7APl1aTqPDZr_NMcOobkuFyrPrMCdM-SgrDhz84m0x2Mlztop1fJd7ZopeY7l0MZlPy3TeLvjW_LGEA83FE-w42j6wupwl4ktWwP_dFDdgJPAmPgYLTFyTIUleqLQh0&t=ffffffffcc58dd65:665)
        at Sys$WebForms$PageRequestManager$_parseDelta [as _parseDelta] (ScriptResource.axd?d=l7OHiyaL9Tzd3pkxh3pWipTXx977JiTkwmjmTXxKTxw8K3idJpn9OD99Ou1e6TeiVz7APl1aTqPDZr_NMcOobkuFyrPrMCdM-SgrDhz84m0x2Mlztop1fJd7ZopeY7l0MZlPy3TeLvjW_LGEA83FE-w42j6wupwl4ktWwP_dFDdgJPAmPgYLTFyTIUleqLQh0&t=ffffffffcc58dd65:1435)
        at Sys$WebForms$PageRequestManager$_onFormSubmitCompleted [as _onFormSubmitCompleted] (ScriptResource.axd?d=l7OHiyaL9Tzd3pkxh3pWipTXx977JiTkwmjmTXxKTxw8K3idJpn9OD99Ou1e6TeiVz7APl1aTqPDZr_NMcOobkuFyrPrMCdM-SgrDhz84m0x2Mlztop1fJd7ZopeY7l0MZlPy3TeLvjW_LGEA83FE-w42j6wupwl4ktWwP_dFDdgJPAmPgYLTFyTIUleqLQh0&t=ffffffffcc58dd65:1314)
        at Array.<anonymous> (ScriptResource.axd?d=oBXqCa_O3M6G3VgJWENhH_S1d4gF60IBZmTFW2d2gSfZxevIk8F7E5bXPNFb3AYTI0vmcQ8A74iqeK3fs0EGC6FFe1yKPOM8XBXCIJFaibLkt1rdzXQRl9bRqQXAM1MNzwSUNQJoo_mZFOlx40CEKtxX9OiXTJCeFxBWYAQsnjChIGiebbPocg46cAhQx4_G0&t=ffffffffcc58dd65:47)
        at ScriptResource.axd?d=oBXqCa_O3M6G3VgJWENhH_S1d4gF60IBZmTFW2d2gSfZxevIk8F7E5bXPNFb3AYTI0vmcQ8A74iqeK3fs0EGC6FFe1yKPOM8XBXCIJFaibLkt1rdzXQRl9bRqQXAM1MNzwSUNQJoo_mZFOlx40CEKtxX9OiXTJCeFxBWYAQsnjChIGiebbPocg46cAhQx4_G0&t=ffffffffcc58dd65:3484
        at Sys$Net$WebRequest$completed [as completed] (ScriptResource.axd?d=oBXqCa_O3M6G3VgJWENhH_S1d4gF60IBZmTFW2d2gSfZxevIk8F7E5bXPNFb3AYTI0vmcQ8A74iqeK3fs0EGC6FFe1yKPOM8XBXCIJFaibLkt1rdzXQRl9bRqQXAM1MNzwSUNQJoo_mZFOlx40CEKtxX9OiXTJCeFxBWYAQsnjChIGiebbPocg46cAhQx4_G0&t=ffffffffcc58dd65:6376)
        at XMLHttpRequest.Sys$Net$XMLHttpExecutor._onReadyStateChange (ScriptResource.axd?d=oBXqCa_O3M6G3VgJWENhH_S1d4gF60IBZmTFW2d2gSfZxevIk8F7E5bXPNFb3AYTI0vmcQ8A74iqeK3fs0EGC6FFe1yKPOM8XBXCIJFaibLkt1rdzXQRl9bRqQXAM1MNzwSUNQJoo_mZFOlx40CEKtxX9OiXTJCeFxBWYAQsnjChIGiebbPocg46cAhQx4_G0&t=ffffffffcc58dd65:5996)

    Can anyone help please ?

    Thanks!

    Tuesday, October 10, 2017 5:48 PM

All replies

  • User347430248 posted

    Hi xandeq,

    you can try to refer example below may help you.

    MyReportViewer.ProcessingMode = ProcessingMode.Remote;
    MyReportViewer.ServerReport.ReportServerUrl = new Uri("http://10.88.141.76:8080/ReportServer2012"); // Report Server URL
    MyReportViewer.ServerReport.ReportPath = "/StartSSRS/PersonAddressDetails";                         // Report Name
    MyReportViewer.ServerReport.Refresh();
     
    Microsoft.Reporting.WebForms.ReportParameter[] reportParameterCollection = new Microsoft.Reporting.WebForms.ReportParameter[1];
    reportParameterCollection[0] = new Microsoft.Reporting.WebForms.ReportParameter();
    reportParameterCollection[0].Name = "City";                                                         //Parameter Name
    reportParameterCollection[0].Values.Add("Seattle");                                                 //Parameter Value
    MyReportViewer.ServerReport.SetParameters(reportParameterCollection);
     
    Warning[] warnings;
    string[] streamids;
    string mimeType, encoding, extension, deviceInfo;
     
    deviceInfo = "True";
     
    byte[] bytes = MyReportViewer.ServerReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
     
    Response.Buffer = true;
    Response.Clear();
    Response.ContentType = mimeType;
     
    /* 
        This header is for saving it as an Attachment and popup window should display to to offer save as or open a PDF file 
        Response.AddHeader("Content-Disposition", "attachment; filename=" + extension);        
    */
     
    /*
        This header is use for open it in browser.
        Response.AddHeader("content-disposition", "inline; filename=myfile." + extension);
        Response.BinaryWrite(bytes);
    */
     
    //Creatr PDF file on disk
    string pdfPath = @"D:\TempReports\PersonAddressDetails." + extension;       // Path to export Report.
     
    System.IO.FileStream pdfFile = new System.IO.FileStream(pdfPath, System.IO.FileMode.Create);
    pdfFile.Write(bytes, 0, bytes.Length);
    pdfFile.Close();
    Response.Flush();
    Response.End();

    Reference:

    Export SSRS Report into PDF Format from ASP.NET Application

    Regards

    Deepak

    Wednesday, October 11, 2017 8:01 AM