Visual Basic.NET - ¡Ayuda! Como unir dos pdf con la libreria itextsharp

 
Vista:
sin imagen de perfil

¡Ayuda! Como unir dos pdf con la libreria itextsharp

Publicado por Carlos (19 intervenciones) el 08/05/2013 11:32:33
Hola buenas, soy yo otra vez, el cansino de antes.

Lamento el titulo tan poco explicativo de mi anterior tema: Como unir dos pdf usando

Meti la pata al olvidar escribir que era usando itextsharp.


Aqui les ofrezco posibles soluciones (necesito que me ayuden a solucionar errores del codigo vb.net). No se asusten por la longitud del mensaje, es que he añadido dos codigos enteros.

En fin, esto es lo que he encontrado:

Link en C# que realiza la union de pdf con itextsharp:

http://ant2e6.webs-interesantes.es/Articulos/Utilidades/Combinar-PDF.htm

Yo sinceramente no se usar C# (por lo que en realidad este codigo no me vale de gran cosa).

A todo esto, aqui les doy el codigo en C#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
internal static bool Merge(string strFileTarget, string [] arrStrFilesSource)
{ bool blnMerged = false;
 
  // Crea el PDF de salida
  try
    { using (System.IO.FileStream stmFile = new System.IO.FileStream(strFileTarget, System.IO.FileMode.Create))
        { Document objDocument = null;
          PdfWriter objWriter = null;
 
          // Recorre los archivos
          for (int intIndexFile = 0; intIndexFile < arrStrFilesSource.Length; intIndexFile++)
            { PdfReader objReader = new PdfReader(arrStrFilesSource[intIndexFile]);
              int intNumberOfPages = objReader.NumberOfPages;
 
              // La primera vez, inicializa el documento y el escritor
              if (intIndexFile == 0)
                { // Asigna el documento y el generador
                  objDocument = new Document(objReader.GetPageSizeWithRotation(1));
                  objWriter = PdfWriter.GetInstance(objDocument, stmFile);
                  // Abre el documento
                  objDocument.Open();
                }
              // Añade las páginas
              for (int intPage = 0; intPage < intNumberOfPages; intPage++)
                { int intRotation = objReader.GetPageRotation(intPage + 1);
                  PdfImportedPage objPage = objWriter.GetImportedPage(objReader, intPage + 1);
 
                  // Asigna el tamaño de la página
                  objDocument.SetPageSize(objReader.GetPageSizeWithRotation(intPage + 1));
                  // Crea una nueva página
                  objDocument.NewPage();
                  // Añade la página leída
                  if (intRotation == 90 || intRotation == 270)
                    objWriter.DirectContent.AddTemplate(objPage, 0, -1f, 1f, 0, 0,
                                                        objReader.GetPageSizeWithRotation(intPage + 1).Height);
                  else
                    objWriter.DirectContent.AddTemplate(objPage, 1f, 0, 0, 1f, 0, 0);
                 }
            }
          // Cierra el documento
          if (objDocument != null)
            objDocument.Close();
          // Cierra el stream del archivo
          stmFile.Close();
        }
      // Indica que se ha creado el documento
      blnMerged = true;
    }
  catch(Exception objException)
    { System.Diagnostics.Debug.WriteLine(objException.Message);
    }
  // Devuelve el valor que indica si se han mezclado los archivos
  return blnMerged;
}



Pero como ya habreis deducido, yo no utilizo C#, sino el maravilloso .net (vb.net).

Y realize una traduccion del codigo.

Lo malo es que al implementar el codigo me saltan errores, y agradeceria cualquier ayuda con esos errores.

