locked
Exporting or printing data to PDF RRS feed

  • Question

  • Please help,

    I  am struggling to get a code to print data from a form(vb.net) to pdf or to printer.I want to use 


        Private Sub PrintToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PrintToolStripMenuItem.Click
            'code to come in here

        End Sub

    Below is a code which filters or popule form, i want to be able to print this date to PDF

    Private Sub BtnFilter_Click(sender As Object, e As EventArgs) Handles BtnFilter.Click
            Try
                Call ConnectionResults()
                cm = New OleDb.OleDbCommand
                With cm
                    .Connection = cnR
                    .CommandType = CommandType.Text
                    .CommandText = "Select serialnumber,(select count(*)from Passes where WorksOrder='" & TxtWorksOrderFilter.Text & "') from Passes"
                    dr = .ExecuteReader
                End With
    
                ' strSQL = "Select serialnumber,(select count(*)from Passes where WorksOrder='" & TxtWorksOrderFilter.Text & "') from Passes"
                PassesBindingSource.Filter = "WorksOrder='" & TxtWorksOrderFilter.Text & "'"
                DataGridView1.Refresh()
                'Debug.Print("Me.ResultsDataSet.Passes.Count")
    
                'dr = cm.ExecuteReader()
                While (dr.Read())
                    'MessageBox.Show(dr(0).ToString())
                    ' MessageBox.Show(dr(1).ToString())
                    TxtQTY.Text = dr(1).ToString()
                End While
            Catch ex As Exception
                MessageBox.Show(ex.Message)
    
            End Try
            '
        End Sub
    Your guidance will be appreciated

    Saturday, August 12, 2017 6:35 PM

