Ver Mensaje Individual
  #5 (permalink)  
Antiguo 08/05/2013, 05:49
cbr20
 
Fecha de Ingreso: abril-2013
Mensajes: 37
Antigüedad: 11 años
Puntos: 1
Respuesta: Introducir dos pdf en otro usando itextsahrp

Hola buenas, aqui estoy de nuevo.

Resulta que al fin logre unir dos pdf en uno solo.

Se que en este tema ya añadi codigo, pero ese codigo no nos ayudara (almenos no directamente, ya que como expuse anteriormente, necesitaba un "arreglo").

De modo que les dejare aqui mi nuevo codigo.

Lamento decirles que en esta ocasion utilizaremos un codigo mucho mas largo, pero funciona perfectamente, os lo aseguro.


En general el codigo funciona asi:
- Mediante un boton llamamos al metodo principal de union de pdf
- Este metodo llama a otros dos para rellenar el nuevo pdf con los que queremos unir.


Para usar el codigo necesitamos:
- Un formulario vb.net (ya que usaremos botones etc.)
- Un boton
- Un textbox
- La libreria itextsharp (si no tenemos esto apaga y vamonos)



El codigo de marras(lamento que no este comentado, por cualquier duda preguntadme en el foro)

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]).



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.GetPageSizeWithRota tion(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.LETTE R)

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




Se que es muy largo, pero funciona de maravilla.


Por cualquier duda preguntadme e intentare responderos lo mejor posible.

Nos vemos en el foro, adiooooooooooooooooooos


PD: el codigo original lo pille de este link (solo copie el codigo que semuestra, ni descargue ni nada, solo copie el codigo que venia y lo modifique para hacerlo mas sencillo)


http://www.codeproject.com/Articles/69177/PDF-Merge