Translate

Dienstag, 12. Mai 2015

Visual Basic .net Datagridview in PDF exportieren


Export Windows Forms DataGridView to PDF using iTextSharp, C# and VB.Net

25 May 2014  
6 Comments   23301 Views

Here Mudassar Ahmed Khan has explained how to export DataGridView data to PDF file in Windows Forms (WinForms) Applications using iTextSharp PDF conversion library, C# and VB.Net.

DataGridView cannot be exported directly to PDF file and hence need to make use of iTextSharp Table for this purpose.

In this article I will explain how to export DataGridView data to PDF file in Windows Forms (WinForms) Applications using iTextSharp PDF conversion library, C# and VB.Net.
DataGridView cannot be exported directly to PDF file and hence need to make use of iTextSharp Table for this purpose.
 
Form Controls
I have added a DataGridView and a Button to the Windows Form.
Export Windows Forms DataGridView to PDF using iTextSharp, C# and VB.Net
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using System.Reflection;
using iTextSharp.text.pdf;
using iTextSharp.text;
 
VB.Net
Imports System.IO
Imports System.Data
Imports System.Reflection
Imports iTextSharp.text
Imports iTextSharp.text.pdf
 
 
Populating DataGridView
In order to populate the DataGridView, I have created a dynamic DataTable with some sample data.
C#
public Form1()
{
    InitializeComponent();
    this.BindDataGridView();
}
 
private void BindDataGridView()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
            new DataColumn("Name", typeof(string)),
            new DataColumn("Country",typeof(string)) });
    dt.Rows.Add(1, "John Hammond", "United States");
    dt.Rows.Add(2, "Mudassar Khan", "India");
    dt.Rows.Add(3, "Suzanne Mathews", "France");
    dt.Rows.Add(4, "Robert Schidner", "Russia");
    this.dataGridView1.DataSource = dt;
}
 
VB.Net
Public Sub New()
    InitializeComponent()
    Me.BindDataGridView()
End Sub
 
Private Sub BindDataGridView()
    Dim dt As New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("Id", GetType(Integer)), _
                                           New DataColumn("Name", GetType(String)), _
                                           New DataColumn("Country", GetType(String))})
    dt.Rows.Add(1, "John Hammond", "United States")
    dt.Rows.Add(2, "Mudassar Khan", "India")
    dt.Rows.Add(3, "Suzanne Mathews", "France")
    dt.Rows.Add(4, "Robert Schidner", "Russia")
    Me.dataGridView1.DataSource = dt
End Sub
 
Export Windows Forms DataGridView to PDF using iTextSharp, C# and VB.Net
 
 
Exporting DataGridView data to PDF
Inside the Button Click event handler, I have written the code for exporting DataGridView data to PDF file.
An iTextSharp PDF Table is created with columns same as that of the DataGridView and then a loop is executed over the DataGridView columns to add their header texts to the PDF Table header row.
Once the header row is populated then loop is executed over the DataGridView rows to create the PDF Table rows.
Then a directory (folder) is created if it does not exists. This folder will be used to save the generated PDF file.
Finally the PDF Table is added to the iTextSharp PDF document and then the PDF document is saved as PDF file to the directory that we had created earlier.
C#
private void btnExportPdf_Click(object sender, EventArgs e)
{
    //Creating iTextSharp Table from the DataTable data
    PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);
    pdfTable.DefaultCell.Padding = 3;
    pdfTable.WidthPercentage = 30;
    pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
    pdfTable.DefaultCell.BorderWidth = 1;
 
    //Adding Header row
    foreach (DataGridViewColumn column in dataGridView1.Columns)
    {
        PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
        cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
        pdfTable.AddCell(cell);
    }
 
    //Adding DataRow
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            pdfTable.AddCell(cell.Value.ToString());
        }
    }
 
    //Exporting to PDF
    string folderPath = "C:\\PDFs\\";
    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
    }
    using (FileStream stream = new FileStream(folderPath + "DataGridViewExport.pdf", FileMode.Create))
    {
        Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
        PdfWriter.GetInstance(pdfDoc, stream);
        pdfDoc.Open();
        pdfDoc.Add(pdfTable);
        pdfDoc.Close();
        stream.Close();
    }
}
 