Aqui les dejo el codigo en .net:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
Friend Shared Function Merge(ByVal strFileTarget As String, ByVal arrStrFilesSource() As String) As Boolean
        Dim blnMerged As Boolean = False
 
        ' Crea el PDF de salida
        Try
            Using stmFile As System.IO.FileStream = New System.IO.FileStream(strFileTarget, System.IO.FileMode.Create)
                Dim objDocument As Document = Nothing
                Dim objWriter As PdfWriter = Nothing
                ' Recorre los archivos
 
                For intIndexFile As Integer = 0 To arrStrFilesSource.Length - 1
                    Dim IntegerIndexFile As Integer
                    Dim objReader(0 To IntegerIndexFile - 1) As PdfReader
 
                    Dim intNumberOfPages As Integer = objReader(0 To IntegerIndexFile - 1).NumberOfPages
                    ' La primera vez, inicializa el documento y el escritor
                    If IntegerIndexFile = 0 Then
                        ' Asigna el documento y el generador
 
                        ''LINEA ERROR:  objDocument = New Document(objReader.GetPageSizeWithRotation(1))
                        ''vale, el error que me sale es: GetPageSizeWithRotation(1) is not a member of System.Array
                        objDocument = New Document(objReader.GetPageSizeWithRotation(1))
 
 
                        objWriter = PdfWriter.GetInstance(objDocument, stmFile)
                        ' Abre el documento
                        objDocument.Open()
 
                    End If
                    ' Añade las páginas
                    For IntegerPage As Integer = 0 To intNumberOfPages - 1
 
                        ''LINEA ERROR:  Dim intRotation As Integer = objReader.GetPageRotation(IntegerPage + 1)
                        ''Error: GetPageRotation is not a member of System.Array
                        Dim intRotation As Integer = objReader.GetPageRotation(IntegerPage + 1)
 
                        ''LINEA ERROR:  Dim objPage As PdfImportedPage = objWriter.GetImportedPage(objReader, IntegerPage + 1)
                        ''Error: Value of type '1-dimensional array of iTextSharp.text.pdf.PdfReader' cannot be converted to 'iTextSharp.text.pdf.PdfReader'
                        Dim objPage As PdfImportedPage = objWriter.GetImportedPage(objReader, IntegerPage + 1)
 
                        ' Asigna el tamaño de la página
 
                        ''LINEA ERROR:  objDocument.SetPageSize(objReader.GetPageSizeWithRotation(IntegerPage + 1))
                        ''Error: GetPageSizeWithRotation(1) is not a member of System.Array
                        objDocument.SetPageSize(objReader.GetPageSizeWithRotation(IntegerPage + 1))
 
                        ' Crea una nueva página
                        objDocument.NewPage()
                        ' Añade la página leída
                        Dim IntegerRotation As Integer
                        If IntegerRotation = 90 OrElse IntegerRotation = 270 Then
 
                            ''LINEA ERROR:  esta de abajo tan sumuamente larga
                            ''Error: GetPageSizeWithRotation(1) is not a member of System.Array
                            objWriter.DirectContent.AddTemplate(objPage, 0, -1.0F, 1.0F, 0, 0, objReader.GetPageSizeWithRotation(IntegerPage + 1).Height)
 
                        Else
                            objWriter.DirectContent.AddTemplate(objPage, 1.0F, 0, 0, 1.0F, 0, 0)
 
                        End If
 
                    Next
                    ' Cierra el documento
                    If objDocument IsNot Nothing Then
                        objDocument.Close()
                    End If
                    ' Cierra el stream del archivo
                    stmFile.Close()
 
                Next
                ' Indica que se ha creado el documento
                blnMerged = True
 
            End Using
        Catch objException As Exception
            System.Diagnostics.Debug.WriteLine(objException.Message)
 
        End Try
 
        ' Devuelve el valor que indica si se han mezclado los archivos
        Return blnMerged
 
    End Function



En fin, si alguien pudiese decirme como solucionar estos errores y hacer que el metodo funciones (vamos, que una unos pocos pdf en uno solo), ya sea modificando la sintaxis de las lineas que tienen error, proponiendo otros codigos...... como sea, cualquier ayuda sera bienvenida

Por cualquier duda sobre los codigos que he mostrado preguntad en el foro o en mi correo, solucionare cualquier duda (en la medida de lo posibl, ya que soy yo el primero que tiene dudas, jajajja).

Nos vemos en el foro.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
1
Responder
sin imagen de perfil

¡Ayuda! Como unir dos pdf con la libreria itextsharp

Publicado por Carlos (19 intervenciones) el 08/05/2013 13:58:15
Hola buenas, soy yo otra vez, el pesao ese de los pdf y de los escaneres (menos mal que lo reconozco)


Tengo la solucion DEFINITIVA.

El codigo lo pille de:http://www.codeproject.com/Articles/69177/PDF-Merge

Pero era un pelin lioso, asi que lo modifique para hacerlo mas asquible por los usuarios a este otro codigo que os mostrare a continuacion.

