'
' Textflow starter:
' Create multi-column text output which may span multiple pages.
' A Web link is inserted with Textflow options and a matchbox
'
' Required data: font file
'
Imports System
Imports System.Text
Imports PDFlib_dotnet

Module starter_textflow

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

        Dim p As PDFlib_dotnet.PDFlib = Nothing
        Dim i As Integer, tf As Integer = -1, action As Integer
        Dim result As String
        Const llx1 As Double = 50, lly1 As Double = 50
        Const urx1 As Double = 250, ury1 As Double = 800
        Const llx2 As Double = 300, lly2 As Double = 50
        Const urx2 As Double = 500, ury2 As Double = 800

        ' Repeat the dummy text to produce more contents
        Const count As Integer = 50

        Const optlist1 As String = _
            "fontname=NotoSerif-Regular fontsize=10.5 " & _
            "leading=125% fillcolor=black alignment=justify"

        Const optlist2 As String = _
            "fontname=NotoSerif-Regular fontsize=16 " & _
            "fillcolor=red charref nounderline"

        ' Dummy text for filling the columns. Soft hyphens are marked with
        ' the character reference "&shy;" (character references are
        ' enabled by the charref option).

        Const 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_textflow.pdf", "") = -1 Then
                Console.WriteLine("Error: " & p.get_errmsg())
                return
            End If

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

            ' Create dummy text and feed it to a Textflow object
            ' with alternating options. 

            For i = 1 To count
                Dim num As String = i & " "

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

                ' In the first section we include a Web link with Textflow options:
                ' - emit URL text and define a matchbox named "link_matchbox" around it;
                '   specify suitable Textflow options, e.g. blue text.
                ' - end matchbox
                ' The corresponding annotation will be created later with
                ' p.create_annotation() using the matchbox name.

                if i = 1 Then
                    tf = p.add_textflow(tf, "www.pdflib.com",
                            "save fontsize=10.5 fillcolor=blue strokecolor=blue underline " & _
                            "matchbox={name=link_matchbox boxheight={ascender descender}}")
                    if tf = -1 Then
                        Console.WriteLine("Error: " & p.get_errmsg())
                        return
                    End If

                    tf = p.add_textflow(tf,  " ", "restore matchbox=end nounderline")
                    if tf = -1 Then
                        Console.WriteLine("Error: " & p.get_errmsg())
                        return
                    End If
                End If

                tf = p.add_textflow(tf, text, optlist1)
                If tf = -1 Then
                    Console.WriteLine("Error: " & p.get_errmsg())
                    return
                End If
            Next i

            ' Loop until all of the text is placed; create new pages
            ' as long as more text needs to be placed. Two columns will
            ' be created on all pages.

            Do
                ' Add "showborder" to visualize the fitbox borders
                Dim optlist As String = _
                    "verticalalign=justify linespreadlimit=120% "

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

                ' Fill the first column
                result = p.fit_textflow(tf, llx1, lly1, urx1, ury1, optlist)

                ' Fill the second column if we have more text
                If result <> "_stop" Then
                    result = p.fit_textflow(tf, llx2, lly2, urx2, ury2, optlist)
                End If
                ' Create the Web link based on the named matchbox which
                ' was created in the Textflow.

                ' Create a "URI" action for the link annotation
                optlist = "url={https://www.pdflib.com}"
                action = p.create_action("URI", optlist)
                ' Coordinates are ignored since we use a matchbox
                p.create_annotation(0, 0, 0, 0, "Link", _
                    "usematchbox={link_matchbox} action={activate " & action & "} linewidth=0")

                p.end_page_ext("")

                ' "_boxfull" means we must continue because there is more text
                ' "_nextpage" is interpreted as "start new column"
            Loop While result = "_boxfull" Or result = "_nextpage"

            ' Check for errors
            If result <> "_stop" Then
                ' "_boxempty" happens if the box is very small and doesn't
                ' hold any text at all.

                If result <> "_boxempty" Then
                    Console.WriteLine("Error: Textflow box too small")
                    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 '" & result & _
                      "' found in Textflow")
                    return
                End If
            End If

            p.delete_textflow(tf)

            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
