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.
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.
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