'
' Table starter:
' Create table which may span multiple pages.
' The table cells are filled with various content types including
' Textflow, Textline, image, SVG, stamp, Web link (annotation) and
' form field.
'
' Required data: image and SVG files, font
'
Imports System
Imports System.Text
Imports PDFlib_dotnet

Module starter_table

    Sub Main()
        ' This is where the data files are. Adjust as necessary.
        Const searchpath As String = "../../../data"

        Const imagefile As String = "nesrin.jpg"
        Const graphicsfile As String = "PDFlib-logo.svg"

        Dim row, col, font, fieldfont, graphics, image, action As Integer
        Dim tf As Integer = -1, tbl As Integer = -1
        Const rowmax As Integer = 50, colmax As Integer = 4

        Dim p As PDFlib_dotnet.PDFlib = Nothing
        Const llx As Double = 50, lly As Double = 50
        Const urx As Double = 550, ury As Double = 800
        Const headertext As String = "Table header (row 1)"
        Dim result As String
        Dim optlist As String

        ' Dummy text for filling a cell with multi-line Textflow
        Const tf_text As String = _
        "Lorem ipsum dolor sit amet, consectetur adi&shy;pi&shy;sicing elit, sed do eius&shy;mod tempor incidi&shy;dunt ut labore et dolore magna ali&shy;qua. Ut enim ad minim ve&shy;niam, quis nostrud exer&shy;citation ull&shy;amco la&shy;bo&shy;ris nisi ut ali&shy;quip ex ea commodo con&shy;sequat. Duis aute irure dolor in repre&shy;henderit in voluptate velit esse cillum dolore eu fugiat nulla pari&shy;atur. Excep&shy;teur sint occae&shy;cat cupi&shy;datat non proident, sunt in culpa qui officia dese&shy;runt mollit anim id est laborum. "

        Try
            p = New PDFlib()

            ' This means we must check return values of load_font() etc.
            p.set_option("errorpolicy=return")

            ' Set the search path for fonts and PDF files 
            p.set_option("SearchPath={{" & searchpath & "}}")

            If p.begin_document("starter_table.pdf", "") = -1 Then
                Console.WriteLine("Error: " & p.get_errmsg())
                return
            End If

            p.set_info("Creator", "PDFlib starter sample")
            p.set_info("Title", "starter_table")

            ' -------------------- Add table cells --------------------

            ' ---------- Row 1: table header (spans all columns)
            row = 1
            col = 1
            font = p.load_font("NotoSerif-Regular", "unicode", "")

            If font = -1 Then
                Console.WriteLine("Error: " & p.get_errmsg())
                return
            End If

            optlist = "fittextline={position=center font=" & font & _
             " fontsize=14} colspan=" & colmax

            tbl = p.add_table_cell(tbl, col, row, headertext, optlist)

            If tbl = -1 Then
                Console.WriteLine("Error adding cell: " & p.get_errmsg())
                return
            End If

            ' ---------- Row 2: various kinds of content
            row = row + 1

            ' ----- Simple text cell
            col = 1

            optlist = _
             "fittextline={font=" & font & " fontsize=12 orientate=west}"

            tbl = p.add_table_cell(tbl, col, row, "vertical line", optlist)

            If tbl = -1 Then
                Console.WriteLine("Error adding new cell: " & p.get_errmsg())
                return
            End If

            ' ----- Colorized background
            col = col + 1

            optlist = _
                "fittextline={font=" & font & " fontsize=12 fillcolor=white} " & _
                "matchbox={fillcolor=orange}"

            tbl = p.add_table_cell(tbl, col, row, "colorized cell", optlist)

            If tbl = -1 Then
                Console.WriteLine("Error adding new cell: " & p.get_errmsg())
                return
            End If


            ' ----- Multi-line text with Textflow
            col = col + 1

            font = p.load_font("NotoSerif-Regular", "unicode", "")

            If font = -1 Then
                Console.WriteLine("Error: " & p.get_errmsg())
                return
            End If

            optlist = _
             "charref fontname=NotoSerif-Regular fontsize=8 alignment=justify"

            tf = p.add_textflow(tf, tf_text, optlist)
            If tf = -1 Then
                Console.WriteLine("Error: " & p.get_errmsg())
                return
            End If

            optlist = "margin=2 textflow=" & tf

            tbl = p.add_table_cell(tbl, col, row, "", optlist)

            If tbl = -1 Then
                Console.WriteLine("Error adding cell: " & p.get_errmsg())
                return
            End If

            ' ----- Rotated image
            col = col + 1

            image = p.load_image("auto", imagefile, "")
            If image = -1 Then
                Console.WriteLine("Couldn't load image: " & p.get_errmsg())
                return
            End If

            optlist = "image=" & image & " fitimage={orientate=west} " & _
                "fittextline={fontname=NotoSerif-Regular fontsize=12 fillcolor=white}"

            tbl = p.add_table_cell(tbl, col, row, "rotated image", optlist)

            If tbl = -1 Then
                Console.WriteLine("Error adding cell: " & p.get_errmsg())
                return
            End If

            ' ---------- Row 3: various kinds of content 
            row = row + 1

            ' ----- Diagonal stamp
            col = 1

            optlist = "rowheight=50 fittextline={font=" & font & " fontsize=10 stamp=ll2ur}"

            tbl = p.add_table_cell(tbl, col, row, "diagonal stamp", optlist)

            If tbl = -1 Then
                Console.WriteLine("Error adding cell: " & p.get_errmsg())
                return
            End If

            ' ----- SVG graphics 
            col = col + 1

            ' Load the graphics 
            graphics = p.load_graphics("auto", graphicsfile, "")
            if graphics = -1 Then
                Console.WriteLine("Error: " & p.get_errmsg())
                return
            End If
            
            optlist = "margin=5 graphics=" & graphics 

            tbl = p.add_table_cell(tbl, col, row, "", optlist)

            If tbl = -1 Then
                Console.WriteLine("Error adding cell: " & p.get_errmsg())
                return
            End If

            ' ----- Annotation: Web link 
            col = col + 1
            
            action = p.create_action("URI", "url={https://www.pdflib.com}")
            
            optlist =  "margin=5 fittextline={fontname=NotoSerif-Regular fontsize=14 fillcolor=blue} " & _
                    "annotationtype=Link fitannotation={action={activate " & action & "} linewidth=0}"
            tbl = p.add_table_cell(tbl, col, row, "Web link", optlist)

            If tbl = -1 Then
                Console.WriteLine("Error adding cell: " & p.get_errmsg())
                return
            End If

            ' ----- Form field 
            col = col + 1

            fieldfont = p.load_font("NotoSerif-Regular", "winansi", "simplefont nosubsetting")

            If fieldfont = -1 Then
                Console.WriteLine("Error: " & p.get_errmsg())
                return
            End If
            
            optlist = "margin=5 fieldtype=textfield fieldname={name} " & _
                      "fitfield={multiline linewidth=0 font=" & fieldfont & " fontsize=12 " & _
                      "alignment=center currentvalue={text field} scrollable=false}"

            tbl = p.add_table_cell(tbl, col, row, "", optlist)

            If tbl = -1 Then
                Console.WriteLine("Error adding cell: " & p.get_errmsg())
                return
            End If

            ' ---------- Fill row 3 and above with their numbers
            row = row + 1
            While row <= rowmax
                For col = 1 To colmax
                    Dim num As String = "Col " & col & "/Row " & row

                    optlist = _
                    "colwidth=25% fittextline={font=" & font & " fontsize=10}"
                    tbl = p.add_table_cell(tbl, col, row, num, optlist)

                    If tbl = -1 Then
                        Console.WriteLine("Error adding cell: " & p.get_errmsg())
                        return
                    End If
                Next col
                row = row + 1
            End While

            ' ---------- Place the table on one or more pages ----------

            '
            ' Loop until all of the table is placed; create new pages
            ' as long as more table instances need to be placed.

            Do
                p.begin_page_ext(0, 0, "width=a4.width height=a4.height")

                ' Shade every other row; draw lines for all table cells.
                ' Add "showcells showborder" to visualize cell borders 
                optlist = _
                "header=1 rowheightdefault=auto " & _
                "fill={{area=rowodd fillcolor={gray 0.9}}} " & _
                "stroke={{line=other}} "

                ' Place the table instance
                result = p.fit_table(tbl, llx, lly, urx, ury, optlist)

                If result = "_error" Then
                    Console.WriteLine("Couldn't place table: " & p.get_errmsg())
                    return
                End If

                p.end_page_ext("")

            Loop While result = "_boxfull"

            ' Check the result; "_stop" means all is ok.
            If result <> "_stop" Then
                If result = "_error" Then
                    Console.WriteLine("Error when placing table: " & p.get_errmsg())
                    return
                Else
                    ' Any other return value is a user exit caused by
                    ' the "return" option; this requires dedicated code to
                    ' deal with.

                    Console.WriteLine("User return found in Table: " & p.get_errmsg())
                    return
                End If
            End If

            ' This will also delete Textflow handles used in the table
            p.delete_table(tbl, "")

            p.end_document("")

        Catch e As PDFlibException
            Console.Error.WriteLine("PDFlib exception occurred:")
            Console.Error.WriteLine("[{0}] {1}: {2}", e.get_errnum(), e.get_apiname(), e.get_errmsg)
        Catch e As System.Exception
            Console.Error.WriteLine(e.ToString())
        Finally
            If Not p Is Nothing Then
                p.Dispose()
                p = Nothing
            End If
        End Try

    End Sub

End Module