Para usarlo necesitaremos: un formulario con un boton un textbox y la libreria itextsharp.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
Function GetPageCount(ByVal sFolderPath As String) As Integer
        Dim iRet As Integer = 0
        Dim oFiles As String() = Directory.GetFiles(sFolderPath)
 
        For i As Integer = 0 To oFiles.Length - 1
            Dim sFromFilePath As String = oFiles(i)
            Dim oFileInfo As New FileInfo(sFromFilePath)
            Dim sExt As String = UCase(oFileInfo.Extension).Substring(1, 3)
            If sExt = "PDF" Then
                iRet += 1
            End If
        Next
 
        Return iRet
 
    End Function
 
    Sub ProccessFolder(ByVal sFolderPath As String)
 
        btnProcess.Enabled = False
 
        Dim bOutputfileAlreadyExists As Boolean = False
        Dim oFolderInfo As New System.IO.DirectoryInfo(sFolderPath)
        Dim sOutFilePath As String = sFolderPath + "\"
        'Dim sOutFilePath As String = sFolderPath + "\" + oFolderInfo.Name + ".pdf"
        If System.IO.File.Exists(sOutFilePath) Then
            Try
                MessageBox.Show("Ya existe el archivo")
            Catch ex As Exception
                MessageBox.Show("Se supone que fue eliminado el archivo, pero yo no lo hice, jaja")
            End Try
        End If
 
        Dim iPageCount As Integer = GetPageCount(sFolderPath)
        If iPageCount > 0 And bOutputfileAlreadyExists = False Then
 
 
            Dim oFiles As String() = Directory.GetFiles(sFolderPath)
 
            Dim oPdfDoc As New iTextSharp.text.Document()
            Dim oPdfWriter As PdfWriter = PdfWriter.GetInstance(oPdfDoc, New FileStream(sOutFilePath, FileMode.Create))
            oPdfDoc.Open()
 
            For i As Integer = 0 To oFiles.Length - 1
                Dim sFromFilePath As String = oFiles(i)
                Dim oFileInfo As New FileInfo(sFromFilePath)
                Dim sExt As String = UCase(oFileInfo.Extension).Substring(1, 3)
 
                Try
 
                    If sExt = "PDF" Then
                        AddPdf(sFromFilePath, oPdfDoc, oPdfWriter)
                    End If
 
 
 
                Catch ex As Exception
                    MessageBox.Show("Ummm, algo fallo")
 
                End Try
 
            Next
 
            Try
                oPdfDoc.Close()
                oPdfWriter.Close()
            Catch ex As Exception
 
                Try
                    System.IO.File.Delete(sOutFilePath)
                Catch ex2 As Exception
                End Try
            End Try
 
 
        End If
 
        btnProcess.Enabled = True
 
        Dim oFolders As String() = Directory.GetDirectories(sFolderPath)
        For i As Integer = 0 To oFolders.Length - 1
            Dim sChildFolder As String = oFolders(i)
            Dim iPos As Integer = sChildFolder.LastIndexOf("\")
            Dim sFolderName As String = sChildFolder.Substring(iPos + 1)
            ProccessFolder(sChildFolder)
        Next
 
    End Sub
 
    Sub AddPdf(ByVal sInFilePath As String, ByRef oPdfDoc _
               As iTextSharp.text.Document, ByVal oPdfWriter As PdfWriter)
 
        Dim oDirectContent As iTextSharp.text.pdf.PdfContentByte = _
                              oPdfWriter.DirectContent
        Dim oPdfReader As iTextSharp.text.pdf.PdfReader = _
            New iTextSharp.text.pdf.PdfReader(sInFilePath)
        Dim iNumberOfPages As Integer = oPdfReader.NumberOfPages
        Dim iPage As Integer = 0
 
        Do While (iPage < iNumberOfPages)
            iPage += 1
            oPdfDoc.SetPageSize(oPdfReader.GetPageSizeWithRotation(iPage))
            oPdfDoc.NewPage()
 
            Dim oPdfImportedPage As iTextSharp.text.pdf.PdfImportedPage = _
                oPdfWriter.GetImportedPage(oPdfReader, iPage)
            Dim iRotation As Integer = oPdfReader.GetPageRotation(iPage)
            If (iRotation = 90) Or (iRotation = 270) Then
                oDirectContent.AddTemplate(oPdfImportedPage, 0, -1.0F, 1.0F, 0, 0, oPdfReader.GetPageSizeWithRotation(iPage).Height)
            Else
                oDirectContent.AddTemplate(oPdfImportedPage, 1.0F, 0, 0, 1.0F, 0, 0)
            End If
        Loop
 
    End Sub
 
    Sub AddImage(ByVal sInFilePath As String, ByRef oPdfDoc _
                 As iTextSharp.text.Document, ByVal oPdfWriter As PdfWriter)
        Dim oImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(sInFilePath)
        Dim oDirectContent As iTextSharp.text.pdf.PdfContentByte = oPdfWriter.DirectContent
 
        Dim iWidth As Single = oImage.Width
        Dim iHeight As Single = oImage.Height
 
 
 
        Dim iAspectRatio As Double = iWidth / iHeight
 
        Dim iWidthPage As Single = iTextSharp.text.PageSize.LETTER.Width
        Dim iHeightPage As Single = iTextSharp.text.PageSize.LETTER.Height
        Dim iPageAspectRatio As Double = iWidthPage / iHeightPage
 
        Dim iWidthGoal As Single = 0
        Dim iHeightGoal As Single = 0
 
        If iWidth < iWidthPage And iHeight < iHeightPage Then
            'Image fits within the page
            iWidthGoal = iWidth
            iHeightGoal = iHeight
 
        ElseIf iAspectRatio > iPageAspectRatio Then
            'Width is too big
            iWidthGoal = iWidthPage
            iHeightGoal = iWidthPage * (iHeight / iWidth)
 
        Else
            'Height is too big
            iWidthGoal = iHeightPage * (iWidth / iHeight)
            iHeightGoal = iHeightPage
        End If
 
        oImage.SetAbsolutePosition(1, 1)
        oPdfDoc.SetPageSize(iTextSharp.text.PageSize.LETTER)
 
        oPdfDoc.NewPage()
        oImage.ScaleAbsolute(iWidthGoal, iHeightGoal)
        oDirectContent.AddImage(oImage)
    End Sub
 
 
    Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcess.Click
 
 
        Dim sFromPath As String = txtFrom.Text
        If Not Directory.Exists(sFromPath) Then
            MsgBox("Folder does not exist")
            Exit Sub
        End If
 
        ProccessFolder(sFromPath)
        MessageBox.Show("Proceso terminado, asegurese de que la plicacion ha dado el resultado esperado (y compruebe que no se han borrado ni modificado documentos de por ahi)")
    End Sub




Aviso, el codigo lo que hace es que toma del textbox la ruta de una carpeta en la cual tenemos los pdf que queremos unir. De modo que al pulsar el boton generamos un pdf nuevo con el nombre de dicha carpeta (ej: en la carpeta C:\carpetaDePdf tenemos pdfUno.pdf y pdfDos.pdf, al pulsar el boton se genera carpetaDePdf.pdf[el cual tiene dentro los otros dos]).



Gracias por visitar este sitio.

Nos vemos en el foro
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
Imágen de perfil de xve
Val: 45
Ha disminuido su posición en 7 puestos en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

¡Ayuda! Como unir dos pdf con la libreria itextsharp

Publicado por xve (100 intervenciones) el 08/05/2013 16:14:38
Excelente Carlos!!!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

¡Ayuda! Como unir dos pdf con la libreria itextsharp

Publicado por RakO (1 intervención) el 25/03/2014 23:54:32
Buenas!!

Ante todo, gracias por tu código, estaba buscando cómo unir varios pdfs. Quisiera añadir que hay un pequeño error:

'Dim sOutFilePath As String = sFolderPath + "\"
Dim sOutFilePath As String = sFolderPath + "\" + oFolderInfo.Name + ".pdf"

Hay que comentar la línea que tengo aquí y descomentar la que aparece comentada en tu código, si no, no genera el pdf y no sabe como llamar al nuevo pdf a generar. (Una pamplina)

Gracias de nuevo, me salvaste!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

¡Ayuda! Como unir dos pdf con la libreria itextsharp

Publicado por José Rojo (1 intervención) el 03/06/2015 11:28:57
Hola,

Primero darte las gracias por el aporte.

Sólo quería copiar el código correcto para que compile en VB .Net es el siguiente, puesto que faltaban algunas variables y había referencias a arrays de objetos que deberían hacerse únicamente al item concreto.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
Friend Shared Function Merge(ByVal strFileTarget As String, ByVal arrStrFilesSource() As String) As Boolean
        Dim blnMerged As Boolean = False
        Dim intNumberOfPages As Integer
        Dim intIndexFile As Integer
        Dim integerPage As Integer
        ' Crea el PDF de salida
        Try
            Using stmFile As System.IO.FileStream = New System.IO.FileStream(strFileTarget, System.IO.FileMode.Create)
                Dim objDocument As iTextSharp.text.Document = Nothing
                Dim objWriter As iTextSharp.text.pdf.PdfWriter = Nothing
                ' Recorre los archivos
 
                For intIndexFile = 0 To arrStrFilesSource.Length - 1
                    Dim IntegerIndexFile As Integer
                    Dim objReader(0 To IntegerIndexFile - 1) As iTextSharp.text.pdf.PdfReader
 
                    intNumberOfPages = objReader(IntegerIndexFile - 1).NumberOfPages
                    ' La primera vez, inicializa el documento y el escritor
                    If IntegerIndexFile = 0 Then
                        ' Asigna el documento y el generador
 
                        ''LINEA ERROR:  objDocument = New Document(objReader.GetPageSizeWithRotation(1))
                        ''vale, el error que me sale es: GetPageSizeWithRotation(1) is not a member of System.Array
                        objDocument = New iTextSharp.text.Document(objReader(intIndexFile).GetPageSizeWithRotation(1))
 
 
                        objWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(objDocument, stmFile)
                        ' Abre el documento
                        objDocument.Open()
 
                    End If
                    ' Añade las páginas
 
                    For integerPage = 0 To intNumberOfPages - 1
 
                        ''LINEA ERROR:  Dim intRotation As Integer = objReader.GetPageRotation(IntegerPage + 1)
                        ''Error: GetPageRotation is not a member of System.Array
                        Dim intRotation As Integer = objReader(integerPage).GetPageRotation(integerPage + 1)
 
                        ''LINEA ERROR:  Dim objPage As PdfImportedPage = objWriter.GetImportedPage(objReader, IntegerPage + 1)
                        ''Error: Value of type '1-dimensional array of iTextSharp.text.pdf.PdfReader' cannot be converted to 'iTextSharp.text.pdf.PdfReader'
                        Dim objPage As iTextSharp.text.pdf.PdfImportedPage = objWriter.GetImportedPage(objReader(integerPage), integerPage + 1)
 
                        ' Asigna el tamaño de la página
 
                        ''LINEA ERROR:  objDocument.SetPageSize(objReader.GetPageSizeWithRotation(IntegerPage + 1))
                        ''Error: GetPageSizeWithRotation(1) is not a member of System.Array
                        objDocument.SetPageSize(objReader(integerPage).GetPageSizeWithRotation(integerPage + 1))
 
                        ' Crea una nueva página
                        objDocument.NewPage()
                        ' Añade la página leída
                        Dim IntegerRotation As Integer
                        If IntegerRotation = 90 OrElse IntegerRotation = 270 Then
 
                            ''LINEA ERROR:  esta de abajo tan sumuamente larga
                            ''Error: GetPageSizeWithRotation(1) is not a member of System.Array
                            objWriter.DirectContent.AddTemplate(objPage, 0, -1.0F, 1.0F, 0, 0, objReader(integerPage).GetPageSizeWithRotation(integerPage + 1).Height)
 
                        Else
                            objWriter.DirectContent.AddTemplate(objPage, 1.0F, 0, 0, 1.0F, 0, 0)
 
                        End If
 
                    Next
                    ' Cierra el documento
                    If objDocument IsNot Nothing Then
                        objDocument.Close()
                    End If
                    ' Cierra el stream del archivo
                    stmFile.Close()
 
                Next
                ' Indica que se ha creado el documento
                blnMerged = True
 
            End Using
        Catch objException As Exception
            System.Diagnostics.Debug.WriteLine(objException.Message)
 
        End Try
 
        ' Devuelve el valor que indica si se han mezclado los archivos
        Return blnMerged
 
    End Function


Un saludo.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

¡Ayuda! Como unir dos pdf con la libreria itextsharp

Publicado por Juan Carlos Bermudez (1 intervención) el 22/01/2016 17:55:49
Estimado amigo, usas la variable "IntegerIndexFile " sin antes asignarle un valor.
Saludos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar