Jonathan Small
Jonathan Small

Reputation: 1089

iTextSharp creates a damaged .pdf file

I am writing a "combine" .pdf file application. The .pdf file that I generate with the code below results in a .pdf file that can not be opened by Adobe. This is the code I am executing:

 Dim doc_fs = CreateObject("Scripting.FileSystemObject")
 Dim document_path = "C:\pdffilesfolder\"
 Dim document_folder = doc_fs.GetFolder(document_path)

 Dim dateArray() As String
 dateArray = lblDateToPrint.Text.Split("/")   'lblDateToPrint.Text contains "3/21/2017"
 If Val(dateArray(0)) < 10 Then
    dateArray(0) = "0" & dateArray(0)
 End If
 If Val(dateArray(1)) < 10 Then
    dateArray(1) = "0" & dateArray(1)
 End If

 Dim outFile as string = document_path & "\confirms_" & dateArray(2) & "_" & dateArray(0) & "_" & dateArray(1) & ".pdf"     
 Dim document = New Document
 Dim writer As PdfCopy = New PdfCopy(document, New FileStream(outFile, FileMode.Create))
 document.Open()


 Dim fileOnServer As String = ""
 Dim fileOnServerDate As String = ""

 For Each item In document_folder.Files
      fileOnServer = item.path
      Dim reader As PdfReader = New PdfReader(fileOnServer)
      writer.AddDocument(reader)
      reader.Close()
 Next

I have attached the 2 .pdf files that I am using as input as well as the resulting .pdf file (even through Adobe says it can not be opened).

Any assistance is greatly appreciated.

Thank you, Jonathan

Upvotes: 0

Views: 965

Answers (1)

mkl
mkl

Reputation: 96029

You forgot to eventually close the Document document:

Dim document = New Document
Dim writer As PdfCopy = New PdfCopy(document, New FileStream(outFile, FileMode.Create))
document.Open()

Dim fileOnServer As String = ""
Dim fileOnServerDate As String = ""

For Each item In document_folder.Files
    fileOnServer = item.path
    Dim reader As PdfReader = New PdfReader(fileOnServer)
    writer.AddDocument(reader)
    reader.Close()
Next

document.Close() ' Don't forget to close the document!

Upvotes: 2

Related Questions