Share via


How to Print report viewer report

Question

Wednesday, May 11, 2016 2:58 PM

trying to print a report that's already generated on the screen

Private Sub Build_Bessemer_Report()
        Try
            Dim Report As String = "Bessemer_Scale_2.Report_Bessemer_Pipe.rdlc"
            Dim StartDate As String = CDate(DataHelper.InvoiceStartDate).ToShortDateString
            Dim EndDate As String = CDate(DataHelper.InvoiceEndDate).ToShortDateString
            StartDate = StartDate.Replace(":", "_")
            EndDate = EndDate.Replace(":", "_")
            Dim ReportPDFPath As String = "C:\Freight Files\PDF Documents\Bessemer_Report" + "_" + StartDate.Replace("/", "-") + "_To_" + EndDate.Replace("/", "-") + ".Pdf"

            With Me.Report_Viewer.LocalReport
                .ReportEmbeddedResource = Report

                Dim parameters(3) As ReportParameter

                parameters(0) = New ReportParameter("Vendor", DataHelper.InvoiceVendor, True)
                parameters(1) = New ReportParameter("Commodity", DataHelper.InvoiceCommodity, True)
                parameters(2) = New ReportParameter("BeginDate", DataHelper.InvoiceStartDate, True)
                parameters(3) = New ReportParameter("EndDate", DataHelper.InvoiceEndDate, True)
                .SetParameters(parameters)
            End With

            dt = DataHelperFunctions.GetTruckInvoiceVendorCommodity(DataHelper.InvoiceStartDate, DataHelper.InvoiceEndDate, DataHelper.InvoiceVendor, _
                                                                    DataHelper.InvoiceCommodity)
            Truck_Report_Vendor_CommodityBindingSource.DataSource = dt

            Dim rptDataSource As New ReportDataSource("DataSet_Bessemer_Report", Truck_Report_Vendor_CommodityBindingSource)
            Me.Report_Viewer.LocalReport.DataSources.Add(rptDataSource)
            SavePDF(ReportPDFPath, ReportPDFPath, True)

            Print(Me.Report_Viewer.LocalReport)
        Catch ex As Exception
            Dim methodName = CStr(System.Reflection.MethodBase.GetCurrentMethod().Name)
            Dim ClassName = CStr(Me.GetType().Name)
            DataHelperFunctions.ReportException(methodName, ClassName, CStr(ex.ToString), CStr(System.DateTime.Now))
        End Try
    End Sub

All replies (7)

Wednesday, May 11, 2016 6:56 PM âś…Answered | 1 vote

cant download anything sorry, do you have a simple snippet?

This is from that projects main form. I don't know anything about it though.

Imports System
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 System.IO
Imports Microsoft.Reporting.WinForms
Imports System.Reflection

