none
Send Report directly to a printer from Report Viewer WITHOUT Print Dialog RRS feed

  • Question

  •  

    Hello, everyone!

    I'm attempting to find a way to automatically generate SRS reports in VB .NET and then send those generated reports directly to the printer.

    Now I can call ReportViewer and generate reports, site unseen. I can even save those as a PDF if I want.

    What I CAN NOT do is send them to a network printer. Does anyone know how this can be done?

    Thanks!

    Wednesday, August 1, 2007 5:11 PM

All replies

  • I found this method on the web some while back and it worked great for me. Good luck.

    This is all C# but you can convert it or create a C# class library and reference the dll.

    Create a Print class with follwoing methods: (Can copy and past if you like)

    using System;
    using System.IO;
    using System.Data;
    using System.Text;
    using System.Drawing.Imaging;
    using System.Drawing.Printing;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using Microsoft.Reporting.WinForms;
    using System.Data.OracleClient;

    namespace CheckReg_Windows
    {
        public class Print : IDisposable
        {
            private int _iPageIndex;
            private IList<Stream> _streams;
            private OracleConnection _oraConn = new OracleConnection(Database.ConnectionString);
            private string _sReportPath = "";

            public int CurrentPage
            {
                get
                {
                    return _iPageIndex;
                }
                set
                {
                    _iPageIndex = value;
                }
            }
            public string EMFPath
            {
                get
                {
                    return _sReportPath;
                }
                set
                {
                    _sReportPath = value;
                }
            }
            /// <summary>
            /// fill and pass a datatablew based upon the query sent to this report class
            /// </summary>
            /// <param name="sSQL"></param>
            /// <returns></returns>
            public DataTable LoadReportRecord(string sSQL)
            {
                DataTable dt;
                try
                {
                    dt = new DataTable();
                    OracleDataAdapter da = new OracleDataAdapter(sSQL, _oraConn);
                    da.Fill(dt);
                }
                catch (Exception ex)
                {
                    throw ex;

                }


                return dt;
            }

            /// <summary>
            /// provides the report renderer in order to save an image for each page of the report
            /// </summary>
            /// <param name="name"></param>
            /// <param name="fileNameExtension"></param>
            /// <param name="encoding"></param>
            /// <param name="mimeType"></param>
            /// <param name="willSeek"></param>
            /// <returns></returns>
            private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
            {
                try
                {
                    Random random = new Random();
                    int iNum = random.Next(1, 9999);
                    name = "Check Remittance Report_" + iNum.ToString();
                    Stream stream = new FileStream(EMFPath +@"\"+ name + fileNameExtension, FileMode.Create);
                    _streams.Add(stream);
                    CommonProperties.EMFFileName = name;

                    return stream;
                }
                catch (Exception ex)
                {
                    throw ex;
                  
                }
            }

            /// <summary>
            /// export the report as an EMF
            /// </summary>
            /// <param name="report"></param>
            public void Export(LocalReport report)
            {
                try
                {
                    string deviceInfo =
                  "<DeviceInfo>" +
                  "  <OutputFormat>EMF</OutputFormat>" +
                  "  <PageWidth>8.5in</PageWidth>" +
                  "  <PageHeight>14in</PageHeight>" +
                  "  <MarginTop>0in</MarginTop>" +
                  "  <MarginLeft>0in</MarginLeft>" +
                  "  <MarginRight>0in</MarginRight>" +
                  "  <MarginBottom>0in</MarginBottom>" +
                  "</DeviceInfo>";

                    Warning[] warnings;
                    _streams = new List<Stream>();
                    report.Render("Image", deviceInfo, CreateStream,
                       out warnings);
                    foreach (Stream stream in _streams)
                        stream.Position = 0;
                }
                catch (Exception ex)
                {
                    ErrorHandler.LogError(ex);
                    throw ex;
                }
            }

            /// <summary>
            /// Print page events handler
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="ev"></param>
            public void PrintPage(object sender, PrintPageEventArgs ev)
            {
                Metafile pageImage = new
                   Metafile(_streams[this._iPageIndex]);
                ev.Graphics.DrawImage(pageImage, ev.PageBounds);
                this._iPageIndex++;
                ev.HasMorePages = (this._iPageIndex < _streams.Count);
            }

            /// <summary>
            /// print the report
            /// </summary>
            public void PrintReport()
            {
                //const string printerName =
                //   "Microsoft Office Document Image Writer";
                if (_streams == null || _streams.Count == 0)
                    return;
                PrintDocument printDoc = new PrintDocument();
                           
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
               
                printDoc.Print();
            }
            public DataTable CreateReportTable(int Index)
            {
                DataTable dt = new DataTable();
                switch(Index)
                {
                    case 1:
                        string sSQL = "SELECT * FROM CHK_REG_APPLICATION_DATA WHERE ROUTE_ID = "+CommonProperties.Route_ID;
                        using (OracleConnection oraConn = new OracleConnection(Database.ConnectionString))
                        {
                            using (OracleDataAdapter da = new OracleDataAdapter(sSQL, oraConn))
                            {
                                da.Fill(dt);
                                if (dt.Rows.Count > 0)
                                {
                                    dt.Columns.Add(new DataColumn("APPROVAL_DATE",typeof(DateTime)));
                                    if(oraConn.State == ConnectionState.Closed)
                                        oraConn.Open();
                                    using (OracleCommand cmd = new OracleCommand("SELECT APPROVAL_DATE FROM " +
                                        "CHK_REG_APPROVAL WHERE APPROVAL_DATE IS NOT NULL AND ROUTE_ID = " +
                                        CommonProperties.Route_ID + " ORDER BY APPROVAL_DATE", oraConn))
                                    {
                                        using (OracleDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                                        {
                                            if (rdr.HasRows)
                                            {
                                                rdr.Read();
                                                DateTime date;
                                                if(DateTime.TryParse(rdr.GetOracleValue(0).ToString(),out date))
                                                    dt.Rows[0]["APPROVAL_DATE"] = date;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                       
                        break;
                    case 2:
                        break;
                }

                return dt;
            }

            public void Dispose()
            {
                if (_streams != null)
                {
                    foreach (Stream stream in _streams)
                        stream.Close();
                    _streams = null;
                }
                //cleanup the emf file
                if (File.Exists(EMFPath + CommonProperties.EMFFileName + "emf"))
                {
                    try
                    {
                        File.Delete(EMFPath + CommonProperties.EMFFileName + "emf");
                        CommonProperties.EMFFileName = "";

                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
               
            }
        }
    }


    In your business layer do this:

    This is the code called by my print buttons Click event:

    using (Print printRpt = new Print())
                    {
                        toolStripButtonPrint.Enabled = false;
                        printRpt.EMFPath = Properties.Settings.Default.ReportsPath;
                      
                        switch (tabControlMain.SelectedIndex)
                        {
                            case 1: //Check Remittance
                                if (this._dataSet.Tables["CHK_REG_APPLICATION_DATA"] != null)
                                {
                                    this.Cursor = Cursors.WaitCursor;
                                    LocalReport report = new LocalReport();
                                    //report.ReportPath = @"Reports\Check Remittance Report.rdlc";
                                    report.ReportPath = @Properties.Settings.Default.ReportsPath + @"Check Remittance Report.rdlc";
                                    //the datasource is called ENPACD insdie the rdlc file. The actual connection can be what ever
                                    report.DataSources.Add(new ReportDataSource("EMPACD", printRpt.CreateReportTable(1)));
                                    printRpt.Export(report);
                                    printRpt.CurrentPage = 0;
                                    printDialog1.Document = new System.Drawing.Printing.PrintDocument();
                                    printDialog1.Document.PrintPage += new      System.Drawing.Printing.PrintPageEventHandler(printRpt.PrintPage);
                                    this.Cursor = Cursors.Arrow;
                                    DialogResult dr = printDialog1.ShowDialog(this);
                                    if (dr == DialogResult.OK)
                                    {
                                        if (printDialog1.PrinterSettings.IsValid)
                                            printDialog1.Document.Print();
                                    }
                                }
                                break;
                        }

                        toolStripButtonPrint.Enabled = true;
                    }


    You can modify the code to do what you need. I hope that it is not too confusing. Good Luck





    Wednesday, August 1, 2007 7:51 PM
  • Check out this link.  If the link does not work search on msdn for the article "Walkthrough: Printing a Local Report without Preview".

     

    http://msdn2.microsoft.com/en-us/library/ms252091(VS.80).aspx

     

    Tuesday, August 7, 2007 1:46 PM
  • When you look at the code within the ReportViewer control with Reflector, one can see that the code associated with printing is for more complex than the above referenced sample.  Perhaps MS could revise the control to allow us to instantiate the control programmatically and call a Print() method instead of a PrintDialog() method.  Sure would be nice.  I don't however know if MS reads these forum entries.
    Monday, August 10, 2009 6:18 PM
  • Microsoft definitely does read these forum postings.  Several members of the Reporting Services team are frequent posters here.  I have some sample code that will allow you to print without launching the print dialog (http://blogs.msdn.com/brianhartman/archive/2009/02/27/manually-printing-a-report.aspx).  Additionally, we are making improvements in this area for VS 2010 based on feedback we have received here and elsewhere.
    Wednesday, August 12, 2009 3:09 AM
    Moderator
  • Microsoft definitely does read these forum postings.  Several members of the Reporting Services team are frequent posters here.  I have some sample code that will allow you to print without launching the print dialog (http://blogs.msdn.com/brianhartman/archive/2009/02/27/manually-printing-a-report.aspx).  Additionally, we are making improvements in this area for VS 2010 based on feedback we have received here and elsewhere.


    I have noticed that most (if not all) the workarounds that are posted with regards to direct printing require a default printer to already be set; however, what if the client's printer is on a network?  Unfortunately, PageSettings() only works with printers installed on the actual client's machine.  Does anybody know of any workarounds to combat this issue?

    In addition, suppose you account for this in your code and prompt the user to specify the network printer to use as needed.  Would this even be possible when using Webforms?  As far as I know, there is no way to invoke a print dialog on the client when using webforms.  What are the remaining options?
    Tuesday, November 17, 2009 9:31 PM
  • Didn't members of the Reporting Services team anticipate the need to print programmatically without launching the print dialog? 

    Or is the approach cited considered adequate?

    Did any members of the reporting services team realize that this was lacking in VS2005?

    Will vs2010 include this capability?


    Thanks!
    Bill


    bill
    Wednesday, March 10, 2010 9:12 PM