Imports System.Drawing.Printing
Imports System.Drawing.Text
Imports System.IO
Imports System.Reflection
Imports System.Text
Imports Microsoft.Office.Interop.Word

Public Class MainForm1
    ' Constants for Activation codes
    Const StrLicenseTo As String = "Amyuni PDF Converter Evaluation"
    Const StrActivationCode As String = "07EFCDAB0100010025AFF1801CB9441306C5739F7D452154D8833B9CECBA2ADE79E3762A69FFC354528A5F4A5811BE3204A0A439F5BA"
    Const AmyuniPrinterName As String = "Amyuni PDF Converter"

    Dim _pdf As CDIntfEx.CDIntfEx
    Dim _pdFdoc As CDIntfEx.DocumentClass


    Const NoPropmt As Int32 = &H1&
    Const UseFileName As Int32 = &H2&
    Const SendByEmail As Int32 = &H800&


    '///////////////////////////////////////////////////////////////////////
    'This code snippet illustrates how to print to the Amyuni PDF Converter
    '///////////////////////////////////////////////////////////////////////
    Private Sub btnPrintText_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnPrintText.Click

        '//get startup path for temp working files
        Dim requiredPath As String = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))))

        'Declare a new cdintfex object
        _pdf = New CDIntfEx.CDIntfEx

        'Get a reference to the installed printer.
        'This will fail if the printer name passed to the DriverInit method is not found in the printer’s folder
        _pdf.DriverInit(AmyuniPrinterName)

        'Resulting PDF document stored here
        _pdf.DefaultFileName = requiredPath & $"\\Resulting_Docs\\PrintText_resulting.pdf"

        'set printer options
        _pdf.FileNameOptions = NoPropmt + UseFileName

        Dim currentPrinter As String = PrintDocument1.PrinterSettings.PrinterName
        PrintDocument1.PrinterSettings.PrinterName = AmyuniPrinterName

        'The EnablePrinter()method needs to be called right before each print job. 
        'Calling the EnablePrinter()method will start a 20 second time-out value
        _pdf.EnablePrinter(StrLicenseTo, StrActivationCode)

        'Print(something)
        PrintDocument1.Print()

        PrintDocument1.PrinterSettings.PrinterName = currentPrinter

        'Clean(-up)
        _pdf.FileNameOptions = 0

        ListBox1.Items.Add("PrintText_resulting.pdf .... created")

    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
        '//get startup path for temp working files
        Dim requiredPath As String = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))))


        Try
            ' Turn on antialias for text
            e.Graphics.TextRenderingHint =
                             TextRenderingHint.AntiAlias
            ' Print a string at the origin
            Dim pFont As Drawing.Font
            pFont = New Drawing.Font("Comic Sans MS", 20)
            e.Graphics.DrawString("Amyuni PDF Converter", pFont, Brushes.Black, 0, 0)

            ' Read margins into local variables
            Dim lmargin, rmargin, tmargin, bMargin As Integer
            With PrintDocument1.DefaultPageSettings.Margins
                lmargin = .Left
                rmargin = .Right
                tmargin = .Top
                bMargin = .Bottom
            End With

            ' Calculate the dimensions of the printable area
            Dim printWidth, printHeight As Integer
            With PrintDocument1.DefaultPageSettings.PaperSize
                printWidth = .Width - lmargin - rmargin
                printHeight = .Height - tmargin - bMargin
            End With

            ' Now print the rectangle
            Dim r As Drawing.Rectangle
            r = New Drawing.Rectangle(lmargin, tmargin, printWidth, printHeight)
            e.Graphics.DrawRectangle(Pens.Black, r)

            Dim img As Image = Image.FromFile(requiredPath & "\\Source_docs\\Penguins.jpg")
            Dim rect As Drawing.Rectangle = New Drawing.Rectangle(100, 100, 50, 50)
            e.Graphics.DrawImage(img, rect)


        Catch exc As Exception
            'Catch and display errors
            MsgBox("Error Printing")
        End Try
    End Sub

    '///////////////////////////////////////////////////////////////////////
    'The Appen or AppendEx methods append or concatenate a second PDF file to a first one.
    '///////////////////////////////////////////////////////////////////////
    Private Sub btnAppend_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAppend.Click
        '//get startup path for temp working files
        Dim requiredPath As String = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))))

        Dim pdfDoc As New CDIntfEx.Document

        Dim sourcePdfFileOne As String = requiredPath & "\\Source_docs\\one.pdf"
        Dim sourcePdfFileTwo As String = requiredPath & "\\Source_docs\\two.pdf"
        Dim resultingPdfFile As String = requiredPath & "\\Resulting_Docs\\Append_resulting.pdf"

        'Open the main file ONLY once
        'This will improve performance because you will not
        'need to open the file at each iteration
        pdfDoc.Open(sourcePdfFileOne)
        pdfDoc.Append(sourcePdfFileTwo)

        pdfDoc.Save(resultingPdfFile)

        ListBox1.Items.Add("Append_resulting.pdf ...... created")

    End Sub




    '///////////////////////////////////////////////////////////////////////
    'The Appen or AppendEx methods append or concatenate a second PDF file to a first one.
    'This code snippet illustrates how to append a large number of documents
    '///////////////////////////////////////////////////////////////////////
    Private Sub btnAppendMultipleDocs_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAppendMultipleDocs.Click
        '//get startup path for temp working files
        Dim requiredPath As String = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))))

        Dim pdfDoc As New CDIntfEx.Document
        Dim result As String = ""
        Dim counter As Integer = 1

        Dim sourcePdfFile As String = requiredPath & "\\Source_docs\\one.pdf"
        Dim resultingPdfFile As String = requiredPath & "\\Resulting_Docs\\AppendMultipleDocs_resulting.pdf"

        pdfDoc.Open(sourcePdfFile)

        'Example:
        'Loop through a directory that has 1000 PDF documents
        Do
            result = Path.GetFileNameWithoutExtension(sourcePdfFile)

            'This is much quicker because you don't need to open
            'the file
            pdfDoc.Append(requiredPath & "\\Source_docs\\" & result & counter & ".pdf")
            counter = counter + 1

        Loop Until counter = 3

        'Save when you are done
        pdfDoc.Save(resultingPdfFile)

        ListBox1.Items.Add("AppendMultipleDocs_resulting.pdf ...... created")
    End Sub

    '///////////////////////////////////////////////////////////////////////
    'The Merge and MergeEx methods merge two PDF documents by combining the contents of every page 
    'of the first documentwith a page from the second document.
    '///////////////////////////////////////////////////////////////////////
    Private Sub btnMerge_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnMerge.Click

        '//get startup path for temp working files
        Dim requiredPath As String = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))))

        ' create two objects of type Document
        Dim pdfDoc1 As New CDIntfEx.Document
        Dim pdfDoc2 As New CDIntfEx.Document

        ' open the document containing the watermark
        pdfDoc1.Open(requiredPath & "\\Source_docs\\one.pdf")

        ' open the main document
        pdfDoc2.Open(requiredPath & "\\Source_docs\\logo.pdf")

        ' merge the watermark document to the main one
        'Repeat first pages = 1 
        'The first pages of the second document are repeated in the 
        'first(document)

        'Second document above first = 2 
        'The contents of the second document are printed above the contents of
        'the first document
        pdfDoc1.MergeEx(pdfDoc2, 1)

        ' save document to some other file
        pdfDoc1.Save(requiredPath & "\\Resulting_Docs\\Merge_resulting.pdf")

        ListBox1.Items.Add("Merge_resulting ...... created")

    End Sub



    '///////////////////////////////////////////////////////////////////////
    'The Encrypt and Encrypt128 methods can be used to password protect a PDF document and restrict users to viewing, 
    'modifying or even printing the document. This function requires a call to Document.SetLicenseKey before it can be used. 
    'The Encrypt method uses 40 bits encryption, whereas the Encrypt128 method uses 128 bits encryption compatible 
    'with Adobe® Acrobat® 5 and higher.
    '///////////////////////////////////////////////////////////////////////
    Private Sub btnEncrypt_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnEncrypt.Click
        '//get startup path for temp working files
        Dim requiredPath As String = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))))

        Dim pdFdoc As New CDIntfEx.Document

        pdFdoc.Open(requiredPath & "\\Source_docs\\one.pdf")
        pdFdoc.SetLicenseKey(StrLicenseTo, StrActivationCode)

        ' '/////////////////////////////////////////////////////////////
        ''Permission                         Permission value
        ''Enable Printing                        - 64 + 4
        ''Enable document modification           - 64 + 8
        ''Enable copying text and graphics       - 64 + 16
        ''Enable adding and changing notes       - 64 + 32
        ''To combine multiple options, use -64 plus the values 4, 8, 16 or 32. E.g. to enable
        ''&HFFFFF0C0

        pdFdoc.Encrypt("aaaaaa", "", -64)

        pdFdoc.Save(requiredPath & "\\Resulting_Docs\\Encrypt_resulting.pdf")

        ListBox1.Items.Add("Encrypt_resulting ...... created")
    End Sub




    '///////////////////////////////////////////////////////////////////////
    'The SetHyperlinkURL method creates hyperlinks to external locations such as http://www.amyuni.com and
    'ftp://ftp.amyuni.com. When the document is opened and the hyperlink is clicked, 
    'the default web browser will be launched.
    '///////////////////////////////////////////////////////////////////////
    Private Sub btnHyperLinks_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnHyperLinks.Click
        '//get startup path for temp working files
        Dim requiredPath As String = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))))

        Dim pdFdoc As New CDIntfEx.Document

        pdFdoc.Open(requiredPath & "\\Source_docs\\hyperlink.pdf")
        pdFdoc.SetLicenseKey(StrLicenseTo, StrActivationCode)

        'SetHyperLinkURL(ByVal PageNumber As Integer, 
        'ByVal xStart As Integer, 
        'ByVal yStart As Integer, 
        'ByVal xEnd As Integer, 
        'ByVal yEnd As Integer, 
        'ByVal URL As String) As Boolean

        'The SetHyperlinkURL method creates hyperlinks to external locations such as http://www.amyuni.com and
        'ftp://ftp.amyuni.com. When the document is opened and the hyperlink is clicked, the default 
        'web browser will be launched.

        'In this example the hyperlink will point another PDF document.
        pdFdoc.SetHyperLinkURL(1, 0, 0, 1000, 1000, "/S /Launch /F (c:/temp/pdf1.pdf)")

        'In this example the hyperlink will point a URL.
        pdFdoc.SetHyperLinkURL(2, 0, 0, 1000, 1000, "www.amyuni.com")

        pdFdoc.Save(requiredPath & "\\Resulting_Docs\\HyperLinks_resulting.pdf")

        ListBox1.Items.Add("HyperLinks_resulting.pdf  ...... created")

    End Sub



    '///////////////////////////////////////////////////////////////////////
    'The searchText method is used to search for a specific text.It is less accurate in returning the text 
    'position but much faster than SearchTextEx. It only works with WinAnsi encoded streams, 
    'but not with other encodings.
    '///////////////////////////////////////////////////////////////////////
    Private Sub btnSearchText_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSearchText.Click

        '//get startup path for temp working files
        Dim requiredPath As String = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))))

        Dim pdfDoc As New CDIntfEx.Document
        pdfDoc.SetLicenseKey(StrLicenseTo, StrActivationCode)
        Try
            pdfDoc.Open(requiredPath & "\\Source_docs\\one.pdf")

            Dim xPos As Double
            Dim yPos As Double
            Dim page As Integer
            Dim start As Short = 0
            Dim strFind As String

            strFind = "One"

            With pdfDoc
                If (.SearchTextEx(start, strFind, page, xPos, yPos)) Then
                    MessageBox.Show(String.Format("Found text on page: {0} at X Position: {1} and at Y Position: {2}", page, xPos, yPos))
                End If
            End With

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        pdfDoc = Nothing
    End Sub


    '///////////////////////////////////////////////////////////////////////
    'This code snippet illustrates how to print a PDF document 
    '///////////////////////////////////////////////////////////////////////
    Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnPrint.Click

        '//get startup path for temp working files
        Dim requiredPath As String = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))))

        Dim pdfDoc As New CDIntfEx.Document
        pdfDoc.SetLicenseKey(StrLicenseTo, StrActivationCode)
        Try

            pdfDoc.Open(requiredPath & "\\Source_docs\\one.pdf")

            With pdfDoc
                'Print function available in Pro version only
                'Print(PrinterName As String, StartPage As Long, EndPage As Long, Copies As Long)
                'PrinterName
                '    Name of printer as it shows in the printers control panel.
                '    If this parameter is left empty, the document will print to the default printer.
                'StartPage
                '   Page number from which to start printing. The index of the first page is 1.
                'EndPage
                '   Page number at which to stop printing.
                'Copies
                '   Number of copies to print the document.
                '.Print "\\Server Name\Printer Name", 1, pdfDoc.PageCount, 1

                'Return code
                ' 0 is success
                ' -1 is a failure
                pdfDoc.Print("", 1, 1, 1)
            End With
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        pdfDoc = Nothing
    End Sub




    '///////////////////////////////////////////////////////////////////////
    'This code snippet illustrates how to automatically send the PDF document as an email 
    'attachment after the document is generated by the Amyuni PDF Converter.
    '///////////////////////////////////////////////////////////////////////
    Private Sub btnPrintSendByEmail_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnPrintSendByEmail.Click
        Dim pdf As New CDIntfEx.CDIntfEx
        pdf.DriverInit(AmyuniPrinterName)

        'Set Email Options
        pdf.EmailFieldFrom = "foo@bar.com"
        pdf.EmailFieldTo = "foobar@foo.com"
        pdf.EmailSubject = "This is a PDF attachment"
        pdf.EmailMessage = "This is an email message body"
        pdf.EmailPrompt = True

        Dim strCurrentPrinter As String = PrintDocument1.PrinterSettings.PrinterName
        PrintDocument1.PrinterSettings.PrinterName = AmyuniPrinterName

        pdf.FileNameOptionsEx = NoPropmt + SendByEmail

        pdf.EnablePrinter(StrLicenseTo, StrActivationCode)
        'Print Something
        PrintDocument1.Print()


        pdf.FileNameOptionsEx = 0
        PrintDocument1.PrinterSettings.PrinterName = strCurrentPrinter

        ListBox1.Items.Add("Document sent by email  ....... ")
    End Sub


    '///////////////////////////////////////////////////////////////////////
    'This code snippet illustrates how print a MsWord document to the Amyuni PDF Converter
    '///////////////////////////////////////////////////////////////////////
    Private Sub btnPrintMsWord_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnPrintMsWord.Click
        '//get startup path for temp working files
        Dim requiredPath As String =
                Path.GetDirectoryName(
                    Path.GetDirectoryName(
                        Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))))

        _pdf = New CDIntfEx.CDIntfEx
        _pdf.DriverInit(AmyuniPrinterName)

        'Create Word objects
        Dim pdfWord As New Application
        Dim msDoc As Document

        With _pdf

            .DefaultFileName = requiredPath & "\\Resulting_Docs\\PrintMsWord_resulting.pdf"
            .FileNameOptionsEx = NoPropmt + UseFileName

        End With


        Try
            pdfWord.Visible = False
            'Get Word’s current active printer
            Dim currentPrinter As String = pdfWord.ActivePrinter

            'Set the PDF Converter as Word’s active printer. 
            'This  is more efficient than changing the system’s default printer
            pdfWord.ActivePrinter = (AmyuniPrinterName)

            _pdf.EnablePrinter(StrLicenseTo, StrActivationCode)

            msDoc = pdfWord.Documents.Open(requiredPath & "\\Source_docs\\tenpages.doc")

            'Make sure to set Background printing to OFF
            msDoc.PrintOut(Background:=False)

            CType(msDoc, _Document).Close()

            'Reset the active printe back
            pdfWord.ActivePrinter = currentPrinter

            ListBox1.Items.Add("PrintMsWord_resulting.pdf ..... created")

        Catch exc As Exception
            'Catch and display errors
            MsgBox("Error Printing")
        End Try

        'Clean up
        CType(pdfWord, _Application).Quit()
        msDoc = Nothing
        pdfWord = Nothing

        'PDF.DriverEnd()
        _pdf.FileNameOptions = 0


    End Sub
End Class