VB.Net
Private Sub btnExportPDF_Click(sender As System.Object, e As System.EventArgs) Handles btnExportPDF.Click
    'Creating iTextSharp Table from the DataTable data
    Dim pdfTable As New PdfPTable(dataGridView1.ColumnCount)
    pdfTable.DefaultCell.Padding = 3
    pdfTable.WidthPercentage = 30
    pdfTable.HorizontalAlignment = Element.ALIGN_LEFT
    pdfTable.DefaultCell.BorderWidth = 1
 
    'Adding Header row
    For Each column As DataGridViewColumn In dataGridView1.Columns
        Dim cell As New PdfPCell(New Phrase(column.HeaderText))
        cell.BackgroundColor = New iTextSharp.text.Color(240, 240, 240)
        pdfTable.AddCell(cell)
    Next
 
    'Adding DataRow
    For Each row As DataGridViewRow In dataGridView1.Rows
        For Each cell As DataGridViewCell In row.Cells
            pdfTable.AddCell(cell.Value.ToString())
        Next
    Next
 
    'Exporting to PDF
    Dim folderPath As String = "C:\PDFs\"
    If Not Directory.Exists(folderPath) Then
        Directory.CreateDirectory(folderPath)
    End If
    Using stream As New FileStream(folderPath & "DataGridViewExport.pdf", FileMode.Create)
        Dim pdfDoc As New Document(PageSize.A2, 10.0F, 10.0F, 10.0F, 0.0F)
        PdfWriter.GetInstance(pdfDoc, stream)
        pdfDoc.Open()
        pdfDoc.Add(pdfTable)
        pdfDoc.Close()
        stream.Close()
    End Using
End Sub
 
Export Windows Forms DataGridView to PDF using iTextSharp, C# and VB.Net
 
 
Downloads
Related Articles
Comments
kennethJun 04, 2014 06:06 AM  121.54.58.247  
I will try this one if it is really working.. Thanks for Sharing..
SACHIN JAINAug 06, 2014 09:08 AM  180.149.39.40  
NICE WORK its working for me. Thanks
NandeshwarFeb 10, 2015 12:02 PM  122.172.166.118  
Finally its working.. Its very useful for me.. Thanks a lot
GouthamApr 08, 2015 09:04 AM  106.51.141.139  
thanks alottt....
sreenivasApr 17, 2015 12:04 PM  198.133.214.10  
Thanks Its working
Add Comments
You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.


Captcha

Montag, 11. Mai 2015

Visual Basic .net eine Textspalte einer Datagridview mit Zeilenumbruch versehen

Datagridview.Columns(4).DefaultCellStyle.WrapMode = DataGridViewTriState.True

Samstag, 9. Mai 2015

Bitte spenden!!!



Wer die Software gut findet, kann gerne Bitcoins spenden ;)

Bitcoin-Adresse: 1ADvphhiAoHTHepUaeFxYMSoX3fuc5ZShq Nicht mehr aktuell


Bitcoins spenden-HowTo




1. Registriere dich auf Litebit.eu (Standorte Niederlande!) und bestätige deine E-Mail Adresse
2. Logge dich ein und klicke auf "Kaufen"
3. Trage beim Betrag den Spendenbetrag in Euro ein.
4. Trage bei Empfangsadresse unsere Bitcoin Adresse ein: 1ADvphhiAoHTHepUaeFxYMSoX3fuc5ZShq Nicht mehr aktuell



5. Wähle bei Zahlungsmethode: Sofort (Sofortüberweisung) oder GiroPay aus
6. Klicke auf "Nächste" und der Rest erklärt sich von selbst!

Zahlungsinformationen
URI: bitcoin:1ADvphhiAoHTHepUaeFxYMSoX3fuc5ZShq?label=Software-H%C3%A4mmer%20Electronics Nicht mehr aktuell 
Adresse: 1ADvphhiAoHTHepUaeFxYMSoX3fuc5ZShq Nicht mehr aktuell
Bezeichnung: Software-Hämmer Electronics


AES-TextCryptor

AES-TextCryptor






Ein Programm, um Texte mit AES zu verschlüsseln. 
Download (GDrive)
Download (Dropbox)
Download (Sourceforge)

