Click here to Skip to main content
15,892,927 members
Articles / Database Development / SQL Server

Microsoft Reporting Services - Part II

Rate me:
Please Sign up or sign in to vote.
4.76/5 (23 votes)
28 Jul 2009CPOL7 min read 141.3K   2.4K   117  
This article shows some tips to improve Microsoft Reports like embedded reports, showing stored images, and images from a path, using custom code and custom assemblies, exporting reports, and printing reports without the ReportViewer control.
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 ReportUtils
    Implements IDisposable

#Region "Export Method"

    Enum rptFormat
        Excel
        PDF
        Image
    End Enum

    ''' <summary>
    ''' Exports an LocalReport 
    ''' </summary>
    ''' <param name="report">LocalReport</param>
    ''' <param name="output">Format</param>
    ''' <remarks></remarks>
    Public Sub Export(ByVal report As LocalReport, ByVal output As rptFormat)

        Try

            Dim warnings As Warning() = Nothing
            Dim streamids As String() = Nothing
            Dim mimeType As String = Nothing
            Dim encoding As String = Nothing
            Dim extension As String = Nothing

            Dim bytes() As Byte = report.Render(output.ToString, Nothing, _
                                    mimeType, encoding, extension, streamids, warnings)

            Dim filePath As String = My.Computer.FileSystem.GetTempFileName()
            Select Case output
                Case rptFormat.Excel
                    filePath = Path.ChangeExtension(filePath, "xls")
                Case rptFormat.Image
                    filePath = Path.ChangeExtension(filePath, "jpg")
                Case rptFormat.PDF
                    filePath = Path.ChangeExtension(filePath, "pdf")
            End Select

            Using fs As New IO.FileStream(filePath, IO.FileMode.Create)
                fs.Write(bytes, 0, bytes.Length)
                fs.Close()
            End Using
            bytes = Nothing

            Process.Start(filePath)

        Catch ex As Exception : End Try

    End Sub


    ''' <summary>
    ''' Exports an LocalReport 
    ''' </summary>
    ''' <param name="report">LocalReport</param>
    ''' <param name="output">Format</param>
    ''' <param name="filePath">File path</param>
    ''' <remarks></remarks>
    Public Sub Export(ByVal report As LocalReport, ByVal output As rptFormat, ByVal filePath As String)

        Try

            Dim warnings As Warning() = Nothing
            Dim streamids As String() = Nothing
            Dim mimeType As String = Nothing
            Dim encoding As String = Nothing
            Dim extension As String = Nothing

            Dim bytes() As Byte = report.Render(output.ToString, Nothing, _
                                    mimeType, encoding, extension, streamids, warnings)

            Using fs As New IO.FileStream(filePath, IO.FileMode.Create)
                fs.Write(bytes, 0, bytes.Length)
                fs.Close()
            End Using
            bytes = Nothing

        Catch ex As Exception : End Try

    End Sub

#End Region

#Region "Print Method"

    Private currentPageIndex As Integer
    Private tmpFileName As String = String.Empty
    Private streamList As List(Of Stream)


    Enum Orientation
        Landscape
        Portrait
    End Enum

    ''' <summary>
    ''' Add the Stream to the list 
    ''' </summary>
    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

        tmpFileName = My.Computer.FileSystem.GetTempFileName()

        Dim s As New FileStream(tmpFileName, FileMode.Create)
        streamList.Add(s)
        Return s

    End Function


    ''' <summary>
    ''' Exports the file to the list of Streams 
    ''' </summary>
    Private Sub ExportToStream(ByVal report As LocalReport, ByVal Orientation As Orientation)
        Dim deviceInfo As New StringBuilder
        With deviceInfo
            .Append("<DeviceInfo>")
            .Append(" <OutputFormat>EMF</OutputFormat>")

            If Orientation = ReportUtils.Orientation.Portrait Then
                .Append(" <PageWidth>8.5in</PageWidth>")
                .Append(" <PageHeight>11.5in</PageHeight>")
            Else
                .Append(" <PageWidth>11.5in</PageWidth>")
                .Append(" <PageHeight>8.5in</PageHeight>")
            End If

            .Append(" <MarginTop>0.3in</MarginTop>")
            .Append(" <MarginLeft>0.3in</MarginLeft>")
            .Append(" <MarginRight>0.3in</MarginRight>")
            .Append(" <MarginBottom>0.3in</MarginBottom>")
            .Append("</DeviceInfo>")
        End With

        Dim warnings() As Warning = Nothing
        report.Render("Image", deviceInfo.ToString, _
                        AddressOf CreateStream, warnings)

        For Each s As Stream In streamList
            s.Position = 0
        Next
        deviceInfo = Nothing

    End Sub


    ''' <summary>
    ''' When the PrintDocument is printing, draw the right page from the list 
    ''' </summary>
    Private Sub PrintPage(ByVal sender As Object, _
                          ByVal ev As PrintPageEventArgs)

        Using pageImage As New Metafile(streamList(currentPageIndex))
            currentPageIndex += 1

            ev.Graphics.DrawImage(pageImage, ev.PageBounds)
            ev.HasMorePages = (currentPageIndex < streamList.Count)
        End Using

    End Sub


    ''' <summary>
    ''' Prints the report without preview 
    ''' </summary>
    ''' <param name="report">Relatório a imprimir</param>
    Public Sub Print(ByVal report As LocalReport, ByVal Orientation As Orientation)

        streamList = New List(Of Stream)

        ' Exports the file to a list of Streams 
        Call ExportToStream(report, Orientation)

        If streamList IsNot Nothing AndAlso streamList.Count > 0 Then

            ' Start the printing process 
            Using printDoc As New PrintDocument()

                If Not printDoc.PrinterSettings.IsValid Then
                    Dim msg As String = "Printer is not available or is not valid!"
                    Throw New ArgumentException(msg)
                End If

                AddHandler printDoc.PrintPage, AddressOf PrintPage
                If Orientation = ReportUtils.Orientation.Portrait Then
                    printDoc.DefaultPageSettings.Landscape = False
                Else
                    printDoc.DefaultPageSettings.Landscape = True
                End If

                printDoc.Print()
            End Using

        End If

    End Sub

    ''' <summary>
    ''' Prints the report without preview
    ''' </summary>
    ''' <param name="report">Report Name</param>
    Public Sub Print(ByVal report As LocalReport)
        Print(report, Orientation.Portrait)
    End Sub


    Public Overloads Sub Dispose() Implements IDisposable.Dispose
        Try

            If streamList IsNot Nothing Then
                For Each s As Stream In streamList
                    s.Close()
                Next
                streamList.Clear()
                streamList = Nothing
            End If

            If tmpFileName <> String.Empty AndAlso IO.File.Exists(tmpFileName) Then
                IO.File.Delete(tmpFileName)
            End If
            tmpFileName = String.Empty

        Catch ex As Exception
            ' ...
        End Try
    End Sub

#End Region

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer
Portugal Portugal
Jorge Paulino
Microsoft Visual Basic MVP
Portuguese Software Developer
VB.NET, ASP.NET, VBA, SQL
http://vbtuga.blogspot.com/

http://twitter.com/vbtuga

Comments and Discussions