Public Class MainForm
    ' Application name to display in message boxes.
    Private m_appName As String = My.Application.Info.ProductName
    ' Default list of file name extensions to ignore.
    Private m_ignoredExtensions As String() = {".gif", ".jpg", ".png", ".dll", ".js", ".css"}
    ' A collection of LogFileEntry objects, to use as data for the report.
    Private m_logFileEntries As LogFileEntryCollection
    ' Path to folder containing log files.
    Private m_logFolderPath As String

    Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.CenterToScreen()
        ' Default location of log files
        Dim defaultDir As String = Environment.SystemDirectory + Path.DirectorySeparatorChar + _
                                   "Logfiles" + Path.DirectorySeparatorChar + "W3SVC1"
        ' If the default location exists then use it as the default in the folder browser dialog.
        If Directory.Exists(defaultDir) Then
            m_logFolderPath = defaultDir
        Else
            m_logFolderPath = ""
        End If
        Try
            Me.Cursor = Cursors.WaitCursor
            ' Parse the sample log file to use as default data for the report.
            Me.m_logFileEntries = LogParser.ParseLogFile("sample.log", m_ignoredExtensions)
            Me.LogFileEntryBindingSource.DataSource = m_logFileEntries
            ' Process and render the report.
            Me.ReportViewer.RefreshReport()
        Catch ex As IOException
            ' There is no harm if the sample log file cannot be loaded, so ignore the exception.
        Catch ex As LogParserException
            MessageBox.Show(ex.Message, m_appName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub


    Dim i As Integer = 1
    Dim ReportToPrint As New LocalReport
    ''' <summary>
    ''' The drillthrough event handler.
    ''' </summary>
    ''' <remarks>This method supplies data for the drillthrough report.</remarks>
    Private Sub ReportViewer_Drillthrough(ByVal sender As Object, ByVal e As DrillthroughEventArgs) Handles ReportViewer.Drillthrough
        Me.Text = i.ToString
        Dim report As LocalReport = e.Report
        ReportToPrint = e.Report
        report.DataSources.Add(New ReportDataSource("WebLogAnalyzer_LogFileEntry", Me.m_logFileEntries))
        i += 1
    End Sub

    ''' <summary>
    ''' Handler for Open Log Files menu command.
    ''' </summary>
    Private Sub OpenLogFilesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenLogFilesToolStripMenuItem.Click
        ' Display the folder browser dialog.
        Me.FolderBrowserDialog.SelectedPath = Me.m_logFolderPath
        If (Me.FolderBrowserDialog.ShowDialog(Me) = Windows.Forms.DialogResult.OK) Then
            Try
                Me.m_logFolderPath = Me.FolderBrowserDialog.SelectedPath
                Me.Cursor = Cursors.WaitCursor
                ' Parse all log files in the selected folder.
                Me.m_logFileEntries = LogParser.ParseLogFileFolder(Me.m_logFolderPath, m_ignoredExtensions)
                Me.LogFileEntryBindingSource.DataSource = Me.m_logFileEntries
                ' Reinitialize the ReportViewer control with the new data.
                Me.ReportViewer.Reset()
                Me.ReportViewer.LocalReport.DisplayName = My.Resources.ReportDisplayName
                Me.ReportViewer.LocalReport.ReportEmbeddedResource = "WebLogAnalyzer.MainReport.rdlc"
                Me.ReportViewer.LocalReport.DataSources.Add(New ReportDataSource("WebLogAnalyzer_LogFileEntry", Me.LogFileEntryBindingSource))
                Me.ReportViewer.RefreshReport()
            Catch ex As IOException
                MessageBox.Show(ex.Message, m_appName)
            Catch ex As LogParserException
                MessageBox.Show(ex.Message, m_appName)
            Finally
                Me.Cursor = Cursors.Default
            End Try
        End If
    End Sub

    ''' <summary>
    ''' Handler for File > Exit menu command.
    ''' </summary>
    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    ''' <summary>
    ''' Handler for View > Ignore Files menu command.
    ''' </summary>
    Private Sub IgnoreFilesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IgnoreFilesToolStripMenuItem.Click
        Dim dialog As New IgnoredFilesDialog()
        dialog.SetIgnoredExtensions(Me.m_ignoredExtensions)
        If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim extensions(dialog.IgnoredExtensions.Count) As String
            dialog.IgnoredExtensions.CopyTo(extensions, 0)
            Me.m_ignoredExtensions = extensions
        End If
    End Sub

    ''' <summary>
    ''' Handler for Show Document Map menu command.
    ''' </summary>
    Private Sub DocumentMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DocumentMapToolStripMenuItem.Click
        Me.ReportViewer.DocumentMapCollapsed = Not Me.ReportViewer.DocumentMapCollapsed
    End Sub

    ''' <summary>
    ''' Handler for View menu Drop Down Opened event.
    ''' </summary>
    Private Sub ViewToolStripMenuItem_DropDownOpened(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ViewToolStripMenuItem.DropDownOpened
        If Me.ReportViewer.LocalReport.GetDocumentMap() Is Nothing Then
            Me.DocumentMapToolStripMenuItem.Enabled = False
            Me.DocumentMapToolStripMenuItem.Checked = False
        Else
            Me.DocumentMapToolStripMenuItem.Enabled = True
            Me.DocumentMapToolStripMenuItem.Checked = Not Me.ReportViewer.DocumentMapCollapsed
        End If
    End Sub

    ''' <summary>
    ''' Handler for Help > About menu command.
    ''' </summary>
    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        My.Forms.AboutDialog.ShowDialog()
    End Sub

    Dim P1Font As New Font("Cambria", 14)

    Private Sub ReportViewer_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs)
        MessageBox.Show("Hello")
    End Sub

    Private Sub ReportViewer_Click(sender As Object, e As EventArgs) Handles ReportViewer.Click
        MessageBox.Show("Hello")
    End Sub


    ' ________________________________________________________________________________________________________________
    ' Code for printing is below, above code I know nothing about really.
    ' ________________________________________________________________________________________________________________

    Dim m_currentPageIndex As Integer
    Private m_streams As IList(Of Stream)


    Private Sub PrintWithoutDialogToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PrintWithoutDialogToolStripMenuItem.Click
        ReportToPrint.DataSources.Add(New ReportDataSource("WebLogAnalyzer_LogFileEntry", Me.m_logFileEntries))
        ReportToPrint.ReportEmbeddedResource = "WebLogAnalyzer.MainReport.rdlc"
        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)()
        ReportToPrint.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
        For Each stream As Stream In m_streams
            stream.Position = 0
        Next

        Dim printDoc As New PrintDocument()
        printDoc.PrinterSettings.PrinterName = "Microsoft XPS Document Writer"
        Dim ps As New PrinterSettings()
        ps.PrinterName = printDoc.PrinterSettings.PrinterName
        printDoc.PrinterSettings = ps

        AddHandler printDoc.PrintPage, AddressOf PrintDocument_PrintPage
        m_currentPageIndex = 0
        printDoc.Print()
    End Sub

    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 PrintDocument_PrintPage(sender As Object, e As PrintPageEventArgs)
        Dim pageImage As New Metafile(m_streams(m_currentPageIndex))

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

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

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

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

        If e.HasMorePages = False Then
            For Each stream As Stream In m_streams
                stream.Dispose()
            Next
        End If
    End Sub