Lizenz
Manual (Englisch) 
Manual (Deutsch)  

Plattform: Windows mit .Net 4.5.1 

Setup-Manager für Programme, die als .exe schon vorliegen


Freitag, 8. Mai 2015

Visual Basic.net RSA-Verschlüsselung für Texte

'RSA
    ' Verschlüsseln
    Public Function RSAEncrypt(ByVal RSAKeySize As Int32, ByVal DataToEncrypt() As Byte, ByVal RSAKeyInfo As RSAParameters, ByVal DoOAEPPadding As Boolean) As Byte()
        Try
            Dim encryptedData() As Byte
            'Create a new instance of RSACryptoServiceProvider.
            Using RSA As New RSACryptoServiceProvider(RSAKeySize)

                'Import the RSA Key information. This only needs
                'toinclude the public key information.
                RSA.ImportParameters(RSAKeyInfo)

                'Encrypt the passed byte array and specify OAEP padding.  
                'OAEP padding is only available on Microsoft Windows XP or
                'later. 
                encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding)
            End Using
            Return encryptedData
            'Catch and display a CryptographicException  
            'to the console.
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return Nothing
        End Try
    End Function

    ' Entschlüsseln
    Public Function RSADecrypt(ByVal RSAKeySize As Int32, ByVal DataToDecrypt() As Byte, ByVal RSAKeyInfo As RSAParameters, ByVal DoOAEPPadding As Boolean) As Byte()
        Try
            Dim decryptedData() As Byte
            'Create a new instance of RSACryptoServiceProvider.
            Using RSA As New RSACryptoServiceProvider(RSAKeySize)
                'Import the RSA Key information. This needs
                'to include the private key information.
                RSA.ImportParameters(RSAKeyInfo)

                'Decrypt the passed byte array and specify OAEP padding.  
                'OAEP padding is only available on Microsoft Windows XP or
                'later. 
                decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding)
                'Catch and display a CryptographicException  
                'to the console.
            End Using
            Return decryptedData
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return Nothing
        End Try
    End Function
    'RSA



Visual Basic.net Textdatei schreiben

Try
            ' Datei öffnen
            Dim fs As FileStream = New FileStream(DATEINAME, FileMode.OpenOrCreate, FileAccess.Write)
            'Stream öffnen
            Dim w As StreamWriter = New StreamWriter(fs)
            'Anfügen am Ende
            w.BaseStream.Seek(0, SeekOrigin.End)
            'Zeilen schreiben
            w.Write("Test")
            w.WriteLine()
            'Writer und Stream schließen
            w.Close()
            fs.Close()
        Catch ex As Exception
            MessageBox.Show(ex.toString) 'Fehlermeldung ausgeben
        End Try



Visual Basic.net Textdatei lesen

Try
            'Datei öffnen
            Dim fs As FileStream = New FileStream(DATEINAME, FileMode.OpenOrCreate, FileAccess.ReadWrite)
            'Stream öffnen
            Dim r As StreamReader = New StreamReader(fs)
            'Zeiger auf den Anfang
            r.BaseStream.Seek(0, SeekOrigin.Begin)
            'Alle Zeilen lesen und an Console ausgeben
            While r.Peek() > -1
                MessageBox.Show((r.ReadLine()))
            End While
            'Reader und Stream schließen
            r.Close()
            fs.Close()
        Catch ex As Exception
            MessageBox.Show(ex.toString) 'Fehlermeldung ausgeben
        End Try



Mittwoch, 6. Mai 2015

Montag, 4. Mai 2015

Visual Basic.net CSV-Export speichern

Dim CSV_SaveFileDialog As New SaveFileDialog
        CSV_SaveFileDialog.InitialDirectory = "C:"
        CSV_SaveFileDialog.Filter = "CSV-Dateien|*.csv"
        CSV_SaveFileDialog.Title = "Wählen Sie einen Dateititel zum Speichern aus"
        If CSV_SaveFileDialog.ShowDialog() = DialogResult.OK Then
            MsgBox("Datei gespeichert unter: " & CSV_SaveFileDialog.FileName)
        Else
            MsgBox("Abbruch")
        End If

Visual Basic.net Äquivalent zu App.Path in Visual Basic 6

