Menu

.NET SharpPDF Additional Class Help + Guide

Help
Shab
2011-08-03
2013-04-15
  • Shab

    Shab - 2011-08-03

    Hi Guys

    Ive just started to use SharpPDF to generate PDF Documents on the fly and due to the fact that its not a very well documented addon for this, I created a small class to help generate very basic PDF Documents.

    I thought i would post it here for criticisms and to see if it may help anyone else who is using SharpPDF. There is some issues as of current with it, But it should help people on their way to generate documents using SharpPDF as i didnt find the tutorials much help and had to do a lot of google searching.

    KNOWN ISSUES WITH THE CLASS AT THE MOMENT :
    1: If the table is too large it does NOT automatically continue the table onto a new page.
    2: The Alignment method does not align the text strings.

    Imports sharpPDF.Collections
    Imports sharpPDF.Elements
    Imports sharpPDF.Exceptions
    Imports sharpPDF.Enumerators
    Imports sharpPDF.PDFControls
    Imports sharpPDF
    Imports sharpPDF.Tables
    Public Class _SharpPDF
        Dim newPDF As pdfDocument
        Dim pdfSaveName As String
        'Table Store.
        Dim tables As New List(Of pdfTable)
        'Store Pages
        Dim pages As New List(Of pdfPage)
        'The currently working pdf objects.
        Dim tempTable As pdfTable
        Dim tempColumn As pdfTableColumn
        Dim tempPage As pdfPage
        Dim tempRow As pdfTableRow
        Dim xAxis As Integer = 0
        Dim yAxis As Integer = 0
      
        Private Function Alignment(ByVal align As Char, ByVal W As Integer, ByVal H As Integer) As Integer
            Dim pageWidth As Integer = tempPage.width
            Dim x As Integer = xAxis
            Select Case (align)
                Case "L"
                    x = xAxis
                    yAxis -= H
                Case "C"
                    Dim half As Integer = pageWidth - xAxis - W
                    x = half / 2
                    yAxis -= H
                Case "R"
                    Dim right As Integer = pageWidth - xAxis - W
                    x = right
                    yAxis -= H
            End Select
            Return x
        End Function
        Public Sub createPDF(ByVal pdfTitle As String, ByVal pdfAuthor As String)
            newPDF = New pdfDocument(pdfTitle, pdfAuthor)
        End Sub
        Public Sub createPage(ByVal leftMargin As Integer, ByVal topMargin As Integer)
            tempPage = newPDF.addPage()
            xAxis = leftMargin
            yAxis = tempPage.height - topMargin
        End Sub
        Public Sub setPDFSaveName(ByVal SaveName As String)
            pdfSaveName = SaveName
        End Sub
        Public Sub createTable(ByVal cellPadding As Integer)
            tempTable = New pdfTable(newPDF, cellPadding)
            tempTable.coordY = yAxis
        
        End Sub
        Public Sub headerStyle()
            tempTable.tableHeader.rowStyle = New pdfTableStyle(newPDF.getFontReference(predefinedFont.csCourier), 24, pdfColor.White, pdfColor.DarkGreen)
        End Sub
        Public Sub createHeaders(ByVal columnWidth As Integer, ByVal columnNames As String(), ByVal colAmount As Integer)
            For j As Integer = 0 To colAmount
                tempTable.tableHeader.addColumn(columnWidth, predefinedAlignment.csCenter)
            Next
            For i As Integer = 0 To columnNames.Count() - 1
                tempTable.tableHeader(i).addText(columnNames(i))
            Next
        End Sub
        Public Sub createRow(ByVal rowValues As String())
            tempRow = tempTable.createRow()
            'The values for the row.
            For i As Integer = 0 To tempTable.tableHeader.columnsCount() - 1
                tempRow(i).addText(rowValues(i))
            Next
            tempRow.rowStyle = New pdfTableStyle(newPDF.getFontReference(predefinedFont.csHelvetica), 12, pdfColor.Black, pdfColor.White)
            tempTable.addRow(tempRow)
        End Sub
        Public Sub finaliseTable(ByVal align As Char)
            yAxis -= tempTable.tableHeader.rowHeight
            yAxis -= tempTable.rowsCount * tempRow.rowHeight
            tempTable.coordX = Alignment(align, tempTable.tableHeader.rowWidth, tempTable.rowsCount * tempRow.rowHeight)
            tempPage.addTable(tempTable)
        End Sub
        Public Sub placeImage(ByVal imgString As String, ByVal align As Char)
            newPDF.addImageReference(imgString, "MyImg")
            tempPage.addImage(newPDF.getImageReference("MyImg"), Alignment(align, newPDF.getImageReference("MyImg").width, newPDF.getImageReference("MyImg").height), yAxis)
        End Sub
        Public Sub writeString(ByVal text As String, ByVal fontSize As Integer, ByVal align As Char)
            yAxis -= fontSize
            yAxis -= 20
            tempPage.addText(text, xAxis, yAxis, newPDF.getFontReference(predefinedFont.csTimes), fontSize, pdfColor.Black)
        End Sub
        Public Function generatePDF() As Boolean
            For Each page As pdfPage In pages
                page = newPDF.addPage()
            Next
            Try
                If (IO.File.Exists(pdfSaveName) = True) Then
                    IO.File.Delete(pdfSaveName)
                    newPDF.createPDF(pdfSaveName)
                Else
                    newPDF.createPDF(pdfSaveName)
                End If
            Catch ex As Exception
                MsgBox("Error::: " & vbNewLine & "Details : No PDF Save Location Given.", MsgBoxStyle.Exclamation, "PDF Creation Error!")
                Return False
            End Try
            Return True
        End Function
        Public Sub openPDF()
            Process.Start(pdfSaveName)
        End Sub
        Public Sub savePage()
            pages.Add(tempPage)
        End Sub
    End Class
    

    The way to use the above class is demonstrated below.

    Make a variable as shown below, but put this above your Form_Load event.

    'This is creating our PDF Table Headers.
    Dim table1Headers As String() = {"Value 1","Value 2"}
    Dim table2Headers As String() = {"Value 1", "Value 2", "Total"}

    Dim table1RowValues as List (Of String())
    Dim table2RowValues as List (Of String())

    Next look below on how to use these to generate a PDF.

         'Create some row data.
    table1RowValues.add({1,9})
    table1RowValues.add({25,25})
    table2RowValues.add({5,5,10})
    table2RowValues.add({10,10,20)
           'Instantiate a PDF Object 
            Dim NewPdf As New _SharpPDF
            'Strip any slashes out of a possible dated filename so 08/09/2011 would become 08-09-2011
            Dim replaceSlash As String = Replace(reports.returnReportName(), "/", "-")
            'Create a save point for the PDF 
            NewPdf.setPDFSaveName(settings.returnSaveDir & "\" & replaceSlash & ".pdf")
            'Create a new PDF document with my Author Name and a PDF Name 
            NewPdf.createPDF("MyPDFName", "MyAuthorName")
            'Create a new page with a left margin of 10 and top margin of 20 
            NewPdf.createPage(10, 20)
            'Place an image in to the document and align the right side of the image to the right side of the PDF
            NewPdf.placeImage("MyImageLocation", "R")
            'Create a message for a description of the PDF COntents.
            NewPdf.writeString("This is a detailed report of " & reports.returnReportName, 12, "L")
            'Write a new string to "simulate a new paragraph"
            NewPdf.writeString("", 10, "L")
            'Create a new table with padding of 5
            NewPdf.createTable(5)
            'Create a new table with width of 100 points 
            NewPdf.createHeaders(100, table1Headers, tableHeaders1.count)
            'Apply the default header style 
            NewPdf.headerStyle()
            'Loop through all the tablevalues to populate the chart 
            For Each row As String() In table1RowValues
                NewPdf.createRow(row)
            Next
            'Apply this table to the pdf.
            NewPdf.finaliseTable("C")
            NewPdf.writeString("Breakdown Costing", 14, "R")
            'Write a new string to "simulate a new paragraph"
            NewPdf.writeString("", 10, "L")
            NewPdf.createTable(10)
            NewPdf.createHeaders(150, breakDownReportHeaders, breakDownReportHeaders.Count - 1)
            NewPdf.headerStyle()
            For Each row As String() In table2RowValues
                NewPdf.createRow(row)
            Next
           'Finished with the table and i wish to put the table in the center of the document.
            NewPdf.finaliseTable("C")
            'Create a PDF File in a Location. 
            NewPdf.generatePDF()
            'Open the new PDF with an associated application. 
            NewPdf.OpenPDF()
    

    Now im not saying this is the perfect substitute to an alternate way to use SharpPDF , Its just a way that i found easier for me as it "tracks" the YAxis of where your last element was placed on the page and adjusts it accordingly so when you add something to the PDF Document it will automatically be under the last thing you put onto the page.

    This class still needs a lot of work to be a fully functional code, But i am still working on it :)

    If anyone has questions about it, Please respond

    Regards Shab

     
  • Shab

    Shab - 2011-08-03

    UPDATE :

    Change

     NewPdf.createHeaders(150, breakDownReportHeaders, breakDownReportHeaders.Count - 1)
    

    To

     NewPdf.createHeaders(150, table2Headers, table2Headers.count())
    
     

Log in to post a comment.

MongoDB Logo MongoDB