All replies

  • Hi SIsyb,

    According to your description, you want to export data that you filter from database to PDF. now you have filtered data from database into DataGridView, you can refer to the code below to export these data to PDF.

    First  add the itextsharp.dll into application.

     '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.BaseColor(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 = "D:\test\"
            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

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, August 14, 2017 3:04 AM
  • Hi Cherry,

    I have implemented your code and modified folderpath accordingly.

    The code runs smoothly, without any error and print the PDF file.

    The problem i get now is that my data is exported vertically.For instance if the header is "Here" it will export as" h

                   e

                    r

                     e"

    The data would be in the same format

    how do i fix this?

    Wednesday, December 13, 2017 2:41 PM
  •  iTextSharp is a pretty good library for working with and creating Pdf documents.  You could also install the Free version of Bullzip - Pdf Printer on your computer which acts like an installed Printer.  It can be used from any program to print to a Pdf file.  It is free for personal and commercial use up to 10 users.

     Then you can just use the standard .Net printing controls to print it, such as the PrintDocument Class.  If you want to preview the document before printing it or set some page settings,  you can use the PrintPreviewDialog Class and/or the PrintDialog Class in conjunction with the PrintDocument class.  However,  you can set the printer to use,  paper sizes,  margins, and all that without using those too.

     Without seeing how you want the page to look,  i really can not give an example.  Maybe a small example image of how you want the page(s) to look and how your data is set up in the DataGridView would help better than words could explain.


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Wednesday, December 13, 2017 3:23 PM
    Wednesday, December 13, 2017 3:17 PM
  • The problem i get now is that my data is exported vertically.For instance if the header is "Here" it will export as" h

                   e

                    r

                     e"

    The data would be in the same format

    how do i fix this?

     As i said in my last post,  it might help if we saw an image of your DataGridView.  It would also surely help to see the exact code you used too.  I can only think there is something changed or there is a Newline and/or Return character in the text or code.  I just tested kunmo bo's example and it seems to be working fine for me.

     My DataGridView...

     

     And here is the table it created in my pdf file...


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Thursday, December 14, 2017 1:45 AM
    Thursday, December 14, 2017 1:44 AM
  • Hello,


    I have now created just a simple form and polulated data from the SQL.

    Stangely, i now get an error on "pdftable.addcell(cell.value.tostring()) 

    System.NullReferenceException: 'Object reference not set to an instance of an object.'

            
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim pdfTable As New PdfPTable(TempDataGridView.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 TempDataGridView.Columns
                Dim cell As New PdfPCell(New Phrase(column.HeaderText))
                'cell.BackgroundColor = New iTextSharp.text.BaseColor(240, 240, 240)
                pdfTable.AddCell(cell)
            Next
    
            'Adding DataRow
            For Each row As DataGridViewRow In TempDataGridView.Rows
                For Each cell As DataGridViewCell In row.Cells
                    pdfTable.AddCell(cell.Value.ToString())
                Next
            Next
    
            'Exporting to PDF
            Dim folderPath As String = "C:H162420\Desktop\test\"
        End Sub
    End Class

    

    Thursday, December 14, 2017 4:18 PM
  •  That is because you have the DataGridView's AllowUserToAddRows property set to True.  Notice the new row at the bottom of the datagridview,  that is where the erxception is being generated from,  the cells in that row have no value set.

     You can either set the AllowUserToAddRows to False,  or you can check if it is a New Row inside the loop as seen below...

            'Adding DataRow
            For Each row As DataGridViewRow In TempDataGridView.Rows
                If Not row.IsNewRow Then 'make sure it is not a New Row before trying to access the cells of the row
                    For Each cell As DataGridViewCell In row.Cells
                        pdfTable.AddCell(cell.Value.ToString())
                    Next
                End If
            Next


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Thursday, December 14, 2017 4:33 PM
    • Proposed as answer by Frank L. Smith Thursday, December 14, 2017 5:24 PM
    Thursday, December 14, 2017 4:32 PM
  •  PS - Your FolderPath seems to be missing the backslash after the drive letter.  It should be...

            'Exporting to PDF
            Dim folderPath As String = "C:\H162420\Desktop\test\"
    


    If you say it can`t be done then i`ll try it

    Thursday, December 14, 2017 4:37 PM
  • Great!!!

    Getting somewhere.

    Now just have to see why does fail on my original project .....Let me just try it and update you.

    Thank you so much so far

    Thursday, December 14, 2017 4:47 PM
  • Great!!!

    Getting somewhere.

    Now just have to see why does fail on my original project .....Let me just try it and update you.

    Thank you so much so far


    iTextSharp works well but do be sure to read the license (it's not free).

    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, December 14, 2017 5:24 PM
  • iTextSharp works well but do be sure to read the license (it's not free).

    "A problem well stated is a problem half solved.” - Charles F. Kettering

     Huh.. I did not know about the commercial use license.  I did know it is Open Source though.  I did find some info on the requirements/limitations (link below) for iTextSharp.  If you don't meet the requirements and don't want to purchase a license,  the PDFsharp library is supposedly free of charge for commercial use according to the info given at that link.

     I would investigate it further yourself though,  you can't take everything typed in a post as a fact.  8)

    Stackoverflow - free alternative to iTextSharp


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Thursday, December 14, 2017 6:00 PM
    Thursday, December 14, 2017 5:59 PM

  •  Huh.. I did not know about the commercial use license.  I did know it is Open Source though.  I did find some info on the requirements/limitations (link below) for iTextSharp.  If you don't meet the requirements and don't want to purchase a license,  the PDFsharp library is supposedly free of charge for commercial use according to the info given at that link.

     I would investigate it further yourself though,  you can't take everything typed in a post as a fact.  8)

    Stackoverflow - free alternative to iTextSharp


    If you say it can`t be done then i`ll try it

    The reason I suggested that he look at the license is because I don't want to misstate something but I remember looking at this a while back (years) and as I recall, you either buy it or you agree that your software is open-source and in that, you divulge all of your source code. If you're willing to do that, he's willing to give it away for free.

    I'll see if I can find something that supports that though - it's based on my memory only here...


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, December 14, 2017 6:06 PM
  • IR,

    This is old but so far as I know it's correctly stated:

    https://stackoverflow.com/questions/1762842/is-the-itextsharp-dll-free-to-use-and-redistribute-with-my-web-application-proje


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, December 14, 2017 6:09 PM
  • SisyB,

     I have been messing around a little with the PDFsharp library which also includes the MigraDoc libraries too.  I have come up with an example of using these to create a table from the data in a DataGridView.  It is not quite as clean cut using these as it is iTextSharp but,  after an hour or two of experimenting and going through some of their Code Samples you should be able to catch on.

     Here Is A Link where you can download all the assemblies in one zip file.  Download the one that says 'PDFsharp-MigraDocFoundation-Assemblies-1_32'.  You should also download the help documents located further down,  the one that says 'PDFsharp-Help-Standalone-1_31.zip'.

     You can find the PDFsharp Code Samples Here and the MigraDoc Code Samples Here.  They are in C# but,  you can easily convert them over manually or use an online code converter such as the Telerik Code Converter to convert them to VB.Net.  It takes a little fumbling around as they don't show you the namespaces for everything they use.  This is where a little guess work and the help documents come in handy.

     Anyways,  you can try this in a new form project with 1 DataGridView and 1 Button added to the form.  You will need to add 3 references to the project.  Add a reference to (PdfSharp.dll),  (MigraDoc.Rendering.dll),  and (MigraDoc.DocumentObjectModel.dll).  They are all in the (GDI+) folder.  You will also need to set the path to save the pdf file to.

    Imports PdfSharp
    Imports MigraDoc.DocumentObjectModel
    
    Public Class Form1
        Private doc As Document
        Private tbl As Tables.Table
        Private adrFrame As Shapes.TextFrame
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            DataGridView1.AllowUserToAddRows = False
    
            Dim dt As New DataTable
            With dt
                .Columns.Add("Names", GetType(String))
                .Columns.Add("Ids", GetType(String))
                .Columns.Add("Base", GetType(Integer))
                .Columns.Add("OrderDate", GetType(String))
                .Columns.Add("Price", GetType(Double))
            End With
    
            Dim somenames() As String = {"Joe", "Mary", "John", "Greg", "Tom"}
            Dim someinfo() As String = {"xx1", "cx4", "af2", "hg7", "ss4"}
            Dim somenumbers() As Integer = {2234, 7723, 9947, 6477, 9103}
            Dim somedates() As String = {Now.ToShortDateString, Now.AddDays(-100).ToShortDateString, Now.AddDays(32).ToShortDateString, Now.AddDays(-482).ToShortDateString, Now.AddDays(432).ToShortDateString}
            Dim someprices() As Double = {66.21, 92.32, 7.25, 99.09, 200.45}
            For i As Integer = 0 To somenames.Length - 1
                dt.Rows.Add(New Object() {somenames(i), someinfo(i), somenumbers(i), somedates(i), someprices(i)})
            Next
    
            DataGridView1.DataSource = dt
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            'create a new document
            Dim doc As New Document 'the default page size is A4
    
            'if wanted, set the properties of the document. These are seen by right clicking on the pdf file and selecting 'Properties' then selecting the 'Pdf' tab.
            doc.Info.Title = "My Table Example"
            doc.Info.Subject = "Demonstrates how to create a table."
            doc.Info.Author = "IronRazerz"
    
            'create a style for the table
            Dim style As Style = doc.Styles("Normal")
            style = doc.Styles.AddStyle("Table", "Normal")
            style.Font.Name = "Tahoma"
            style.Font.Size = 9
    
            'add a new section to the document
            Dim section As Section = doc.AddSection()
    
            'add a new table to the section
            Dim tbl As Tables.Table = section.AddTable()
    
            'set the style for the table borders
            tbl.Style = "Table"
            tbl.Borders.Color = Colors.Blue 'sets the color of the border lines
            tbl.Borders.Width = 0.25
            tbl.Borders.Left.Width = 0.5
            tbl.Borders.Right.Width = 0.5
            tbl.Rows.LeftIndent = 0
    
            'add the columns to the table
            Dim column As Tables.Column
            For i As Integer = 0 To DataGridView1.ColumnCount - 1
                column = tbl.AddColumn("2cm") 'the unit sizes for the cells can be set in Inches, Centimeters, Millimeter, Picas or Points (search for 'unit' in the help documentation)
            Next
    
            'add a row to the table for the headers
            Dim row As Tables.Row = tbl.AddRow()
            row.HeadingFormat = True
            row.Format.Alignment = ParagraphAlignment.Center 'sets the alignment of the text in the header cels
            row.Shading.Color = Colors.LightSteelBlue 'sets the shading color of the header row
    
            'add the text to each column's header
            For i As Integer = 0 To DataGridView1.ColumnCount - 1
                row.Cells(i).AddParagraph(DataGridView1.Columns(i).HeaderText)
                row.Cells(i).Format.Font.Bold = True 'make the font in the header cells Bold
            Next
    
            'add the cells for each row of data
            For Each r As DataGridViewRow In DataGridView1.Rows
                If Not r.IsNewRow Then
                    row = tbl.AddRow()
                    For i As Integer = 0 To DataGridView1.ColumnCount - 1
                        Dim cellText As String = ""
                        If Not r.Cells(i).Value Is Nothing Then
                            cellText = r.Cells(i).Value.ToString
                        End If
                        row.Cells(i).AddParagraph(cellText)
                        row.Format.Alignment = ParagraphAlignment.Left 'sets the alignment of the text for the data cells
                        row.Shading.Color = Colors.WhiteSmoke 'sets the shading color of the data cells
                    Next
                End If
            Next
    
            tbl.Rows.Alignment = Tables.RowAlignment.Center 'center the table in document
    
            'convert the MigraDoc Document to a Pdf Document and save the PdfDocument to a file
            Dim rndr As New MigraDoc.Rendering.PdfDocumentRenderer(False, Pdf.PdfFontEmbedding.Always) 'if using unicode, set first parameter to True to use unicode encoding
            rndr.Document = doc
            rndr.RenderDocument()
            rndr.PdfDocument.Save("C:\TestFolder\Example Table.pdf")
        End Sub
    End Class
     

     

     Here is what the table looks like in the Pdf file...


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Saturday, December 16, 2017 12:14 AM
    Saturday, December 16, 2017 12:11 AM