Home > Net >  Cannot open PDF file in VB.NET
Cannot open PDF file in VB.NET

Time:06-12

The library I'm using is iTextsharp but I don't mind any method that can be used to read all text file into one PDF. Thanks for leaving comments and ideas.

I'm using VB.NET to read all text files in a directory and saving them as PDf using iTextsharp. The code shown here can generate PDF, but it cannot open those files. The system tells me the PDF has been destroyed.

pdf screenshot

Dim path As String = TextBox2.Text
Dim searchPattern As String = "*.txt"
Dim doc As Document = New Document()
doc.Open()

For Each fileName As String In Directory.GetFiles(path, "*.txt")
        Dim sr As StreamReader = New StreamReader(fileName)
        doc.Add(New Paragraph(sr.ReadToEnd()))
Next

doc.Close()

PdfWriter.GetInstance(doc, New FileStream(TextBox2.Text & "\Test.pdf", FileMode.Create))

'Open the Converted PDF File
Process.Start(TextBox2.Text & "\Test.pdf")
MsgBox("Done")

Any ideas? Thanks.

CodePudding user response:

You are opening files all over the place and not closing them. I don't know for sure but that may well be your issue. When you read the files, if you open a StreamReader then close it afterwards:

For Each fileName As String In Directory.GetFiles(path, "*.txt")
    Using sr As New StreamReader(fileName)
        doc.Add(New Paragraph(sr.ReadToEnd()))
    End Using
Next

Better still, don't create the StreamReader yourself:

For Each fileName As String In Directory.GetFiles(path, "*.txt")
    doc.Add(New Paragraph(File.ReadAllText(fileName)))
Next

When you write the file, close the FileStream that you open afterwards:

Using fs As New FileStream(TextBox2.Text & "\Test.pdf", FileMode.Create)
    PdfWriter.GetInstance(doc, fs)
End Using

CodePudding user response:

You have to tie the stream to the document before adding to the document, something like this:

Dim srcDir = "C:\temp"
Dim searchPattern = "*.txt"
Dim destFile = Path.Combine(srcDir, "SO72581578.pdf")

Using fs = New FileStream(destFile, FileMode.Create)
    Dim pdfDoc As New Document(PageSize.A4, 25, 25, 40, 40)

    Using writer = PdfWriter.GetInstance(pdfDoc, fs)
        pdfDoc.Open()

        For Each f In Directory.EnumerateFiles(srcDir, searchPattern)
            pdfDoc.Add(New Paragraph(File.ReadAllText(f)))
        Next

        pdfDoc.Close()

    End Using

End Using
  • Related