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.
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
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
Related
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
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!
i just want to ask how can i add a password on a existing PDF file, i just created a pdf file using crystal reports and i kinda need to add some security features for the report. Thank you very much in advance.
lets say the file "c:\Folder1\sample.pdf" already exist. i have seen codes like the one below, but i don't know if it works because i don't know what to add in my reference to make it work
' Define input and output files path.
Dim intputFilePath As String = Program.RootPath + "\\" + "1.pdf"
Dim outputFilePath As String = Program.RootPath + "\\" + "1_with_pw.pdf"
' Set passwords for user and owner.
Dim userPassword As String = "you"
Dim ownerPassword As String = "me"
' Create password setting.
Dim setting As PasswordSetting = New PasswordSetting(userPassword, ownerPassword)
' Add password to plain PDF file and output a new file.
Dim errorCode As Integer = PDFDocument.AddPassword(intputFilePath, outputFilePath, setting)
If errorCode = 0 Then
Console.WriteLine("Success")
Else
Console.WriteLine("Failed")
End If
Dim WorkingFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim InputFile As String = Path.Combine(WorkingFolder, "PSNOs.pdf")
Dim OutputFile As String = Path.Combine(WorkingFolder, "PSNOs_enc.pdf")
Using input As Stream = New FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read)
Using output As Stream = New FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)
Dim reader As New PdfReader(input)
PdfEncryptor.Encrypt(reader, output, True, Nothing, "secret", PdfWriter.ALLOW_SCREENREADERS)
End Using
End Using
the word "PdfReader" have an error message but it doesn't ask to import something..
I've got the below code on a button click which work great. It adds an image to each existing .pdf and then combines several of the new .pdf's together and creates one .pdf. Again, this part of it works great.
The problem I'm having is now I want to keep the existing code but add some text to each page at the same point in the code where the image gets added. I've read a bunch of examples on how to add text to an existing .pdf but due to my inexperience in the area I cant figure out how to make any of the examples work with my existing code. Using VB.net.
I want to add a simple line of text "Example Of text" and position it on the page (300, 300).
Any help would greatly appreciated.
Dim tempFilename = IO.Path.GetTempFileName()
Dim tempFile As New IO.FileStream(tempFilename, IO.FileMode.Create)
' Set up iTextSharp document to hold merged PDF
Dim mergedDocument As New iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER)
Dim copier As New iTextSharp.text.pdf.PdfCopy(mergedDocument, tempFile)
mergedDocument.Open()
Dim pic1 As String = "C:\xxx\xxxx\xxx.png"
Using inputPdfStream As IO.Stream = New IO.FileStream(Server.MapPath(".") + "/xxx.pdf", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Using inputImageStream As IO.Stream = New IO.FileStream(pic1, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Using outputPdfStream As IO.Stream = New IO.FileStream(Server.MapPath(".") + "/xxx2.pdf", IO.FileMode.Create, IO.FileAccess.ReadWrite, IO.FileShare.None)
Dim reader1 = New iTextSharp.text.pdf.PdfReader(inputPdfStream)
Dim stamper = New iTextSharp.text.pdf.PdfStamper(reader1, outputPdfStream)
Dim pdfContentByte = stamper.GetOverContent(1)
Dim image__1 As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(inputImageStream)
image__1.SetAbsolutePosition(527, 710)
image__1.ScaleAbsolute(60, 60)
pdfContentByte.AddImage(image__1)
stamper.Close()
reader1.Close()
outputPdfStream.Close()
inputImageStream.Close()
inputPdfStream.Close()
outputPdfStream.Dispose()
End Using
End Using
End Using
Dim reader As New iTextSharp.text.pdf.PdfReader(New iTextSharp.text.pdf.RandomAccessFileOrArray(Server.MapPath(".") + "/yyy/xxx3".pdf", True), Nothing)
For pageNum = 1 To reader.NumberOfPages
copier.AddPage(copier.GetImportedPage(reader, pageNum))
Next
PTime = PTime + 1
Loop
mergedDocument.Close()
tempFile.Dispose()
After a lot of trial and error I got it to work by adding the following code.
Dim bf As iTextSharp.text.pdf.BaseFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED)
pdfContentByte.SetColorFill(iTextSharp.text.BaseColor.DARK_GRAY)
pdfContentByte.SetFontAndSize(bf, 8)
pdfContentByte.BeginText()
Dim strX As String = "Here"
pdfContentByte.ShowTextAligned(1, strX, 500, 500, 0)
pdfContentByte.EndText()
I cannot write a file in a textfile in my wp7 application, what should I do?
here is my code
Dim isolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication
Dim isoStream As IsolatedStorageFileStream = New IsolatedStorageFileStream("TextFile1.txt", FileMode.Append, isolatedStorage)
Dim streamwriter As StreamWriter = New StreamWriter(isoStream)
streamwriter.WriteLine("sample")
streamwriter.Close()
I also try to put it inside the Using statement, but it is still now writing in the text file
Dim isolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication
Using isoStream As IsolatedStorageFileStream = New IsolatedStorageFileStream("/TextFile1.txt", FileMode.Append, isolatedStorage)
Using streamwriter As StreamWriter = New StreamWriter(isoStream)
streamwriter.WriteLine("PreMenu.xaml")
streamwriter.Close()
End Using
End Using
there is no error, but it is not writing a text in textfile, what should I do?
As the title say i would like to search a text file for a specific word and then start reading the text from that point forth.
A code snippet is the following
Dim path As String = "c:\temp\test.txt"
Dim readall As String
Dim i As Integer
If File.Exists(path) Then
File.Delete(path)
End If
Dim sw As StreamWriter = New StreamWriter(path)
sw.WriteLine("Hello")
sw.WriteLine("i am here")
sw.WriteLine("to test")
sw.WriteLine("the class")
sw.Close()
Dim sr As StreamReader = New StreamReader(path)
readall = sr.ReadToEnd
sr.Close()
So right now i have read the file and stored it to string readall.
How can i write back to the file but now starting from the word "to"
For instance the outpout text file would be
to test
the class
I hope i made myself clear
Search readall for the first occurrence of "to" and store the rest of readall, starting with "to", to the variable stringToWrite:
Dim stringToWrite As String
stringToWrite = readall.Substring(IndexOf("to"))
Then write stringToWrite to file:
Dim sw As StreamWriter = New StreamWriter(path)
sw.write(stringToWrite)
sw.Close()