Foros del Web » Programación para mayores de 30 ;) » .NET »

[SOLUCIONADO] Introducir dos pdf en otro usando itextsahrp

Estas en el tema de Introducir dos pdf en otro usando itextsahrp en el foro de .NET en Foros del Web. Hola, buenas, soy yo otra vez, el enrrea de turno. En esta ocasion os vengo con una duda interesante (duda a la cual todo el ...
  #1 (permalink)  
Antiguo 07/05/2013, 05:54
 
Fecha de Ingreso: abril-2013
Mensajes: 37
Antigüedad: 11 años
Puntos: 1
Introducir dos pdf en otro usando itextsahrp

Hola, buenas, soy yo otra vez, el enrrea de turno.

En esta ocasion os vengo con una duda interesante (duda a la cual todo el mundo responde de la misma manera ("Usa la libreria itextsharp") y en vez de poner el codigo en vb.net lo ponen en C++ o cualquier otro).

La duda: usando la maravillosa libreria itextsahrp, como puedo introducir dos pdf en otro (cada pdf es de SOLO una pagina), o como puedo unirlos, o como puedo meter dos tiff en un pdf...... en resumen, pillar dos imagenes (pdf o tif me da igual) y tener al fin un pdf con dichas imagenes.

Si alguien sabe la respuesta se lo agradeceria.

Y por favor, que no tenga que ser yo otra vez el que responda a mis propias preguntas, despues de todo soy el que pregunta.

Y agradeceria que añadiesen codigo a la explicacion (a ser posible en VB.NET, ni C#, ni ASP.NET, ni visual basic ni gaitas, EN VB.NET.) Gracias por su aportacion.

Para cualquier duda contacten conmigo en este tema del foro.
  #2 (permalink)  
Antiguo 07/05/2013, 11:03
Avatar de drako_darpan  
Fecha de Ingreso: octubre-2008
Ubicación: Sinaloa
Mensajes: 617
Antigüedad: 15 años, 6 meses
Puntos: 58
Respuesta: Introducir dos pdf en otro usando itextsahrp

Hola que tal, bueno hace tiempo ( desde el 2011 ) hice la misma pregunta jejejeje

Revisa este link:

http://www.forosdelweb.com/f29/abrir...tsharp-962089/

Ami me sirvio a las mil maravillas y es el metodo que mas uso



Una cosa, en el modo de pedir esta el dar, siento un poco como agresiva la petición, sera que estoy algo estresado por tanto trabajo jejejeje , trata de no hacer tan agresivas las preguntas, fuera de eso estamos para ayudarnos

Lo digo por esta linea:

Cita:
Y por favor, que no tenga que ser yo otra vez el que responda a mis propias preguntas, despues de todo soy el que pregunta
  #3 (permalink)  
Antiguo 08/05/2013, 01:53
 
Fecha de Ingreso: abril-2013
Mensajes: 37
Antigüedad: 11 años
Puntos: 1
Respuesta: Introducir dos pdf en otro usando itextsahrp

Dos mil millones de gracias por el consejo. Lamento que suene suene asi, pero soy nuevo en esto de los foros y no se usar el sarcasmo web, jaja.
Ahorita mismo miro el link.

En serio, gracias. De todas maneras hare como siempre, podre aqui mi codigo modificado y comentado para que todo el mundo pueda beneficiarse de el (que para eso estamos en un foro, ¿no?).

Si cualquiera quisiese aportar algo mas (se aceptan criticas del codigo y sugerencias varias) dejare este tema como no resuelto una semana mas.

Gracias a todos por entrar en este tema y por sus aportaciones.

Nos vemos en el foro.
  #4 (permalink)  
Antiguo 08/05/2013, 03:21
 
Fecha de Ingreso: abril-2013
Mensajes: 37
Antigüedad: 11 años
Puntos: 1
Respuesta: Introducir dos pdf en otro usando itextsahrp

Hola de nuevo. Utilice el enlace que me enviaste, pero esta en C#.


He traducido a vb.net pero me da error en un metodo que al parecer no exsiste, y hay discrepancia de tipos etc.

Aqui les dejo el codigo de C# haver si alguien me lo puede traducir a vb.net, yo lo intente, pero algo falla por que me da error.


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.GetPageSizeWithR otation(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.Me ssage);
}
// Devuelve el valor que indica si se han mezclado los archivos
return blnMerged;
}



Este codigo se consiguio gracias a la aportacion de drako_darpan, el enlace esta en la respuesta de arriba (una vez en el enlace id al segundo enlace, el que dice que une dos pdf) y al final llegais a este link:
http://www.elguille.info/NET/WebServices/deCSaVB_web.aspx

en el cual esta este codigo de C#. En fin, que lo traduje con un programa pero algo no se traudjo bien o algo falla en el metodo.

Asi que aqui les dejo mi traduccion comentada en las lineas que dan error y que error dan.




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.GetPageSizeWithR otation(IntegerPage + 1))
''Error: GetPageSizeWithRotation(1) is not a member of System.Array
objDocument.SetPageSize(objReader.GetPageSizeWithR otation(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.Me ssage)

End Try

' Devuelve el valor que indica si se han mezclado los archivos
Return blnMerged



End Function




Bueno, espero que os sirvan estos codigos.

Repito, agradeceria cualquier ayuda con las lineas de error, por si estan mal traducidas, si se dev¡ben poner de otra manera, si hay que usar otra forma de hacerlas ....... Cualquier aportacion sera bienvenida.

Gracias por ayudar
  #5 (permalink)  
Antiguo 08/05/2013, 05:49
 
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

Etiquetas: basic, introducir, net, pdf, usando, vb, visual
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:23.