Visual Basic em Português

Página pessoal de Jorge Paulino sobre o Visual Basic (VB.NET, ASP.NET, VB6, VBA) e algumas noticias de tecnologia

VB.NET: Microsoft Reports – Imprimir e Exportar (actualização)

Em dois artigos anteriores, mostrei como se pode de uma forma simples, exportar e imprimir um relatório (*.rdlc) sem a utilização do controlo ReportViewer.

VB.NET: Microsoft Reports – Imprimir sem utilizar o ReportViewer
VB.NET: Microsoft Reports – Exportar Relatórios

No entanto, o exemplo de impressão que mostrei funcionava apenas caso o relatório estivesse definido com Portrait(retrato). Isto porque o método Render() é feito para uma definição, através do DeviceInfo, especifica para este formato. Para imprimir como Landscape(paisagem) é apenas necessário alterar essa definição.

Como surgiram algumas dúvidas, resolvi mostrar a classe alterada e que normalmente uso, com a possibilidade de definir no método Print(), o formato da impressão.

Os exemplos de utilização e comentários, estão disponíveis nos artigos anteriores.


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"

  
Enum rptFormat
        Excel
        PDF
        Image
    End Enum

  
'''<summary>
  
''' Exporta um LocalReport para um formato definido
    '''
</summary>
  
'''<param name="report">LocalReport</param>
  
'''<param name="output">Formato final</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>
  
''' Exporta um LocalReport para um formato definido
    '''
</summary>
  
'''<param name="report">LocalReport</param>
  
'''<param name="output">Formato final</param>
  
'''<param name="filePath">Caminho para o ficheiro</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"

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


    Enum Orientation
        Landscape
        Portrait
    End Enum

   
''' <summary>
   
''' Adiciona a stream à lista de streams
    '''
</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>
   
''' Exporta o ficheiro para uma lista de Streams
    '''
</summary>
   
Private Sub ExportToStream(ByVal report As LocalReport, _
                              ByVal Orientation AsOrientation)

        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>
  
''' Quando o PrintDocument está a imprimir, desenha
    ''' a página correspondente da lista de Stream
    '''
</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>
  
''' Imprime um relatório sem visualização
    '''
</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)

        ' Exporta o ficheiro para uma lista de Streams
      
Call ExportToStream(report, Orientation)

        If streamList IsNot Nothing AndAlso streamList.Count > 0 Then

          
' Inicia o processo de impressão
          
Using printDoc As New PrintDocument()

                If Not printDoc.PrinterSettings.IsValid Then
                    Dim
msg As String= "Impressora não disponível ou não válida!"
                  
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>
  
''' Imprime um relatório sem visualização
    '''
</summary>
  
'''<param name="report">Relatório a imprimir</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

0 comentários:

Mensagens Recentes



Microsoft Office Especialist

Membro da Comunidade
Experts-Exchange


Administ. da Comunidade
Portugal-a-Programar



Twitter

Artigos no CodeProject

Artigos no CodeProject

Subscrever Novidades

Endereço de Email:

Delivered by FeedBurner

Seguidores

Histórico