vb@rchiv
VB Classic
VB.NET
ADO.NET
VBA
C#
Blitzschnelles Erstellen von grafischen Diagrammen!  
 vb@rchiv Quick-Search: Suche startenErweiterte Suche starten   Impressum  | Datenschutz  | vb@rchiv CD Vol.6  | Shop Copyright ©2000-2024
 
zurück
Rubrik: Datenbanken · DataSet/DataTable   |   VB-Versionen: VB.NET16.03.06
Dataset nach PDF exportieren (.NET)

Ein Dataset mit der itextsharp.dll in eine PDF-Datei exportieren

Autor:   Stefan MährBewertung:     [ Jetzt bewerten ]Views:  32.570 
www.visualsoft-net.deSystem:  WinNT, Win2k, WinXP, Win7, Win8, Win10, Win11 Beispielprojekt auf CD 

Das PDF Format ist schon lange Industriestandard für das Austauschen von Dokumenten. Programmiertools für das Erstellen und Drucken von PDF-Inhalten sind meist nur von teuren Drittanbietern zu bekommen.
Aber es geht auch kostenlos. Mit der itextsharp.dll ( http://itextsharp.sourceforge.net) bekommen wir hierzu ein mächtiges Tool frei Haus geliefert.

Nachfolgendes kleine VB.NET 2005 WinForms-Projekt soll zeigen, wie einfach man z.B. ein Dataset in eine PDF-Datei schreiben kann. Als Datenquelle verwende ich die Northwind.mdb. Die itextsharp.dll kommt in der aktuellen Version 3.1 zum Einsatz.

Erstellen Sie ein neues WinForms Projekt mit folgenden Komponenten auf Ihrem Formular:

  • 1 x Textbox (txtPath)
  • 1 x CommandButton (cmdPath)
  • 1 x Datagridview (gridData)
  • 1 x Progressbar (ProgressBar1)
  • 1 x CommandButton (cmdCreatePDF)

Fügen Sie einen Verweis auf die itextsharp.dll hinzu.

Nun zum Code.

Unsere Imports Anweisungen:

Imports System.Data.OleDb
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO

Die benötigten privaten Variablen:

Private ds As DataSet
Private Const TABELLE As String = "Employees"

Die Form_Load Routine:

Private Sub frmMain_Load(ByVal sender As Object, _
  ByVal e As System.EventArgs) Handles Me.Load
 
  Me.cmdCreatePDF.Enabled = False
End Sub

Der Dateiauswahldialog für die Northwind.mdb:

Private Sub cmdPath_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles cmdPath.Click
 
  Dim opendlg As New OpenFileDialog
  With opendlg
    .InitialDirectory = Application.StartupPath
    .Filter = "Access (*.mdb)|*.mdb"
    .Title = "Northwind DB"
    .FileName = "Northwind.mdb"
    If .ShowDialog = Windows.Forms.DialogResult.OK Then
      Me.txtPath.Text = .FileName
      Call LoadDS()
    End If
  End With
End Sub

Die Laderoutine für das Dataset:

Private Sub LoadDS()
  Dim conn As OleDbConnection = Nothing
  Dim strConn As String = String.Empty
  Dim adapter As OleDbDataAdapter = Nothing
  Dim cmd As OleDbCommand = Nothing
  Dim strSQL As String = String.Empty
 
  Try
    Using conn
      strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &  _
        Me.txtPath.Text & ";"
      conn = New OleDbConnection(strConn)
      conn.Open()
      ds = New DataSet
      strSQL = "SELECT Title, LastName, FirstName, Format(BirthDate, " & _
        "'Short Date'), Format(HireDate, 'Short Date') FROM " & TABELLE
      cmd = New OleDbCommand(strSQL, conn)
      adapter = New OleDbDataAdapter(cmd)
      adapter.Fill(ds)
      Me.gridData.DataSource = ds.Tables(0)
    End Using
 
    Me.cmdCreatePDF.Enabled = True
 
  Catch ex As Exception
    MessageBox.Show(ex.Message)
  End Try
End Sub

Der CreatePDF Aufruf:

Private Sub cmdCreatePDF_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles cmdCreatePDF.Click
 
  Dim saveDlg As New SaveFileDialog
 
  With saveDlg
    .InitialDirectory = Application.StartupPath
    .Filter = "PDF (*.pdf)|*.pdf"
    .Title = "PDF-File"
    If .ShowDialog = Windows.Forms.DialogResult.OK Then
      CreatePDF(.FileName)
    End If
  End With
End Sub

Die Routine die sich um das erstellen des PDF-Dokuments kümmert:

Private Sub CreatePDF(ByVal strFilename As String)
  Dim oDoc As Document = Nothing
  Dim Writer As PdfWriter = Nothing
  Dim line As Long
  Dim colPos As Long
  Dim t As iTextSharp.text.Table = Nothing
  Dim tCell As Cell = Nothing
 
  Try
    Me.ProgressBar1.Visible = True
    Me.ProgressBar1.Minimum = 0
    Me.ProgressBar1.Maximum = ds.Tables(0).Rows.Count
 
    ' --> PDF Document erstellen
    oDoc = New Document(PageSize.A4, 20, 20, 20, 20)
    Writer = PdfWriter.GetInstance(oDoc, New FileStream(strFilename, _
      FileMode.Create))
    Writer.Open()
    oDoc.Open()
 
    ' --> Dokumententitel
    oDoc.Add(New Paragraph(TABELLE, _
      FontFactory.GetFont(FontFactory.TIMES_ROMAN, 14, style:=1)))
 
    ' -->  ContentTabelle erstellen
    t = New iTextSharp.text.Table(ds.Tables(0).Columns.Count)
    t.AutoFillEmptyCells = True
    t.BorderWidth = 0
    t.Border = 0
    t.Padding = 5
    t.WidthPercentage = 100
 
    Dim zeile As Integer = 0
 
    ' --> Headerzeile erstellen
    For Each col As DataColumn In ds.Tables(0).Columns
      tCell = New Cell(col.Caption)
      tCell.Header = True
      tCell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY
      tCell.Border = iTextSharp.text.Rectangle.BOTTOM_BORDER
      t.AddCell(tCell, line, colPos)
      colPos += 1
    Next
    line += 1
 
    colPos = 0
 
    ' --> Datencontent erstellen
    For Each row As DataRow In ds.Tables(0).Rows
      For Each col As DataColumn In ds.Tables(0).Columns
        tCell = New Cell(row(col.Caption).ToString)
        tCell.Border = 0
        tCell.BorderWidth = 3
        t.AddCell(tCell, line, colPos)
        colPos += 1
      Next
      colPos = 0
      line += 1
      Application.DoEvents()
      Me.ProgressBar1.Value += 1
    Next
 
    ' --> Tabelle an Dokument anfügen
    oDoc.Add(t)
 
    ' --> Objekte schliessen
    oDoc.Close()
    Writer.Close()
 
    Me.ProgressBar1.Visible = False
 
    If MessageBox.Show("Erstellte Datei anzeigen?", "Frage", _
      MessageBoxButtons.YesNo, MessageBoxIcon.Question) = _
      Windows.Forms.DialogResult.Yes Then
 
      Call OpenFile(strFilename)
    End If
 
  Catch ex As Exception
    MessageBox.Show(ex.Message)
  End Try
End Sub

Eine Hilfsfunktion für das aufrufen der erstellten PDF-Datei:

Private Sub OpenFile(ByVal strFile As String)
  Try
    System.Diagnostics.Process.Start(strFile)
  Catch ex As Exception
    MessageBox.Show(ex.Message)
  End Try
End Sub

Wie Sie sehen können ist es ein leichtes kostenlos PDF-Exporte zu erstellen.