Ver Mensaje Individual
  #3 (permalink)  
Antiguo 10/05/2013, 10:59
cbr20
 
Fecha de Ingreso: abril-2013
Mensajes: 37
Antigüedad: 11 años
Puntos: 1
Respuesta: Como borrar dos pdf en tiempo de ejecucion

Ahi esta el probelma. Yo ya borro los pdf, pero para ello tengo que cerrar la aplicacion y volver a encenderla, por que si no me dice que los documentos estan siendo utilizados en otro lugar.

El problema es que yo ya me asegure de que la accion de borrado se ejecutase una vez existiesen los dos pdf originales y el nuevo (vamos, que hasta que no esten los 3 pdf creados y mascados no puedo ni borroar ni na).

Y esa es mi duda. Les paso algo de codigo para que vean como realizo esa union de pdf, y asi puedan ayudarme con este dilema.

Como curiosidad: estoy usando vb.net, no C#, ya se que son "parecidos", pero existen grandes diferencias internas (no es uq ecambie el codigo y ya esta, es que un lenguaje no tiene los metodos que hay en otro y viceversa).

Pero tienes razon, con ese codigo que has puesto se borra el archivo (habiendolo traducido previamente a vb.net: My.Computer.FileSystem.DeleteFile(rutaCarpeta)).

De todos modos gracias.

Aqui les dejo el codigo de union de pdf (que ya mostre en un tema anterior) para ver que puede estar fallando (donde podria el metodo seguir utilizando los pdf originales de modo que mientras no se apague o reinicie la aplicacion no puedo borrar los pdf por que los estan "usando").


El codigo:






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)
Dim bOutputfileAlreadyExists As Boolean = False
Dim oFolderInfo As New System.IO.DirectoryInfo(sFolderPath)
'Dim sOutFilePath As String = sFolderPath + "\PdfFinalAbsoluto.pdf"
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
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


Public Sub btnProcess(ByVal sFromPath)

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 aplicacion ha dado el resultado esperado (y compruebe que no se han borrado ni modificado documentos de por ahi)")
End Sub


Este codigo toma la ruta de una carpeta y une todos los pdf que hay en ella en un nuevo pdf.



Tras generarse este nuevo pdf (y dejar de usar los otros dos) le doy a este boton, que llama a la funcion de borrar:



'------BOTON Borrar------
Private Sub btnBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBorrar.Click
Dim rutaCarpeta1 As String = "C:\carpetaPdf\pdfUno.pdf"
Dim rutaCarpeta2 As String = "C:\carpetaPdf\pdfDos.pdf"


'Si existen los pdf entonces podremos borrarlos
If (System.IO.File.Exists(rutaCarpeta1)) Then
borrarPdf(rutaCarpeta1)
End If
If (System.IO.File.Exists(rutaCarpeta2)) Then
borrarPdf(rutaCarpeta2)
End If
End Sub

'------Metodo borrar------
Private Sub borrarDniPartido(ByVal rutaCarpeta)

My.Computer.FileSystem.DeleteFile(rutaCarpeta) 'esta es la linea que da error
MessageBox.Show("El archivo fue borrado")

End Sub


Como pueden ver no realizo la operacion de borrado hasta que los archivos existen.

Entonces, quien esta usando los pdf???


Gracias por su ayuda.