Click here to Skip to main content
15,881,424 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Direct print for microsoft_report (RDLC)

Rate me:
Please Sign up or sign in to vote.
4.50/5 (4 votes)
16 Jul 2014CPOL 71.3K   10   26
direct print for microsoft report (RDLC) without preview

Introduction

I used to work with crystal report and when i moved to microsoft report there were some needs i couldn't find (like "print_to_printer" function) , after a google search i found this on msdn , well it does the job (render's rdlc as an image then send it to the default printer with the default paper setup), unfortunately there is not print option :( .

adding a print option's take me some time, I hope this will be helpful to save your time.

Using the code

This is a modul in vb.net , the main public methods is "print_microsoft_report".

It has tow overload's (both with optional parameter's) , first method is to print the report with a custom paper width and height, second is to print the rdlc report with a specific paper kind.

(paper_kind, printer_name and paper_landscap) are optional parameter's.

last thing to mention that i assigned all margin's to 0 (this can easily edited as needs).

VB.NET
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
Module modul_print_reports
    Private m_currentPageIndex As Integer
    Private m_streams As IList(Of Stream)
    Private printdoc As PrintDocument

    ''' <summary>
    ''' Print rdlc report with custom page width and height
    ''' </summary>
    ''' <param name="report"></param>
    ''' <param name="page_width">the width of the papger, in hunderdths of an inch</param>
    ''' <param name="page_height">the height of the papger, in hunderdths of an inch</param>
    ''' <param name="islandscap"></param>
    ''' <param name="printer_name">Ignore this parameter to use default printer</param>
    ''' <remarks></remarks>
    Public Sub print_microsoft_report(ByRef report As LocalReport, ByVal page_width As Integer, ByVal page_height As Integer, _
                                      Optional ByVal islandscap As Boolean = False, _
                                      Optional ByVal printer_name As String = Nothing)
        printdoc = New PrintDocument()
        If printer_name <> Nothing Then printdoc.PrinterSettings.PrinterName = printer_name
        If Not printdoc.PrinterSettings.IsValid Then ' detecate is the printer is exist
            Throw New Exception("Cannot find the specified printer")
        Else
            Dim ps As New PaperSize("Custom", page_width, page_height)
            printdoc.DefaultPageSettings.PaperSize = ps
            printdoc.DefaultPageSettings.Landscape = islandscap
            Export(report)
            Print()
        End If
    End Sub
    ''' <summary>
    ''' Print rdlc report with specific paper kind
    ''' </summary>
    ''' <param name="report"></param>
    ''' <param name="paperkind">String paper Kind, ex:"letter"</param>
    ''' <param name="islandscap"></param>
    ''' <param name="printer_name">Ignore this parameter to use default printer</param>
    ''' <remarks></remarks>
    Public Sub print_microsoft_report(ByVal report As LocalReport, Optional ByVal paperkind As String = "A4", _
                                      Optional ByVal islandscap As Boolean = False, _
                                      Optional ByVal printer_name As String = Nothing)

        printdoc = New PrintDocument()
        If printer_name <> Nothing Then printdoc.PrinterSettings.PrinterName = printer_name
        If Not printdoc.PrinterSettings.IsValid Then ' detecate is the printer is exist
            Throw New Exception("Cannot find the specified printer")
        Else
            Dim ps As PaperSize
            Dim pagekind_found As Boolean = False
            For i = 0 To printdoc.PrinterSettings.PaperSizes.Count - 1
                If printdoc.PrinterSettings.PaperSizes.Item(i).Kind.ToString = paperkind Then
                    ps = printdoc.PrinterSettings.PaperSizes.Item(i)
                    printdoc.DefaultPageSettings.PaperSize = ps
                    pagekind_found = True
                End If
            Next
            If Not pagekind_found Then Throw New Exception("paper size is invalid")
            printdoc.DefaultPageSettings.Landscape = islandscap
            Export(report)
            Print()
        End If

    End Sub

    ' 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 w As Integer
        Dim h As Integer
        If printdoc.DefaultPageSettings.Landscape = True Then
            w = printdoc.DefaultPageSettings.PaperSize.Height
            h = printdoc.DefaultPageSettings.PaperSize.Width
        Else
            w = printdoc.DefaultPageSettings.PaperSize.Width
            h = printdoc.DefaultPageSettings.PaperSize.Height
        End If
        Dim deviceInfo As String = "<DeviceInfo>" & _
            "<OutputFormat>EMF</OutputFormat>" & _
            "<PageWidth>" & w / 100 & "in</PageWidth>" & _
            "<PageHeight>" & h / 100 & "in</PageHeight>" & _
            "<MarginTop>0.0in</MarginTop>" & _
            "<MarginLeft>0.0in</MarginLeft>" & _
            "<MarginRight>0.0in</MarginRight>" & _
            "<MarginBottom>0.0in</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
        AddHandler printdoc.PrintPage, AddressOf PrintPage
        m_currentPageIndex = 0
        printdoc.Print()
    End Sub
End Module

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Iraq Iraq
Software developer
Morabba company

Comments and Discussions

 
QuestionNot working after deploying on server Pin
SAQIB NISAR 202116-Nov-21 7:25
SAQIB NISAR 202116-Nov-21 7:25 
QuestionHow RDLC report print from click button???? Pin
ali walo26-Dec-20 11:26
ali walo26-Dec-20 11:26 
Questionpos bill printing Pin
Member 1175690311-Aug-19 9:45
Member 1175690311-Aug-19 9:45 
QuestionAwesome! Pin
The Cool Cat24-Apr-19 15:12
professionalThe Cool Cat24-Apr-19 15:12 
QuestionI had a proplem with paper size and margins using Custom size 4 by 2 Pin
Member 138864506-Jul-18 10:21
Member 138864506-Jul-18 10:21 
I had a proplem with paper size and margins using Custom size 4 by 2 

QuestionMy report quality degrades with this code. Pin
Rahul R Sutar20-Apr-17 19:00
professionalRahul R Sutar20-Apr-17 19:00 
AnswerRe: My report quality degrades with this code. Pin
M. Rawan23-Apr-17 5:07
M. Rawan23-Apr-17 5:07 
QuestionPOS RECIEPT Pin
Motasim198521-Jun-16 12:27
Motasim198521-Jun-16 12:27 
AnswerRe: POS RECIEPT Pin
M. Rawan27-Jul-16 12:12
M. Rawan27-Jul-16 12:12 
SuggestionWorks fine.... Pin
Member 1231174213-May-16 19:22
Member 1231174213-May-16 19:22 
GeneralRe: Works fine.... Pin
M. Rawan27-Jul-16 12:19
M. Rawan27-Jul-16 12:19 
GeneralRe: Works fine.... Pin
Lisanas2-May-19 20:50
Lisanas2-May-19 20:50 
QuestionConverted this to C# here you go Pin
Oscar Ortiz Arellano19-Apr-16 6:03
Oscar Ortiz Arellano19-Apr-16 6:03 
AnswerRe: Converted this to C# here you go Pin
Member 134852322-Nov-17 3:07
Member 134852322-Nov-17 3:07 
QuestionDirect Print RDLC Pin
Member 106771656-Jul-15 1:41
Member 106771656-Jul-15 1:41 
QuestionPrint Reportwier1 without printdialogue in default printer Pin
Member 1075135722-Apr-15 11:33
Member 1075135722-Apr-15 11:33 
Questionrdlc direct print Pin
VBNetHack14-Feb-15 8:57
VBNetHack14-Feb-15 8:57 
AnswerRe: rdlc direct print Pin
raghavendran from Tiruvallur29-May-15 1:37
professionalraghavendran from Tiruvallur29-May-15 1:37 
QuestionNot working with application hosted on IIS Pin
SRS(The Coder)31-Jan-15 1:46
professionalSRS(The Coder)31-Jan-15 1:46 
AnswerRe: Not working with application hosted on IIS Pin
Naing Win9-Mar-17 22:30
Naing Win9-Mar-17 22:30 
GeneralRe: Not working with application hosted on IIS Pin
M. Rawan23-Apr-17 5:08
M. Rawan23-Apr-17 5:08 
GeneralRe: Not working with application hosted on IIS Pin
SAQIB NISAR 202116-Nov-21 7:27
SAQIB NISAR 202116-Nov-21 7:27 
QuestionRDLC Pin
itsmehaboob7-Jan-15 4:28
professionalitsmehaboob7-Jan-15 4:28 
AnswerRe: RDLC Pin
M. Rawan19-Jan-15 3:58
M. Rawan19-Jan-15 3:58 
Questionrdlc Pin
mufeed k14-Nov-14 18:35
mufeed k14-Nov-14 18:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.