Carlos Anez Carlos Anez - 1 year ago 497 Question

delete pdf file after merging using iTextSharp

I'm merging two pdf into one i'm using a function that I found here

Private Sub MergePdfFiles(ByVal pdfFiles() As String, ByVal outputPath As String)
Dim pdfCount As Integer = 0
Dim f As Integer = 0
Dim fileName As String
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim pageCount As Integer = 0
Dim pdfDoc As iTextSharp.text.Document = Nothing
Dim writer As PdfWriter = Nothing
Dim cb As PdfContentByte = Nothing

Dim page As PdfImportedPage = Nothing
Dim rotation As Integer = 0

pdfCount = pdfFiles.Length
If pdfCount > 1 Then
fileName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fileName)
pageCount = reader.NumberOfPages
pdfDoc = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18)
writer = PdfWriter.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))
With pdfDoc
End With
cb = writer.DirectContent
While f < pdfCount
Dim i As Integer = 0
While i < pageCount
i += 1
page = writer.GetImportedPage(reader, i)
rotation = reader.GetPageRotation(i)
If rotation = 90 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height)
ElseIf rotation = 270 Then
cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30)
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
End While
f += 1
If f < pdfCount Then
fileName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fileName)
pageCount = reader.NumberOfPages
End If
End While
End If
Catch ex As Exception
End Try
End Sub

Now I need to delete the old files "pdfFiles()" but I'm getting the error "The process cannot access the file 'C:.......pdf' because it is being used by another process." this is only happening with the first file, I have no problem with the other one

OP Here with the function


Answer Source

I know this is in C# but this is what i use to merge files together.

var document = new Document();
var outFile = Path.Combine(finishedFilePath, fileName + ".pdf");
var writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
    foreach (var fileName in filesList)
         var reader = new PdfReader(Path.Combine(StartPath, fileName));

         for (var i = 1; i <= reader.NumberOfPages; i++)
             var page = writer.GetImportedPage(reader, i);


catch (Exception ex)
    //catch error             

Hope this helps in some way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download