System.AppDomain.CurrentDomain.BaseDirectory()

Visual Basic.net Mails per SMTP-Server versenden

https://www.vb-paradise.de/index.php/Thread/6931-E-Mail-senden-per-SMTP-Simple-Mail-Transfer-Protocol/
https://msdn.microsoft.com/de-de/library/bb979096.aspx

Dim Message As New MailMessage
        Dim Login As New System.Net.NetworkCredential
        Login.UserName = "andreas@absender.de"
        Login.Password = "Passwort des Absenders"
        Message.IsBodyHtml = False
        Dim SMTPServer As New SmtpClient()
        SMTPServer.Host = "smtp.web.de" 'bei web.de
        SMTPServer.Port = 25
        SMTPServer.UseDefaultCredentials = False
        SMTPServer.Credentials = Login
        Try
            Message.From = New MailAddress("andreas@absender.de")
            Message.To.Add("entchen@empfänger.de")
            Message.Subject = "Betreff"
            Message.Body = "Inhalt"
            SMTPServer.Send(Message)
            MsgBox("E-Mail gesendet.", MsgBoxStyle.Information, Title:="Information")
        Catch ex As Exception
            MsgBox(ex.Message) 'Fehlermeldung ausgeben
        End Try

Visual Basic.net ToolTips setzen

toolTip1.SetToolTip(Me.button1, "My button1")

Gute Seite für Icons


Visual Basic.net-Eine Form maximieren

Me.WindowState = FormWindowState.Maximized 'Form maximieren

Visual Basic.net-Double-Zahlen für SQL-Befehl formatieren

Value.ToString("G", New System.Globalization.CultureInfo("en-US")))

--> Ändert 1,00 auf 1.00

Code-Converter für C#, Visual Basic.net, Boo, Phyton, Ruby


Kalenderwoche aus Datum berechnen-C# und Visual Basic.net

C#:

public static int berechneKalenderwoche(DateTime datum)
{
      int kalenderwoche = (datum.DayOfYear/7)+1;
      if (kalenderwoche == 53) kalenderwoche = 1;
      return kalenderwoche;
}

Visual Basic.net:

Public Shared Function berechneKalenderwoche(datum As DateTime) As Integer
    Dim kalenderwoche As Integer = (datum.DayOfYear / 7) + 1
    If kalenderwoche = 53 Then
        kalenderwoche = 1
    End If
    Return kalenderwoche
End Function

Samstag, 2. Mai 2015

Island-Schöne Bilder

















Eigenen Linux vServer mit Apache Web- und MySQL Server unter Windows aufsetzen [Deutsch][HD]


Twitter: @FranzHuber23
Twitter: @TheFranzHuber23
Homepage
Keine Homepage
Facebook
Facebook
Youtube:FranzHuber23
Youtube:HansDampf99984
Youtube:LetsZockClassic
Youtube:Elon Musk
Google+:FranzHuber23
Google+:LetsZockClassic
Google+:HansDampf99984
Google+:Elon Musk

Online Passwortgenerator


Donnerstag, 30. April 2015

Visual Basic .net Strings mit AES verschlüsseln

Option Strict On

Imports System.Security.Cryptography

Public Class cCrypt

#Region "Zustandsvariablen"
    Private EncryptedString_ As String
    Private DecryptedString_ As String
#End Region

    Public Sub New()

    End Sub

