
Imports System.IO
Imports TSpdf.Kernel.Font

Imports System.Security.Cryptography.X509Certificates

Imports System.Security.Cryptography
Imports TSpdf.Kernel.Pdf
Imports TSpdf.Kernel.Utils
Imports TSpdf.Forms
Imports TSpdf.Signatures
Imports System.Text
Imports TSpdf.Kernel.Pdf.Action
Imports TSpdf.Kernel.Pdf.Navigation
Imports TSpdf.Kernel.Pdf.Canvas
Imports TSpdf.Kernel.Geom
Imports TSpdf.Layout.Element
Imports TSpdf.IO.Font.Constants
Imports System.Diagnostics.Contracts
Imports System.Text.RegularExpressions
Imports Microsoft.VisualBasic.Devices
Imports Org.BouncyCastle.Asn1
Imports Org.BouncyCastle.Pkcs
Imports TSpdf.Commons.Bouncycastle.Cert
Imports TSpdf.Commons.Bouncycastle.Crypto
Imports TSpdf.Bouncycastle.Crypto
Imports TSpdf.Bouncycastle.Cert
Imports Org.BouncyCastle.Asn1.X509
Imports Org.BouncyCastle.X509
Imports Org.BouncyCastle.Crypto.Tls
Imports TSpdf
Imports TSpdf.Kernel.Pdf.Canvas.Parser
Imports TSpdf.Kernel.Pdf.Canvas.Parser.Listener