End Class

La vida loca


Wednesday, May 11, 2016 5:32 PM

You can see if either of the downloads (which are basically the same I believe) work at these two links ReportViewer Samples for Visual Studio 2005 or ReportViewer Samples for Microsoft Visual Studio 2008 and if one or the other works the executable should create two sample projects I believe.

The WebLogAnalyzer project is in VB.Net. It has a menu strip at the top with a selection for printing without displaying the print or print preview dialog. So I suspect the code in it can be used to do whatever you may want to do.

There also appears to be a forum for MS Report Viewer Controls - Visual Studio Report Controls.

La vida loca


Wednesday, May 11, 2016 6:45 PM

cant download anything sorry, do you have a simple snippet?


Wednesday, May 11, 2016 7:03 PM

There should be a toolbar with a print icon. If you want to print programmatically then see the below link:

https://msdn.microsoft.com/en-us/library/ms252091.aspx

Paul ~~~~ Microsoft MVP (Visual Basic)


Thursday, May 12, 2016 3:35 PM

thank you for your response but what does this part mean? Is this related to like hardware settings or margins or something?

Dim deviceInfo As String = "<DeviceInfo><OutputFormat>EMF</OutputFormat><PageWidth>8.5in

Thursday, May 12, 2016 4:19 PM

From google.

"EMF is a file extension for Enhanced MetaFile, a spool file format used in printing by the Windows operating system. When a print job is sent to the printer, if it is already printing another file, the computer reads the new file and stores it, usually on the hard disk or in memory, for printing at a later time"

I suppose that line is used to set the output format as EMF with a page width of 8.5 inches.

La vida loca


Thursday, May 12, 2016 4:45 PM

thank you for your response but what does this part mean? Is this related to like hardware settings or margins or something?

Dim deviceInfo As String = "<DeviceInfo><OutputFormat>EMF</OutputFormat><PageWidth>8.5in

Apparently that tells the LocalReport control? to output WMF which is a vector based scalable format with no resolution losses. And WMF is easy to print as graphics which is what is done in the print routine. And so its better high res print quality output than just printing a form bitmap or jpg file.