#Region "Methoden"
    ' Verschlüsseln
    Public Sub Encrypt(ByVal AESKeySize As Int32, _
      ByVal DecryptedString As String, _
      ByVal Password As String)

        ' Der Salt-Wert ist eine zufällig gewählte Zeichenfolge,
        ' wenn man so will ein zweites Passwort.
        ' Nur wer den Salt-Wert und das Passwort kennt,
        ' kann entschlüsseln.
        ' Durch Verwendung eines Salt-Wertes ist es deutlich
        ' schwerer das Passwort zu knacken.
        ' Wird das Passwort selber zur Erstellung des Salt-Wertes
        ' verwendet, muss dieses mindestens 8 Zeichen haben.
        Dim Salt() As Byte
        Salt = System.Text.Encoding.UTF8.GetBytes( _
          "12345")

        ' Mit Hilfe des Passwortes und des Salt wird ein Key (Hash-Wert)
        ' generiert, der später zur Initialisierung des
        ' AES-Algorithmus verwendt wird.
        Dim GenerierterKey As New Rfc2898DeriveBytes(Password, Salt)

        ' Instanzierung des AES-Algorithmus-Objekts mit 256-bit
        ' oder 256-bit Schlüssel und 256-bit Block-Size
        Dim AES As New AesManaged
        AES.KeySize = AESKeySize ' möglich sind 128 oder 256 bit
        AES.BlockSize = 128

        ' Algorithmus initialisieren:
        AES.Key = GenerierterKey.GetBytes(AES.KeySize \ 8)
        AES.IV = GenerierterKey.GetBytes(AES.BlockSize \ 8)

        ' Memory-Stream und Crypto-Stream erzeugen -> CreateEncryptor()
        Dim ms As New IO.MemoryStream
        Dim cs As New CryptoStream(ms, AES.CreateEncryptor(), _
          CryptoStreamMode.Write)

        ' Daten verschlüsseln:
        Dim Data() As Byte
        Data = System.Text.Encoding.UTF8.GetBytes(DecryptedString)
        cs.Write(Data, 0, Data.Length)
        cs.FlushFinalBlock()
        cs.Close()

        ' Verschlüsselte Daten als String ausgeben:
        EncryptedString_ = Convert.ToBase64String(ms.ToArray)
        ms.Close()

        AES.Clear()

    End Sub

    ' Entschlüsseln
    Public Sub Decrypt(ByVal AESKeySize As Int32, _
      ByVal EncryptedString As String, _
      ByVal Password As String)

        ' Der Salt-Wert und das Passwort müssen mit dem übereinstimmen,
        ' das bei der Verschlüsselung verwendet wurde:
        Dim Salt() As Byte
        Salt = System.Text.Encoding.UTF8.GetBytes( _
          "12345")

        Dim GenerierterKey As New Rfc2898DeriveBytes(Password, Salt)

        ' Instanzierung des AES-Algorithmus-Objekts:
        Dim AES As New AesManaged
        ' Ein mit 256 bit verschlüsselter String kann
        ' auch nur mit 256 bit entschlüsselt werden!
        AES.KeySize = AESKeySize ' möglich sind 128 oder 256 bit
        AES.BlockSize = 128

        ' Algorithmus initialisieren:
        AES.Key = GenerierterKey.GetBytes(AES.KeySize \ 8)
        AES.IV = GenerierterKey.GetBytes(AES.BlockSize \ 8)

        ' Memory-Stream und Crypto-Stream erzeugen -> CreateDecryptor()
        Dim ms As New IO.MemoryStream
        Dim cs As New CryptoStream(ms, AES.CreateDecryptor(), _
          CryptoStreamMode.Write)

        Try ' Daten entschlüsseln:
            Dim Data() As Byte
            Data = Convert.FromBase64String(EncryptedString)
            cs.Write(Data, 0, Data.Length)
            cs.FlushFinalBlock()
            cs.Close()

            ' Die entschlüsselten Daten als String ausgeben:
            DecryptedString_ = System.Text.Encoding.UTF8.GetString(ms.ToArray)
            ms.Close()

            AES.Clear()
        Catch ex As Exception
            DecryptedString_ = "Ungültiges Passwort!"
        End Try

    End Sub
#End Region

#Region "Eigenschaften"
    ReadOnly Property EncryptedString() As String
        Get
            Return EncryptedString_
        End Get
    End Property


    ReadOnly Property DecryptedString() As String
        Get
            Return DecryptedString_
        End Get
    End Property
#End Region

End Class
 

Visual Basic .net-Datagridview Spalten auf Datum/ Währung formatieren

Me.dataGridView1.Columns("UnitPrice").DefaultCellStyle.Format = "c"
Me.dataGridView1.Columns("ShipDate").DefaultCellStyle.Format = "d"

Visual Basic .net-Datagridview sortieren

DataGridView.Sort(DataGridView.Columns(1), System.ComponentModel.ListSortDirection.Ascending)

DataGridView.Sort(DataGridView.Columns(1), System.ComponentModel.ListSortDirection.Descending)