Public Class pdf
    Public Shared Sub Aplanar(Origen As String)
        Dim PdfDocument = New PdfDocument(New PdfReader(Origen))
        Dim form = PdfAcroForm.GetAcroForm(PdfDocument, False)
        If form IsNot Nothing Then form.FlattenFields()
        PdfDocument.Close()
    End Sub

    Public Shared Sub Aplanar(Origen As String, Destino As String)
        Dim PdfDocument = New PdfDocument(New PdfReader(Origen), New PdfWriter(Destino))
        Dim form = PdfAcroForm.GetAcroForm(PdfDocument, False)
        If form IsNot Nothing Then form.FlattenFields()
        PdfDocument.Close()
    End Sub

    Public Shared Function ObtieneFicheroAleatorio(ByVal Extension As String) As String
        Dim sFichero As String = System.IO.Path.GetTempPath & System.IO.Path.GetRandomFileName & "." & Extension
        Do While System.IO.File.Exists(sFichero)
            'Try
            '    IO.File.Delete(sFichero)
            'Catch ex As Exception
            sFichero = System.IO.Path.GetTempPath & "\" & System.IO.Path.GetRandomFileName & "." & Extension
            ' End Try
        Loop
        Return sFichero
    End Function

    Public Shared Sub UnePdfs(Pdfs()() As Byte, outputPdf As String, Optional UnirTags As Boolean = True, Optional UnirMarcadores As Boolean = True, Optional MarcadoresInicioFichero() As String = Nothing, Optional Aplanar As Boolean = True)
        Dim lista = Pdfs.Select(Function(x) New MemoryStream(x)).ToArray
        UnePdfs(lista, outputPdf, UnirTags, UnirMarcadores, MarcadoresInicioFichero, Aplanar)
    End Sub

    Public Shared Sub UnePdfs(Pdfs() As String, st As Stream, Optional UnirTags As Boolean = True, Optional UnirMarcadores As Boolean = True, Optional MarcadoresInicioFichero() As String = Nothing, Optional Aplanar As Boolean = True)
        Try
            Dim pdfw As New PdfWriter(st)
            Dim pdfDoc As PdfDocument = New PdfDocument(pdfw)
            Dim merger As PdfMerger = New PdfMerger(pdfDoc, UnirTags, UnirMarcadores)
            Dim i As Integer = 0
            Dim NumeroPaginasTotal As Integer = 1
            Dim rootoutline As PdfOutline = Nothing
            Dim pagini(Pdfs.Count - 1) As Integer
            For Each pdf In Pdfs
                i += 1
                Dim pdfr As New PdfReader(pdf)
                pdfr.SetUnethicalReading(True)
                Dim ms As New MemoryStream
                Dim pdfwtmp As New PdfWriter(ms)
                Dim srcDoc As PdfDocument

                If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores Then
                    srcDoc = New PdfDocument(pdfr, pdfwtmp)
                    MueveMarcadorARaiz(srcDoc, MarcadoresInicioFichero(i - 1))
                    srcDoc.Close()
                    pdfr = New PdfReader(New MemoryStream(ms.ToArray))
                    srcDoc = New PdfDocument(pdfr)
                Else
                    srcDoc = New PdfDocument(pdfr)
                End If
                Dim np = srcDoc.GetNumberOfPages
                pagini(i - 1) = np
                If Aplanar Then
                    Dim form = PdfAcroForm.GetAcroForm(srcDoc, False)
                    If form IsNot Nothing Then form.FlattenFields()
                End If
                merger.SetCloseSourceDocuments(i = Pdfs.Count).Merge(srcDoc, 1, np)
                srcDoc.Close()
            Next
            If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores = False Then
                pdfDoc.InitializeOutlines()
                rootoutline = pdfDoc.GetOutlines(False)
                For i = 0 To pagini.Length - 1
                    Dim oul As PdfOutline = rootoutline.AddOutline(MarcadoresInicioFichero(i))
                    oul.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(NumeroPaginasTotal)))
                    NumeroPaginasTotal += pagini(i)
                Next
            End If
            pdfDoc.Close()
            pdfw.Close()
            merger.Close()
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub

    Public Shared Sub UnePdfs(Pdfs() As String, outputPdf As String, Optional UnirTags As Boolean = True, Optional UnirMarcadores As Boolean = True, Optional MarcadoresInicioFichero() As String = Nothing, Optional Aplanar As Boolean = True)
        Try
            Dim pdfw As New PdfWriter(outputPdf)
            Dim pdfDoc As PdfDocument = New PdfDocument(pdfw)
            Dim merger As PdfMerger = New PdfMerger(pdfDoc, UnirTags, UnirMarcadores)
            Dim i As Integer = 0
            Dim NumeroPaginasTotal As Integer = 1
            Dim rootoutline As PdfOutline = Nothing
            Dim pagini(Pdfs.Count - 1) As Integer
            For Each pdf In Pdfs
                i += 1
                Dim pdfr As New PdfReader(pdf)
                pdfr.SetUnethicalReading(True)
                Dim ms As New MemoryStream
                Dim pdfwtmp As New PdfWriter(ms)
                Dim srcDoc As PdfDocument

                If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores Then
                    srcDoc = New PdfDocument(pdfr, pdfwtmp)
                    MueveMarcadorARaiz(srcDoc, MarcadoresInicioFichero(i - 1))
                    srcDoc.Close()
                    pdfr = New PdfReader(New MemoryStream(ms.ToArray))
                    srcDoc = New PdfDocument(pdfr)
                Else
                    srcDoc = New PdfDocument(pdfr)
                End If
                Dim np = srcDoc.GetNumberOfPages
                pagini(i - 1) = np
                If Aplanar Then
                    Dim form = PdfAcroForm.GetAcroForm(srcDoc, False)
                    If form IsNot Nothing Then form.FlattenFields()
                End If
                merger.SetCloseSourceDocuments(i = Pdfs.Count).Merge(srcDoc, 1, np)
                srcDoc.Close()
            Next
            If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores = False Then
                pdfDoc.InitializeOutlines()
                rootoutline = pdfDoc.GetOutlines(False)
                For i = 0 To pagini.Length - 1
                    Dim oul As PdfOutline = rootoutline.AddOutline(MarcadoresInicioFichero(i))
                    oul.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(NumeroPaginasTotal)))
                    NumeroPaginasTotal += pagini(i)
                Next
            End If
            pdfDoc.Close()
            pdfw.Close()
            merger.Close()
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub
    Public Shared Sub UnePdfs(Pdfs() As Stream, outputPdf As String, Optional UnirTags As Boolean = True, Optional UnirMarcadores As Boolean = True, Optional MarcadoresInicioFichero() As String = Nothing, Optional Aplanar As Boolean = True)
        Try
            Dim pdfw As New PdfWriter(outputPdf)
            Dim pdfDoc As PdfDocument = New PdfDocument(pdfw)
            Dim merger As PdfMerger = New PdfMerger(pdfDoc, UnirTags, UnirMarcadores)
            Dim i As Integer = 0
            Dim NumeroPaginasTotal As Integer = 1
            Dim rootoutline As PdfOutline = Nothing
            Dim pagini(Pdfs.Count - 1) As Integer
            For Each pdf In Pdfs
                i += 1
                Dim pdfr As New PdfReader(pdf)
                pdfr.SetUnethicalReading(True)
                Dim ms As New MemoryStream
                Dim pdfwtmp As New PdfWriter(ms)
                Dim srcDoc As PdfDocument

                If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores Then
                    srcDoc = New PdfDocument(pdfr, pdfwtmp)
                    MueveMarcadorARaiz(srcDoc, MarcadoresInicioFichero(i - 1))
                    srcDoc.Close()
                    pdfr = New PdfReader(New MemoryStream(ms.ToArray))
                    srcDoc = New PdfDocument(pdfr)
                Else
                    srcDoc = New PdfDocument(pdfr)
                End If
                Dim np = srcDoc.GetNumberOfPages
                pagini(i - 1) = np
                If Aplanar Then
                    Dim form = PdfAcroForm.GetAcroForm(srcDoc, False)
                    If form IsNot Nothing Then form.FlattenFields()
                End If
                merger.SetCloseSourceDocuments(i = Pdfs.Count).Merge(srcDoc, 1, np)
                srcDoc.Close()
            Next
            If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores = False Then
                pdfDoc.InitializeOutlines()
                rootoutline = pdfDoc.GetOutlines(False)
                For i = 0 To pagini.Length - 1
                    Dim oul As PdfOutline = rootoutline.AddOutline(MarcadoresInicioFichero(i))
                    oul.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(NumeroPaginasTotal)))
                    NumeroPaginasTotal += pagini(i)
                Next
            End If
            pdfDoc.Close()
            pdfw.Close()
            merger.Close()
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try



    End Sub
    Public Shared Function UnePdfs(Pdfs()() As Byte, Optional UnirTags As Boolean = True, Optional UnirMarcadores As Boolean = True, Optional MarcadoresInicioFichero() As String = Nothing, Optional Aplanar As Boolean = True) As Byte()
        Dim lista = Pdfs.Select(Function(x) New MemoryStream(x)).ToArray
        Return UnePdfs(lista, UnirTags, UnirMarcadores, MarcadoresInicioFichero, Aplanar)
    End Function
    Public Shared Function UnePdfs(Pdfs() As Stream, Optional UnirTags As Boolean = True, Optional UnirMarcadores As Boolean = True, Optional MarcadoresInicioFichero() As String = Nothing, Optional Aplanar As Boolean = True) As Byte()
        Try
            Dim msw As New MemoryStream
            Dim pdfw As New PdfWriter(msw)
            Dim pdfDoc As PdfDocument = New PdfDocument(pdfw)
            Dim merger As PdfMerger = New PdfMerger(pdfDoc, UnirTags, UnirMarcadores)
            Dim i As Integer = 0
            Dim NumeroPaginasTotal As Integer = 1
            Dim rootoutline As PdfOutline = Nothing
            Dim pagini(Pdfs.Count - 1) As Integer
            For Each pdf In Pdfs
                i += 1
                Dim pdfr As New PdfReader(pdf)
                pdfr.SetUnethicalReading(True)
                Dim ms As New MemoryStream
                Dim pdfwtmp As New PdfWriter(ms)
                Dim srcDoc As PdfDocument

                If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores Then
                    srcDoc = New PdfDocument(pdfr, pdfwtmp)
                    MueveMarcadorARaiz(srcDoc, MarcadoresInicioFichero(i - 1))
                    srcDoc.Close()
                    pdfr = New PdfReader(New MemoryStream(ms.ToArray))
                    srcDoc = New PdfDocument(pdfr)
                Else
                    srcDoc = New PdfDocument(pdfr)
                End If
                Dim np = srcDoc.GetNumberOfPages
                pagini(i - 1) = np
                If Aplanar Then
                    Dim form = PdfAcroForm.GetAcroForm(srcDoc, False)
                    If form IsNot Nothing Then form.FlattenFields()
                End If
                merger.SetCloseSourceDocuments(i = Pdfs.Count).Merge(srcDoc, 1, np)
                srcDoc.Close()
            Next
            If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores = False Then
                pdfDoc.InitializeOutlines()
                rootoutline = pdfDoc.GetOutlines(False)
                For i = 0 To pagini.Length - 1
                    Dim oul As PdfOutline = rootoutline.AddOutline(MarcadoresInicioFichero(i))
                    oul.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(NumeroPaginasTotal)))
                    NumeroPaginasTotal += pagini(i)
                Next
            End If
            pdfDoc.Close()
            pdfw.Close()
            merger.Close()
            Return msw.ToArray
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Function

    Public Shared Sub UnePdfs(Pdfs() As Stream, Destino As Stream, Optional UnirTags As Boolean = True, Optional UnirMarcadores As Boolean = True, Optional MarcadoresInicioFichero() As String = Nothing, Optional Aplanar As Boolean = True)
        Try
            Dim pdfw As New PdfWriter(Destino)
            Dim pdfDoc As PdfDocument = New PdfDocument(pdfw)
            Dim merger As PdfMerger = New PdfMerger(pdfDoc, UnirTags, UnirMarcadores)
            Dim i As Integer = 0
            Dim NumeroPaginasTotal As Integer = 1
            Dim rootoutline As PdfOutline = Nothing
            Dim pagini(Pdfs.Count - 1) As Integer
            For Each pdf In Pdfs
                i += 1
                Dim pdfr As New PdfReader(pdf)
                pdfr.SetUnethicalReading(True)
                Dim ms As New MemoryStream
                Dim pdfwtmp As New PdfWriter(ms)
                Dim srcDoc As PdfDocument

                If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores Then
                    srcDoc = New PdfDocument(pdfr, pdfwtmp)
                    MueveMarcadorARaiz(srcDoc, MarcadoresInicioFichero(i - 1))
                    srcDoc.Close()
                    pdfr = New PdfReader(New MemoryStream(ms.ToArray))
                    srcDoc = New PdfDocument(pdfr)
                Else
                    srcDoc = New PdfDocument(pdfr)
                End If
                Dim np = srcDoc.GetNumberOfPages
                pagini(i - 1) = np
                If Aplanar Then
                    Dim form = PdfAcroForm.GetAcroForm(srcDoc, False)
                    If form IsNot Nothing Then form.FlattenFields()
                End If
                merger.SetCloseSourceDocuments(i = Pdfs.Count).Merge(srcDoc, 1, np)
                srcDoc.Close()
            Next
            If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores = False Then
                pdfDoc.InitializeOutlines()
                rootoutline = pdfDoc.GetOutlines(False)
                For i = 0 To pagini.Length - 1
                    Dim oul As PdfOutline = rootoutline.AddOutline(MarcadoresInicioFichero(i))
                    oul.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(NumeroPaginasTotal)))
                    NumeroPaginasTotal += pagini(i)
                Next
            End If
            pdfDoc.Close()
            pdfw.Close()
            merger.Close()
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub

    Public Shared Function UnePdfs(Pdfs() As String, Optional UnirTags As Boolean = True, Optional UnirMarcadores As Boolean = True, Optional MarcadoresInicioFichero() As String = Nothing, Optional Aplanar As Boolean = True) As Byte()
        Try
            Dim msw As New MemoryStream
            Dim pdfw As New PdfWriter(msw)
            Dim pdfDoc As PdfDocument = New PdfDocument(pdfw)
            Dim merger As PdfMerger = New PdfMerger(pdfDoc, UnirTags, UnirMarcadores)
            Dim i As Integer = 0
            Dim NumeroPaginasTotal As Integer = 1
            Dim rootoutline As PdfOutline = Nothing
            Dim pagini(Pdfs.Count - 1) As Integer
            For Each pdf In Pdfs
                i += 1
                Dim pdfr As New PdfReader(pdf)
                pdfr.SetUnethicalReading(True)
                Dim ms As New MemoryStream
                Dim pdfwtmp As New PdfWriter(ms)
                Dim srcDoc As PdfDocument

                If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores Then
                    srcDoc = New PdfDocument(pdfr, pdfwtmp)
                    MueveMarcadorARaiz(srcDoc, MarcadoresInicioFichero(i - 1))
                    srcDoc.Close()
                    pdfr = New PdfReader(New MemoryStream(ms.ToArray))
                    srcDoc = New PdfDocument(pdfr)
                Else
                    srcDoc = New PdfDocument(pdfr)
                End If
                Dim np = srcDoc.GetNumberOfPages
                pagini(i - 1) = np
                If Aplanar Then
                    Dim form = PdfAcroForm.GetAcroForm(srcDoc, False)
                    If form IsNot Nothing Then form.FlattenFields()
                End If
                merger.SetCloseSourceDocuments(i = Pdfs.Count).Merge(srcDoc, 1, np)
                srcDoc.Close()
            Next
            If MarcadoresInicioFichero IsNot Nothing AndAlso UnirMarcadores = False Then
                pdfDoc.InitializeOutlines()
                rootoutline = pdfDoc.GetOutlines(False)
                For i = 0 To pagini.Length - 1
                    Dim oul As PdfOutline = rootoutline.AddOutline(MarcadoresInicioFichero(i))
                    oul.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(NumeroPaginasTotal)))
                    NumeroPaginasTotal += pagini(i)
                Next
            End If
            pdfDoc.Close()
            pdfw.Close()
            merger.Close()
            Return msw.ToArray
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try

    End Function


    Private Shared Sub MueveMarcadorARaiz(ByVal pdfDocument As PdfDocument, ByVal EtiquetaMarcadorRaiz As String)
        pdfDocument.InitializeOutlines()
        Try
            Dim pp = pdfDocument.GetFirstPage()
            Dim rootOutline As PdfOutline = pdfDocument.GetOutlines(False)
            Dim subOutline As PdfOutline = rootOutline.AddOutline(EtiquetaMarcadorRaiz)


            Dim dest As PdfDestination = PdfExplicitDestination.CreateFit(pp)
            subOutline.AddDestination(dest)
            Dim pdfOutlineChildren As List(Of PdfOutline) = rootOutline.GetAllChildren().ToList
            If pdfOutlineChildren.Count = 1 Then
                Return
            End If
            Dim i As Integer = 0
            Dim p As PdfOutline

            For Each p In pdfOutlineChildren
                If Not p.Equals(subOutline) Then
                    Dim nd = p.GetDestination
                    If nd Is Nothing Then nd = dest
                    dest = nd
                    Corrigeoutl(p, dest)
                    subOutline.AddOutline(p)
                End If
            Next
            rootOutline.GetAllChildren().Clear()
            rootOutline.AddOutline(subOutline)
            subOutline.AddDestination(PdfExplicitDestination.CreateFit(pdfDocument.GetFirstPage()))
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub
    Private Shared Sub CreaMarcadorInicioFichero(ByVal pdfDocument As PdfDocument, ByVal EtiquetaMarcadorRaiz As String)
        pdfDocument.InitializeOutlines()
        Try
            Dim pp = pdfDocument.GetFirstPage()
            Dim rootOutline As PdfOutline = pdfDocument.GetOutlines(False)
            Dim subOutline As PdfOutline = rootOutline.AddOutline(EtiquetaMarcadorRaiz)


            Dim dest As PdfDestination = PdfExplicitDestination.CreateFit(pp)
            subOutline.AddDestination(dest)
            Dim pdfOutlineChildren As List(Of PdfOutline) = rootOutline.GetAllChildren().ToList
            If pdfOutlineChildren.Count = 1 Then
                Return
            End If
            Dim i As Integer = 0
            Dim p As PdfOutline

            For Each p In pdfOutlineChildren
                If Not p.Equals(subOutline) Then
                    Dim nd = p.GetDestination
                    If nd Is Nothing Then nd = dest
                    dest = nd
                    Corrigeoutl(p, dest)
                    subOutline.AddOutline(p)
                End If
            Next
            rootOutline.GetAllChildren().Clear()
            rootOutline.AddOutline(subOutline)
            subOutline.AddDestination(PdfExplicitDestination.CreateFit(pdfDocument.GetFirstPage()))
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub

    Private Shared Sub Corrigeoutl(p As PdfOutline, ByRef ultimoDestino As PdfDestination)
        If p.GetDestination Is Nothing Then
            p.AddDestination(ultimoDestino)
        End If
        Dim hijos = p.GetAllChildren
        For Each h In hijos
            If h.GetDestination Is Nothing OrElse h.GetDestination.GetPdfObject Is Nothing Then
                h.AddDestination(ultimoDestino)
            End If
            ultimoDestino = h.GetDestination
            Corrigeoutl(h, ultimoDestino)
        Next
    End Sub


    Public Shared Function ObtieneNumeroPaginasPDF(PDF As String) As Integer
        Dim pdfr As New PdfReader(PDF)
        Dim NP = New PdfDocument(pdfr).GetNumberOfPages
        pdfr.Close()
        Return NP
    End Function

    Public Shared Sub ConvierteAPDFX(PdfOrigen As String, PdfDestino As String)
        Dim wp As WriterProperties = New WriterProperties()
        wp.SetPdfVersion(PdfVersion.PDF_1_3)
        Dim pdfDoc As PdfDocument = New PdfDocument(New PdfReader(PdfOrigen), New PdfWriter(PdfDestino, wp))
        pdfDoc.Close()
    End Sub


    Public Shared Sub RotarPdf(ByVal PdfOrigen As String, ByVal PdfDestino As String, Grados As Integer)

        Dim pdfDoc As PdfDocument = New PdfDocument(New PdfReader(PdfOrigen), New PdfWriter(PdfDestino))
        For p As Integer = 1 To pdfDoc.GetNumberOfPages()
            Dim page As PdfPage = pdfDoc.GetPage(p)
            Dim rotate As Integer = page.GetRotation()
            If rotate = 0 Then
                page.SetRotation(Grados)
            Else
                page.SetRotation((rotate + Grados) Mod 360)
            End If
        Next
        pdfDoc.Close()

    End Sub







    Public Shared Sub RecortaPDF(ByVal PdfOrigen As String, PdfRecortado As String, PaginaInicio As Integer, PaginaFin As Integer)
        Dim pdfDoc As PdfDocument = New PdfDocument(New PdfWriter(PdfRecortado))
        Dim merger As PdfMerger = New PdfMerger(pdfDoc, False, False)
        Dim srcDoc As PdfDocument = New PdfDocument(New PdfReader(PdfOrigen))
        Dim np = srcDoc.GetNumberOfPages
        merger.SetCloseSourceDocuments(True).Merge(srcDoc, PaginaInicio, PaginaFin)
        pdfDoc.Close()
    End Sub




    Public Shared Sub RellenaFormularioPDF(PdfOrigen As String, PdfDestino As String, Valores As Hashtable, Optional Aplanar As Boolean = True)
        Try
            Dim fs As New FileStream(PdfDestino, FileMode.CreateNew, FileAccess.Write)
            RellenaFormularioPDF(PdfOrigen, fs, Valores, Aplanar)
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub

    Public Shared Sub RellenaFormularioPDF(PdfOrigen As String, PdfDestino As String, Valores As String, Optional Aplanar As Boolean = True)
        Try
            Dim fs As New FileStream(PdfDestino, FileMode.CreateNew, FileAccess.Write)
            Dim ht As New Hashtable
            Dim pares = Valores.Split("|")
            For Each par In pares
                ht.Add(par.Split(":")(0), par.Split(":")(1))
            Next
            RellenaFormularioPDF(PdfOrigen, fs, ht, Aplanar)
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub


    Public Shared Sub RellenaFormularioPDF(PdfOrigen As String, Destino As Stream, Valores As Hashtable, Optional Aplanar As Boolean = True)
        Try
            Dim pdfReader As New PdfReader(PdfOrigen)
            Dim pdfDoc As New PdfDocument(pdfReader, New PdfWriter(Destino))
            Dim form = PdfAcroForm.GetAcroForm(pdfDoc, True)
            For Each Valor As DictionaryEntry In Valores
                Try
                    form.GetField(Valor.Key).SetValue(Valor.Value)
                Catch ex As Exception
                End Try
            Next
            If Aplanar Then
                form.FlattenFields()
            End If
            pdfDoc.Close()
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub


    Public Shared Function RellenaFormularioPDF(PdfOrigen As Byte(), ListaValores As List(Of Hashtable), Optional Aplanar As Boolean = True) As Byte()

        Try

            Dim i, j As Integer
            Dim iosPdf(ListaValores.Count - 1)() As Byte
            For i = 0 To ListaValores.Count - 1
                Dim pdfReader As New PdfReader(New MemoryStream(PdfOrigen))
                Dim Valores = ListaValores(i)
                Dim ms As New MemoryStream
                Dim pdfDoc As New PdfDocument(pdfReader, New PdfWriter(ms))
                Dim form = PdfAcroForm.GetAcroForm(pdfDoc, True)
                For Each Valor As DictionaryEntry In Valores
                    Try
                        form.GetField(Valor.Key).SetValue(Valor.Value)
                    Catch ex As Exception
                    End Try
                Next
                If Aplanar Then
                    form.FlattenFields()
                End If
                pdfDoc.Close()
                '   ms.Seek(0, 0)
                iosPdf(i) = ms.ToArray
            Next
            If ListaValores.Count = 1 Then
                Return iosPdf(0).ToArray
            Else
                Return UnePdfs(iosPdf)
            End If
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Function

    Public Shared Function RellenaFormularioPDF(PdfOrigen As Byte(), Valores As Hashtable, Optional Aplanar As Boolean = True) As Byte()

        Try
            Dim pdfReader As New PdfReader(New MemoryStream(PdfOrigen))
            Dim ms As New MemoryStream
            Dim pdfDoc As New PdfDocument(pdfReader, New PdfWriter(ms))
            Dim form = PdfAcroForm.GetAcroForm(pdfDoc, True)
            For Each Valor As DictionaryEntry In Valores
                Try
                    Dim f = form.GetField(Valor.Key)
                    If f IsNot Nothing Then f.SetValue(Valor.Value)
                Catch ex As Exception
                End Try
            Next
            If Aplanar Then
                form.FlattenFields()
            End If
            pdfDoc.Close()
            If ms.CanSeek Then ms.Seek(0, 0)
            Return ms.ToArray
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Function
    Public Shared Sub AñadePropiedadesAPdf(ByVal FicheroPdf As String, ByVal Valores As Hashtable)

        Try
            Dim ms As New MemoryStream
            Dim pdfReader As New PdfReader(FicheroPdf)
            Dim pdfDoc As New PdfDocument(pdfReader, New PdfWriter(ms))
            Dim info = pdfDoc.GetDocumentInfo()

            Dim newInfo As IDictionary(Of String, String) = New Dictionary(Of String, String)()
            For Each Valor As DictionaryEntry In Valores
                Try
                    newInfo.Add(CStr(Valor.Key), Valor.Value)
                Catch ex As Exception
                End Try
            Next
            info.SetMoreInfo(newInfo)
            pdfDoc.Close()
            Dim b = ms.ToArray
            pdfReader.Close()
            System.IO.File.Delete(FicheroPdf)
            System.IO.File.WriteAllBytes(FicheroPdf, b)

        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub
    Public Shared Sub AñadePropiedadesAPdf(pdfDoc As PdfDocument, ByVal Valores As Hashtable)

        Try
            Dim ms As New MemoryStream

            Dim info = pdfDoc.GetDocumentInfo()

            Dim newInfo As IDictionary(Of String, String) = New Dictionary(Of String, String)()
            For Each Valor As DictionaryEntry In Valores
                Try
                    newInfo.Add(Valor.Key, Valor.Value)
                Catch ex As Exception
                End Try
            Next
            info.SetMoreInfo(newInfo)
            pdfDoc.Close()
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub

    Public Shared Function AñadePropiedadesAPdf(ByVal FicheroPdf As MemoryStream, ByVal Valores As Hashtable) As MemoryStream
        Try
            Dim ms As New MemoryStream
            Dim pdfReader As New PdfReader(FicheroPdf)
            Dim pdfDoc As New PdfDocument(pdfReader, New PdfWriter(ms))
            Dim info = pdfDoc.GetDocumentInfo()

            Dim newInfo As IDictionary(Of String, String) = New Dictionary(Of String, String)()
            For Each Valor As DictionaryEntry In Valores
                Try
                    newInfo.Add(Valor.Key, Valor.Value)
                Catch ex As Exception
                End Try
            Next
            info.SetMoreInfo(newInfo)
            pdfDoc.Close()
            If ms.CanSeek Then ms.Seek(0, 0)
            Return ms
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Function

    Public Shared Function ExtractTextFromPDF(ByVal RutaPdf As String) As String
        Dim pdfReader As PdfReader = New PdfReader(RutaPdf)
        Dim pdfDoc As PdfDocument = New PdfDocument(pdfReader)
        Dim contenido As String = ""
        Dim Estrategia = New SimpleTextExtractionStrategy
        For page As Integer = 1 To pdfDoc.GetNumberOfPages()
            Dim pagina = pdfDoc.GetPage(page)
            Dim Texto = PdfTextExtractor.GetTextFromPage(pagina, Estrategia)
            contenido &= Texto & vbCrLf
        Next
        pdfDoc.Close()
        pdfReader.Close()
        Return contenido
    End Function

    Public Shared Sub PruebaSellado(FicheroASellar As String, FicheroDestino As String)
        Dim pdfr As New PdfReader(FicheroASellar)
        Dim pdfw = New PdfWriter(FicheroDestino)
        Dim wp As New WriterProperties
        'Dim cl = pdfr.GetPdfAConformanceLevel()


        Dim pdfd As New PdfDocument(pdfr, pdfw)


        Dim np = pdfd.GetNumberOfPages
        Dim fuente = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN)

        For i = 1 To np
            Dim page As PdfPage = pdfd.GetPage(i)
            Dim pdfc As New PdfCanvas(page)
            Dim fc As New PdfCanvas(page.NewContentStreamAfter, page.GetResources, pdfd)

            pdfc.BeginText()
            pdfc.SetFontAndSize(fuente, 12)

            pdfc.MoveText(0, 0)

            pdfc.ShowText("PRUEBA PRUEBA")

            pdfc.EndText()

        Next

        pdfd.Close()
        pdfw.Close()
    End Sub
End Class

