Results 1 to 22 of 22

Thread: [RESOLVED] Print Directly to Printer with RDLC Report

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Resolved [RESOLVED] Print Directly to Printer with RDLC Report

    I am wondering how I can print directly to a printer with a local rdlc report instead of using the report viewer. Basically what I am trying to do is allow the user to push a button and print a report using the record that the user is currently viewing on the screen.

    I have tried using the code on the MSDN http://msdn.microsoft.com/en-us/library/ms252091.aspx, but I get an error Variable 'warnings' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Which is this part of the code:
    Dim warnings As Warning()
    m_streams = New List(Of Stream)()
    report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
    For Each stream As Stream In m_streams
    stream.Position = 0

    So it won't run. Also the msdn sample code wants an XML file and I only have an xsd.

    Can't believe this is so much work just to print the report without viewing it.

    Any help you can provide would be much appreciated as I am new to vb.

  2. #2

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Re: Print Directly to Printer with RDLC Report

    Ok I've got the example from MSDN working now. The example calls for an XML file instead of an XSD. I am wondering how I can convert (or get) my XSD files to XML. This little piece of code is my problem.
    Private Function LoadSalesData() As DataTable
    ' Create a new DataSet and read sales data file
    ' data.xml into the first DataTable.
    Dim dataSet As New DataSet()
    dataSet.ReadXml("C:\MaintenanceTracker\MaintenanceTracker\POReport.xml")
    Return dataSet.Tables(0)

    End Function
    Thanks for any help you can provide.
    Stacy

  3. #3
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,195

    Re: Print Directly to Printer with RDLC Report

    I don't understand, what does this have to do with printing directly to the printer. A XSD file is not a data file. It contains the code for accessing a data file.

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Re: Print Directly to Printer with RDLC Report

    wes4bt,
    Thanks for your reply.
    In the MSDN example it wants an XML file to Read from (example above) I don't have an XML file for it to read from, but I already have a XSD file though so maybe I don't even need to do that step exactly like that. I am just guessing as to what the code in the MSDN example is doing. I think it makes an XSD file from an XML.

    I was able to get the example to work for me using a report that doesn't have any data (or DataSet hooked to it) on it and that was fine but the Report I am trying to print directly to the printer will have data on it and is hooked to a dataset.

    I'm a little out of my league here as I have only been working with .net for a few months. Not sure what the Return dataset.Table(0) does. If that is so maybe I need to change the code for this function to return my existing dataset table I already have. Not sure exactly how to do that though.
    Your knowledge and input would be greatly appreciated.
    Stacy

  5. #5
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,195

    Re: Print Directly to Printer with RDLC Report

    This link has some videos on creating rdlc reports http://windowsclient.net/learn/videos.aspx there's lots of info on the subject, just Google something like ".net rdlc dataset"

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Re: Print Directly to Printer with RDLC Report

    wes4dbt,

    Oh I already have my report built - it's the getting it to print directly to the printer without the preview that is causing the problem.
    Stacy

  7. #7
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,195

    Re: Print Directly to Printer with RDLC Report

    After reviewing the link in post #1, I think I understand your problem.
    report.DataSources.Add(New ReportDataSource("Sales", LoadSalesData()))
    You don't need to use the "LoadsalesData", basically what you need is this,
    report.DataSources.Add(New ReportDataSource("thenameofyourdataset",thenameofthedatatable))
    Read this,
    Hooking up the DataSource at Runtime
    Finally, you need to let the ReportViewer know where to get the actual data from so it can feed that into the report. In your form's OnLoad method (or wherever is appropriate for your application), you need to add code much like this:


    private void Form1_Load(object sender, EventArgs e) {
    // somehow get the data at runtime, application specific
    this.myData = GetDataSource();

    this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet_Person", myData));
    this.reportViewer1.RefreshReport();
    }

    Notice we are adding a DataSource to the ReportViewer. This is the bridge from your data into the report. Key here is the name you specify for the ReportDataSource, it must match the name found in the .rdlc file for this dataset. This name was determined by how you named the DataSet you added to your project and designed. If you view the .rdlc file in the XML editor (right click it and select "Open With..." then pick "XML Editor"), you will find a <DataSets> node, containing a <DataSet> node, this node is the report's understanding of the data for this report, and what your actual data will map to at runtime. Notice the Name attribute of the DataSet node, this is the name you need to specify in the ReportDataSource constructor.
    Make sure you fill the datatable.

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Re: Print Directly to Printer with RDLC Report

    Ok I have tried doing your above idea. In my Run() I changed the code so it doesn't use the LoadSales() function anymore and add as you suggested the following...
    Private Sub Run()
    Dim report As New LocalReport()
    report.ReportPath = ("C:\MaintenanceTracker\MaintenanceTracker\Reports\PO.rdlc")
    'report.DataSources.Add(New ReportDataSource("Sales", LoadSalesData()))
    DataTable1TableAdapter.Fill(Me.POReport.DataTable1)
    report.DataSources.Add(New ReportDataSource("POReport", "DataTable1"))
    Export(report)
    Print()
    End Sub
    So it used to do...
    report.DataSources.Add(New ReportDataSource("Sales", LoadSalesData()))

    I now fill my datatable and do the datasource add as follows...
    DataTable1TableAdapter.Fill(Me.POReport.DataTable1)
    report.DataSources.Add(New ReportDataSource("POReport", "DataTable1"))
    I am still getting an error when I try to run. I don't know about using your suggestions for the following lines...
    this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet_Person", myData));
    this.reportViewer1.RefreshReport();
    Because I am not using the reportViewer - I want to print directly to the printer without using the reportviewer.

    Thanks for all your help with this. I think it is really close!
    Stacy

    P.S. When I run it with these lines added and taken out I get an error on this line of code under my Private Sub Export
    report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
    and it says LocalProcessingException was unhandled
    An error occurred during local report processing.
    Last edited by StacyOW; Oct 4th, 2012 at 03:29 PM.

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Re: Print Directly to Printer with RDLC Report

    Quote Originally Posted by wes4dbt View Post
    Notice we are adding a DataSource to the ReportViewer. This is the bridge from your data into the report.
    I can get the report to work perfectly if I use the reportviewer. But the user doesn't want to view them - just print directly to the printer.

    Can't I just change the LoadSales() Function to fill and use my dataset and then return that table? Not sure exactly how to do that though. I have tried several different things but I always get that same error from my previous post.

    Stacy

  10. #10
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,195

    Re: Print Directly to Printer with RDLC Report

    Ignore the the code referring to the reportviewer, I just wanted you to read about adding a datasource, especially this,
    Key here is the name you specify for the ReportDataSource, it must match the name found in the .rdlc file for this dataset. This name was determined by how you named the DataSet you added to your project and designed. If you view the .rdlc file in the XML editor (right click it and select "Open With..." then pick "XML Editor"), you will find a <DataSets> node, containing a <DataSet> node, this node is the report's understanding of the data for this report, and what your actual data will map to at runtime. Notice the Name attribute of the DataSet node, this is the name you need to specify in the ReportDataSource constructor.
    If this line is causing the error,
    report.Render("Image", deviceInfo, AddressOf CreateStream, warnings).
    Have you checked the other parameters?

    If you still can't find the problem, post all relevant code.
    Last edited by wes4dbt; Oct 4th, 2012 at 09:02 PM.

  11. #11

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Re: Print Directly to Printer with RDLC Report

    I believe it is the warnings that is causing the problem which in turn refers back to my datasource being the problem. If I run this code with a report that doesn't have a datasource attached to it - it works perfectly. It's when I try to use the code to refer to my dataset that I get the errors when I run it. The error is so generic though so it isn't much help.

    Thanks,
    Stacy

  12. #12

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Re: Print Directly to Printer with RDLC Report

    Ok I can get it to print but it is printing blank pages. I did as you said and opened the RDLC file with XML editor and the <DataSet Name ="DataSet1"> the DataSource is <DataSource Name="POReport"> that is near the top of the file. Towards to bottom is another section that has dataset it looks like this...
    <Query>
    <DataSourceName>POReport</DataSourceName>
    <CommandText>/* Local Query */</CommandText>
    </Query>
    <rdataSetInfo>
    <rdataSetName>POReport</rdataSetName>
    <rd:SchemaPath>C:\Users\Stacy\documents\visual studio 2010\Projects\MaintenanceTracker\MaintenanceTracker\POReport.xsd</rd:SchemaPath>
    <rd:TableName>DataTable1</rd:TableName>
    <rd:TableAdapterFillMethod>Fill</rd:TableAdapterFillMethod>
    <rd:TableAdapterGetDataMethod>GetData</rd:TableAdapterGetDataMethod>
    <rd:TableAdapterName>DataTable1TableAdapter</rd:TableAdapterName>
    </rdataSetInfo>
    </DataSet>
    Not sure which area in the file you are referring too.
    So I tried leaving the LoadSales() and just changing it so it fills and uses my current dataset for the report. This is what I have for the LoadSales() right now. Apparently it is not filling the dataset cuz the report is printing blank.
    Private Function LoadSalesData() As DataTable
    ' Create a new DataSet and read sales data file
    ' data.xml into the first DataTable.
    Dim dataSet1 As New DataSet("POReport")
    dataSet1.Tables.Add("DataTable1")
    DataTable1TableAdapter.Fill(POReport.DataTable1)
    Return dataSet1.Tables(0)

    End Function
    I'm pretty sure I have screwed up this vb code somehow but too new to figure out where. Not sure how it works when you Dim a new DataSet and then how do you fill it?
    Thanks,
    Stacy
    Last edited by StacyOW; Oct 10th, 2012 at 12:35 PM.

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Re: Print Directly to Printer with RDLC Report

    wes4dbt,
    I finally got it! YEAH! I took out all the Dim stuff and just used the following to fill my existing datatable and then return it and it works perfectly!
    DataTable1TableAdapter.Fill(POReport.DataTable1)
    Return POReport.Tables(0)
    Thank you so much for all your advise - I really appreciate it! I couldn't have figured it out without your help.
    Stacy

  14. #14
    Addicted Member
    Join Date
    Jul 2012
    Location
    Tiruvallur, India
    Posts
    201

    Re: [RESOLVED] Print Directly to Printer with RDLC Report

    Stacy !
    Can you post the entire working code for the benefit of beginners ?

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Re: [RESOLVED] Print Directly to Printer with RDLC Report

    The link to the full code is in my first post on the MSDN site.
    http://msdn.microsoft.com/en-us/library/ms252091.aspx

    But here is my code with a few changes I needed to make it work with a local report using a dataset. Hope it helps.
    Code:
     Private Function LoadSalesData() As DataTable
            ' Create a new DataSet and read sales data file 
            ' data.xml into the first DataTable.
            Dim SearchValue As String = ""
            SearchValue = MPONumTextBox.Text
            DataTable1TableAdapter.FillByPONum(POReport.DataTable1, SearchValue)
    
            Return POReport.Tables(0)
    
        End Function
    
        ' Routine to provide to the report renderer, in order to
        ' save an image for each page of the report.
        Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
            Dim stream As Stream = New MemoryStream()
            m_streams.Add(stream)
            Return stream
        End Function
    
        ' Export the given report as an EMF (Enhanced Metafile) file.
        Private Sub Export(ByVal report As LocalReport)
            Dim deviceInfo As String = "<DeviceInfo>" & _
                "<OutputFormat>EMF</OutputFormat>" & _
                "<PageWidth>8.5in</PageWidth>" & _
                "<PageHeight>11in</PageHeight>" & _
                "<MarginTop>0.25in</MarginTop>" & _
                "<MarginLeft>0.25in</MarginLeft>" & _
                "<MarginRight>0.25in</MarginRight>" & _
                "<MarginBottom>0.25in</MarginBottom>" & _
                "</DeviceInfo>"
            Dim warnings As Warning()
            m_streams = New List(Of Stream)()
            report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
            For Each stream As Stream In m_streams
                stream.Position = 0
            Next
        End Sub
    
        ' Handler for PrintPageEvents
        Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
            Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
    
            ' Adjust rectangular area with printer margins.
            Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX), _
                                              ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY), _
                                              ev.PageBounds.Width, _
                                              ev.PageBounds.Height)
    
            ' Draw a white background for the report
            ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
    
            ' Draw the report content
            ev.Graphics.DrawImage(pageImage, adjustedRect)
    
            ' Prepare for the next page. Make sure we haven't hit the end.
            m_currentPageIndex += 1
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
        End Sub
    
        Private Sub Print()
            If m_streams Is Nothing OrElse m_streams.Count = 0 Then
                Throw New Exception("Error: no stream to print.")
            End If
            Dim printDoc As New PrintDocument()
            If Not printDoc.PrinterSettings.IsValid Then
                Throw New Exception("Error: cannot find the default printer.")
            Else
                AddHandler printDoc.PrintPage, AddressOf PrintPage
                m_currentPageIndex = 0
                printDoc.Print()
            End If
        End Sub
    
        ' Create a local report for Report.rdlc, load the data,
        ' export the report to an .emf file, and print it.
        'Private Sub Run()
        Private Sub PrintPO()
            Dim report As New LocalReport()
            report.ReportPath = ("C:\MaintenanceTracker\MaintenanceTracker\Reports\POReport.rdlc")
            report.DataSources.Add(New ReportDataSource("DataSet1", LoadSalesData()))
            Export(report)
            Print()
    
        End Sub
    
        Public Overloads Sub Dispose() Implements IDisposable.Dispose
            If m_streams IsNot Nothing Then
                For Each stream As Stream In m_streams
                    stream.Close()
                Next
                m_streams = Nothing
            End If
        End Sub
    I run it from a button on my winforms. Here is that code
    Code:
    Private Sub ToolStripButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton3.Click
            Me.PordersBindingSource.EndEdit()
            PrintPO()
        End Sub

  16. #16
    Addicted Member
    Join Date
    Jul 2012
    Location
    Tiruvallur, India
    Posts
    201

    Re: [RESOLVED] Print Directly to Printer with RDLC Report

    Thank you Stacy !.
    In VB6 it is possible to print a Page range with the command : Report1.PrintReport False, rptRangeFromTo, n1, n2
    How to give page range like the above in vb.net with these codes (in your post # 15)
    Last edited by raghavendran; Nov 12th, 2013 at 10:56 PM.

  17. #17
    Junior Member
    Join Date
    Nov 2013
    Location
    Ireland
    Posts
    25

    Re: [RESOLVED] Print Directly to Printer with RDLC Report

    Hi StacyOW,

    Im trying to do this exact same thing but so far ive had no luck.. =(

    I tried your code and changed it to suit mine obviously but now im getting an error saying "Error: no stream to print".. Have you any idea how to fix this?

    My code is:

    Code:
    Imports System
    Imports System.IO
    Imports System.Data
    Imports System.Text
    Imports System.Drawing.Imaging
    Imports System.Drawing.Printing
    Imports System.Collections.Generic
    Imports Microsoft.Reporting.WinForms
    
    Public Class Receipt
        Implements IDisposable
        Public PicLocation As String
        Dim Ctrl1, Ctrl2 As Control
        Dim CN As New OleDb.OleDbConnection
        Dim CMD As New OleDb.OleDbCommand
        Dim DataR As OleDb.OleDbDataReader
    
        'To display into datagrid purpose
        Dim dataS As New DataSet
        Dim dataAd As New OleDb.OleDbDataAdapter
        Public SqlStr, SqlStr1, DBPath, DBStatus, SearchBox As String
        Dim X, Y, SqlH, Onh As Integer
        Dim SqlUser As String
        Dim DataP As Decimal
        Dim Balance As Integer
    
        Private m_currentPageIndex As Integer
        Private m_streams As IList(Of Stream)
    
        ' Routine to provide to the report renderer, in order to
        ' save an image for each page of the report.
        Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
            Dim stream As Stream = New MemoryStream()
            m_streams.Add(stream)
            Return stream
        End Function
        Private Sub Receipt_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'Sets the program resolution to 1024 x 768 & centers the form screen via code.
            Me.Size = New System.Drawing.Size(270, 500)
    
            'TODO: This line of code loads data into the 'ProductListDataSet' table.
            DBPath = (Application.StartupPath & "\ProductList.accdb")
            If CN.State = ConnectionState.Open Then
                CN.Close()
                DBStatus = ("Not Connected")
            End If
            SqlStr = ("Provider = Microsoft.ACE.OLEDB.12.0;Data Source =" & DBPath)
            CN.ConnectionString = SqlStr
            CN.Open()
            Onh = Nothing
    
            lblTime.Text = CStr(DateAndTime.Now)
            lblUser.Text = Login.userTB.Text
    
            Dim sql As String
            sql = "SELECT * Receipt"
            Me.ReceiptTableAdapter.ClearBeforeFill = True
            Me.ReceiptTableAdapter.Connection = CN
            Me.ReceiptTableAdapter.Connection.CreateCommand.CommandText = sql
            Me.ReceiptTableAdapter.Fill(Me.ProductListDataSet.Receipt)
            Me.ReportViewer1.RefreshReport()
            Me.Refresh()
    
        End Sub
    
        Private Function LoadReceiptData() As DataTable
            ' Create a new DataSet and read sales data file 
            ' data.xml into the first DataTable.
    
            Me.ReceiptTableAdapter.Fill(Me.ProductListDataSet.Receipt)
    
            Return ProductListDataSet.Tables(0)
    
        End Function
    
        ' Export the given report as an EMF (Enhanced Metafile) file.
        Private Sub Export(ByVal report As LocalReport)
            Dim deviceInfo As String = "<DeviceInfo>" & _
                "<OutputFormat>EMF</OutputFormat>" & _
                "<PageWidth>8cm</PageWidth>" & _
                "<PageHeight>29.7cm</PageHeight>" & _
                "<MarginTop>0in</MarginTop>" & _
                "<MarginLeft>0in</MarginLeft>" & _
                "<MarginRight>0in</MarginRight>" & _
                "<MarginBottom>0in</MarginBottom>" & _
                "</DeviceInfo>"
        End Sub
        Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
            Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
    
            ' Adjust rectangular area with printer margins.
            Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX), _
                                              ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY), _
                                              ev.PageBounds.Width, _
                                              ev.PageBounds.Height)
    
            ' Draw a white background for the report
            ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
    
            ' Draw the report content
            ev.Graphics.DrawImage(pageImage, adjustedRect)
    
            ' Prepare for the next page. Make sure we haven't hit the end.
            m_currentPageIndex += 1
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
        End Sub
    
        Private Sub Print()
            If m_streams Is Nothing OrElse m_streams.Count = 0 Then
                Throw New Exception("Error: no stream to print.")
            End If
            Dim printDoc As New PrintDocument()
            If Not printDoc.PrinterSettings.IsValid Then
                Throw New Exception("Error: cannot find the default printer.")
            Else
                AddHandler printDoc.PrintPage, AddressOf PrintPage
                m_currentPageIndex = 0
                printDoc.Print()
            End If
        End Sub
    
        ' Create a local report for Report.rdlc, load the data,
        ' export the report to an .emf file, and print it.
        'Private Sub Run()
    
        Private Sub PrintPO()
            Dim report As New LocalReport()
            report.ReportPath = ("C:\Users\KerrieMcConaghy\Desktop\Epos Project (061113)   LATEST\BEDECK\Receipt.vb")
            report.DataSources.Add(New ReportDataSource("ProductListDataSet", LoadReceiptData()))
            Export(report)
            Print()
    
        End Sub
        Public Sub Dispose() Implements IDisposable.Dispose
         If m_streams IsNot Nothing Then
               For Each stream As Stream In m_streams
                   stream.Close()
               Next
               m_streams = Nothing
           End If
        'End Sub
    
        Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
            Me.ReceiptBindingSource.EndEdit()
            PrintPO()
        End Sub
    End Class
    Thanks
    Kerrie
    Last edited by KerrieJMc; Nov 28th, 2013 at 07:02 AM. Reason: added code

  18. #18

    Thread Starter
    Addicted Member
    Join Date
    Jun 2012
    Location
    Minnesota
    Posts
    238

    Re: [RESOLVED] Print Directly to Printer with RDLC Report

    Kerrie,

    I believe I had this error before also. For me it turned out the report dataset was wrong. You will have the regular dataset and then when you create the dataset in your report it might be named differently then the regular dataset name. I would double check that first. I see yours is set up using a OleDb Connection. Mine was using a sql connection. Another thing to check would be to make sure it can find your report. I've had that problem before also, but it will usually give an error that it can't find the report.

    Hope that helps.

    Stacy

  19. #19
    Junior Member
    Join Date
    Nov 2013
    Location
    Ireland
    Posts
    25

    Re: [RESOLVED] Print Directly to Printer with RDLC Report

    Thanks for your reply StacyOW.

    I've tried everything and have had no luck. I am now looking into buying a reporting software package to see if it will help.

    Thanks again
    Kerrie

  20. #20
    Addicted Member coolwater's Avatar
    Join Date
    Dec 2004
    Location
    philippines
    Posts
    215

    Re: [RESOLVED] Print Directly to Printer with RDLC Report

    Quote Originally Posted by KerrieJMc View Post
    Hi StacyOW,

    Im trying to do this exact same thing but so far ive had no luck.. =(

    I tried your code and changed it to suit mine obviously but now im getting an error saying "Error: no stream to print".. Have you any idea how to fix this?

    My code is:

    Code:
    Imports System
    Imports System.IO
    Imports System.Data
    Imports System.Text
    Imports System.Drawing.Imaging
    Imports System.Drawing.Printing
    Imports System.Collections.Generic
    Imports Microsoft.Reporting.WinForms
    
    Public Class Receipt
        Implements IDisposable
        Public PicLocation As String
        Dim Ctrl1, Ctrl2 As Control
        Dim CN As New OleDb.OleDbConnection
        Dim CMD As New OleDb.OleDbCommand
        Dim DataR As OleDb.OleDbDataReader
    
        'To display into datagrid purpose
        Dim dataS As New DataSet
        Dim dataAd As New OleDb.OleDbDataAdapter
        Public SqlStr, SqlStr1, DBPath, DBStatus, SearchBox As String
        Dim X, Y, SqlH, Onh As Integer
        Dim SqlUser As String
        Dim DataP As Decimal
        Dim Balance As Integer
    
        Private m_currentPageIndex As Integer
        Private m_streams As IList(Of Stream)
    
        ' Routine to provide to the report renderer, in order to
        ' save an image for each page of the report.
        Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
            Dim stream As Stream = New MemoryStream()
            m_streams.Add(stream)
            Return stream
        End Function
        Private Sub Receipt_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'Sets the program resolution to 1024 x 768 & centers the form screen via code.
            Me.Size = New System.Drawing.Size(270, 500)
    
            'TODO: This line of code loads data into the 'ProductListDataSet' table.
            DBPath = (Application.StartupPath & "\ProductList.accdb")
            If CN.State = ConnectionState.Open Then
                CN.Close()
                DBStatus = ("Not Connected")
            End If
            SqlStr = ("Provider = Microsoft.ACE.OLEDB.12.0;Data Source =" & DBPath)
            CN.ConnectionString = SqlStr
            CN.Open()
            Onh = Nothing
    
            lblTime.Text = CStr(DateAndTime.Now)
            lblUser.Text = Login.userTB.Text
    
            Dim sql As String
            sql = "SELECT * Receipt"
            Me.ReceiptTableAdapter.ClearBeforeFill = True
            Me.ReceiptTableAdapter.Connection = CN
            Me.ReceiptTableAdapter.Connection.CreateCommand.CommandText = sql
            Me.ReceiptTableAdapter.Fill(Me.ProductListDataSet.Receipt)
            Me.ReportViewer1.RefreshReport()
            Me.Refresh()
    
        End Sub
    
        Private Function LoadReceiptData() As DataTable
            ' Create a new DataSet and read sales data file 
            ' data.xml into the first DataTable.
    
            Me.ReceiptTableAdapter.Fill(Me.ProductListDataSet.Receipt)
    
            Return ProductListDataSet.Tables(0)
    
        End Function
    
        ' Export the given report as an EMF (Enhanced Metafile) file.
        Private Sub Export(ByVal report As LocalReport)
            Dim deviceInfo As String = "<DeviceInfo>" & _
                "<OutputFormat>EMF</OutputFormat>" & _
                "<PageWidth>8cm</PageWidth>" & _
                "<PageHeight>29.7cm</PageHeight>" & _
                "<MarginTop>0in</MarginTop>" & _
                "<MarginLeft>0in</MarginLeft>" & _
                "<MarginRight>0in</MarginRight>" & _
                "<MarginBottom>0in</MarginBottom>" & _
                "</DeviceInfo>"
        End Sub
        Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
            Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
    
            ' Adjust rectangular area with printer margins.
            Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX), _
                                              ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY), _
                                              ev.PageBounds.Width, _
                                              ev.PageBounds.Height)
    
            ' Draw a white background for the report
            ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
    
            ' Draw the report content
            ev.Graphics.DrawImage(pageImage, adjustedRect)
    
            ' Prepare for the next page. Make sure we haven't hit the end.
            m_currentPageIndex += 1
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
        End Sub
    
        Private Sub Print()
            If m_streams Is Nothing OrElse m_streams.Count = 0 Then
                Throw New Exception("Error: no stream to print.")
            End If
            Dim printDoc As New PrintDocument()
            If Not printDoc.PrinterSettings.IsValid Then
                Throw New Exception("Error: cannot find the default printer.")
            Else
                AddHandler printDoc.PrintPage, AddressOf PrintPage
                m_currentPageIndex = 0
                printDoc.Print()
            End If
        End Sub
    
        ' Create a local report for Report.rdlc, load the data,
        ' export the report to an .emf file, and print it.
        'Private Sub Run()
    
        Private Sub PrintPO()
            Dim report As New LocalReport()
            report.ReportPath = ("C:\Users\KerrieMcConaghy\Desktop\Epos Project (061113)   LATEST\BEDECK\Receipt.vb")
            report.DataSources.Add(New ReportDataSource("ProductListDataSet", LoadReceiptData()))
            Export(report)
            Print()
    
        End Sub
        Public Sub Dispose() Implements IDisposable.Dispose
         If m_streams IsNot Nothing Then
               For Each stream As Stream In m_streams
                   stream.Close()
               Next
               m_streams = Nothing
           End If
        'End Sub
    
        Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
            Me.ReceiptBindingSource.EndEdit()
            PrintPO()
        End Sub
    End Class
    Thanks
    Kerrie

    I also had the same error. I followed the MSDN tutorial to the letter. I got the solution when I read wes4dbt advice to open the rdlc file with the xml editor. In the xml editor I found the xml tag ex.
    Code:
    <DataSet Name="DatasetName">
    . I copied the "DatasetName" and replaced the code
    Code:
    report.DataSources.Add(New ReportDataSource("DatasetName", LoadSalesData()))
    . After that I managed to run the report without errors.

  21. #21
    Junior Member
    Join Date
    Nov 2013
    Location
    Ireland
    Posts
    25

    Re: [RESOLVED] Print Directly to Printer with RDLC Report

    Thanks for your reply coolwater!

    I'll give that a try later and I'll let you know how I get on.

    Thanks again

  22. #22
    New Member
    Join Date
    Jul 2012
    Posts
    1

    Unhappy Re: [RESOLVED] Print Directly to Printer with RDLC Report

    StacyOW,

    Hello stacy.. i have my vb code here.. i follow yours step but i won't work.. still display this error to me. "An error occurred during local report processing." the errors display on the warning. I hope u can help me... i did attach my code here... thanks stacy!


    this is my code:

    Imports System
    Imports System.IO
    Imports System.Data
    Imports System.Text
    Imports System.Drawing
    Imports System.Drawing.Imaging
    Imports System.Drawing.Printing
    Imports System.Collections.Generic
    Imports System.Windows.Forms
    Imports Microsoft.Reporting.WinForms
    Public Class frmReceipt
    Private m_currentPageIndex As Integer
    Private m_streams As IList(Of Stream)
    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
    PrintPO()
    Me.Close()
    End Sub

    Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    Me.Close()

    End Sub

    Private Sub frmReceipt_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Me.qryReceiptTableAdapter.Fill(Me.ReceiptDataSet.qryReceipt)

    Me.ReportViewer1.RefreshReport()


    End Sub


    Private Function LoadSalesData() As DataTable
    ' Create a new DataSet and read sales data file
    ' data.xml into the first DataTable.
    'Dim SearchValue As String = ""
    'SearchValue = MPONumTextBox.Text
    Dim DataTable1TableAdapter As New DataTable

    qryReceiptTableAdapter.Fill(ReceiptDataSet.qryReceipt)

    Return ReceiptDataSet.Tables(0)

    End Function

    ' Routine to provide to the report renderer, in order to
    ' save an image for each page of the report.
    Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
    Dim stream As Stream = New MemoryStream()
    m_streams.Add(stream)
    Return stream
    End Function

    ' Export the given report as an EMF (Enhanced Metafile) file.
    Private Sub Export(ByVal report As LocalReport)
    Dim deviceInfo As String = "<DeviceInfo>" & _
    "<OutputFormat>EMF</OutputFormat>" & _
    "<PageWidth>8.5in</PageWidth>" & _
    "<PageHeight>11in</PageHeight>" & _
    "<MarginTop>0.25in</MarginTop>" & _
    "<MarginLeft>0.25in</MarginLeft>" & _
    "<MarginRight>0.25in</MarginRight>" & _
    "<MarginBottom>0.25in</MarginBottom>" & _
    "</DeviceInfo>"
    Dim warnings As Warning()
    m_streams = New List(Of Stream)()
    report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
    For Each stream As Stream In m_streams
    stream.Position = 0
    Next
    End Sub

    ' Handler for PrintPageEvents
    Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
    Dim pageImage As New Metafile(m_streams(m_currentPageIndex))

    ' Adjust rectangular area with printer margins.
    Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX), _
    ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY), _
    ev.PageBounds.Width, _
    ev.PageBounds.Height)

    ' Draw a white background for the report
    ev.Graphics.FillRectangle(Brushes.White, adjustedRect)

    ' Draw the report content
    ev.Graphics.DrawImage(pageImage, adjustedRect)

    ' Prepare for the next page. Make sure we haven't hit the end.
    m_currentPageIndex += 1
    ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
    End Sub

    Private Sub Print()
    If m_streams Is Nothing OrElse m_streams.Count = 0 Then
    Throw New Exception("Error: no stream to print.")
    End If
    Dim printDoc As New PrintDocument()
    If Not printDoc.PrinterSettings.IsValid Then
    Throw New Exception("Error: cannot find the default printer.")
    Else
    AddHandler printDoc.PrintPage, AddressOf PrintPage
    m_currentPageIndex = 0
    printDoc.Print()
    End If
    End Sub

    ' Create a local report for Report.rdlc, load the data,
    ' export the report to an .emf file, and print it.
    'Private Sub Run()
    Private Sub PrintPO()
    Dim report As New LocalReport()
    report.ReportPath = ("C:\Users\JOE\Desktop\Deployment\POS - Copy\POS\rptReceipt.rdlc")
    report.DataSources.Add(New ReportDataSource("ReceiptDataSet", LoadSalesData()))
    Export(report)
    Print()

    End Sub

    Public Overloads Sub Dispose()
    If m_streams IsNot Nothing Then
    For Each stream As Stream In m_streams
    stream.Close()
    Next
    m_streams = Nothing
    End If
    End Sub
    End Class

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width