Itextsharp Error using RegenerateField : Field Name can't contain a '#' - vb.net

How do I hide a button in a PDF? When I try the code below I get an error that says the Field Name can't contain a '#'. The error occurs on the line that uses RegenerateField.
The field name is "form1[0].#pageSet[0].Page1[0].PrintButton1[0]"
Thanks in advance.
Using outStream As New MemoryStream
Dim pdfReader As New PdfReader(pdfBinaryFile)
Dim stamper As New PdfStamper(pdfReader, outStream)
Dim form As AcroFields = stamper.AcroFields
stamper.AddViewerPreference(PdfName.HIDETOOLBAR, New PdfBoolean(True))
stamper.AddViewerPreference(PdfName.FITWINDOW, New PdfBoolean(True))
stamper.FormFlattening = False
Dim keyStringPrintButton As String = stamper.AcroFields.Fields.First(Function(item) item.Key.ToString().ToUpper().Contains("PRINT")).Key.ToString()
Dim keyValuePrintButton As AcroFields.Item = stamper.AcroFields.Fields.First(Function(item) item.Key.ToString().ToUpper().Contains("PRINT")).Value
Dim dictionaryEntryPrintButton As Dictionary(Of String, AcroFields.Item)
dictionaryEntryPrintButton = New Dictionary(Of String, AcroFields.Item)
dictionaryEntryPrintButton.Add(keyStringPrintButton, keyValuePrintButton)
form.SetFieldProperty(dictionaryEntryPrintButton.Keys(0), "setfflags", PdfFormField.FLAGS_HIDDEN, Nothing)
form.RegenerateField(dictionaryEntryPrintButton.Keys(0))
stamper.Close()
pdfReader.Close()
End Using

I found the answer. The SetFieldProperty command was using PdfFormField.FLAGS_HIDDEN and it should be using PDfAnnotation and "setflags' instead.
So
form.SetFieldProperty(dictionaryEntryPrintButton.Keys(0), "setfflags", PdfFormField.FLAGS_HIDDEN, Nothing)
Becomes
form.SetFieldProperty(dictionaryEntryPrintButton.Keys(0), "setflags", PdfAnnotation.FLAGS_HIDDEN, Nothing)
And I don't need the RegenerateField command.

Related

I have to get a pdf mainstream using itexsharp after have add a password

I am writing code for add a password in a pdf (I have an array of byte, not a file in a dir) but i have problem with outputStream (I need another array but protect from password): it is 15 bite and not contains the start pdf. I use a itexsharp 5.5 version, is not young but not very old, how is the error?
thi is my code:
Dim PasswordUser As String = ""
Dim UserPassByte = Encoding.Unicode.GetBytes(PasswordUser)
Dim ownerPassword As String = "1"
Dim ownerPassByte = Encoding.Unicode.GetBytes(ownerPassword)
Dim reader As New PdfReader("c:\tmp\pdfx.pdf")
Dim array As Byte()
Using outputStream As New MemoryStream
Dim PdfStamper As New PdfStamper(reader, outputStream)
PdfStamper.SetEncryption(UserPassByte, ownerPassByte, PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128)
PdfStamper.FormFlattening = True
array = outputStream.ToArray()
End Using

iText 7 .NET - 'System.NullReferenceException' when flattening a form

In order to duplicate a form in a PDF, I'm doing the following (used this code as reference):
Dim pdfDocumentR As PdfDocument
Dim writer As PdfWriter = New PdfWriter(DEST)
writer.SetSmartMode(True)
Dim pdfDocumentW As New PdfDocument(writer)
Dim tmp As ByteArrayOutputStream
Dim form As PdfAcroForm
Dim fields As IDictionary(Of String, PdfFormField)
Dim tf As PdfFormField
For Each documento As Documento In documentos
tmp = New ByteArrayOutputStream()
pdfDocumentR = New PdfDocument(New PdfReader(SRC), New PdfWriter(tmp))
form = PdfAcroForm.GetAcroForm(pdfDocumentR, False)
fields = form.GetFormFields()
documento.campos.remove("templateID")
Dim keys As Dictionary(Of String, String).KeyCollection = documento.campos.Keys
For Each key As String In keys
Dim value As String
documento.campos.TryGetValue(key, value)
fields.TryGetValue(key, tf)
tf.SetValue(value)
Next
form.FlattenFields()
pdfDocumentR.Close()
pdfDocumentR = New PdfDocument(New PdfReader(New MemoryStream(tmp.GetBuffer())))
pdfDocumentR.CopyPagesTo(1, pdfDocumentR.GetNumberOfPages(), pdfDocumentW, New PdfPageFormCopier())
pdfDocumentR.Close()
Next
pdfDocumentW.Close()
I'm getting 'System.NullReferenceException' when it tries to flatten the form - form.FlattenFields().
Could someone help me?

Parsing CSV from stream with TextFieldParser always reaches EndOfData

During parsing CSV file as a stream from Azure Blob, TextFieldParser always reaches EndOfData immediately, without any data read. The same code, but with the path to same physical file instead of stream works.
Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(AzureStorageConnection)
Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()
Dim BlobList As IEnumerable(Of CloudBlockBlob) = blobClient.GetContainerReference("containername").ListBlobs().OfType(Of CloudBlockBlob)
For Each blb In BlobList
Dim myList As New List(Of MyBusinessObject)
Using memoryStream = New MemoryStream()
blb.DownloadToStream(memoryStream)
Using Reader As New FileIO.TextFieldParser(memoryStream)
Reader.TextFieldType = FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(2, 9, 10)
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
myList.Add(New GsmXFileRow() With {
' code to read currentRow and add elements to myList
})
Catch ex As FileIO.MalformedLineException
End Try
End While
End Using
End Using
Next
I have also tried to convert MemoryStream to TextReader
Dim myTextReader As TextReader = New StreamReader(memoryStream)
and then passing myTextReader into TextFieldParser, but this does not work either.
Using Reader As New FileIO.TextFieldParser(myTextReader)
I see this:
Value of Length property equals file size
and this:
'Position` property has same value
That means at the start of the loop, the MemoryStream has already advanced to the end of the stream. Just set Position back to 0, and you should be in a better place.
However, there may be another issue here, too. That stream data is binary with some unknown encoding. The TextFieldParser wants to work with Text. You need a way to give the TextFieldParser information about what encoding is used.
In this case, I recommend a StreamReader. This type inherits from TextReader, so you can use it with the TextFieldParser :
Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(AzureStorageConnection)
Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()
Dim BlobList As IEnumerable(Of CloudBlockBlob) = blobClient.GetContainerReference("containername").ListBlobs().OfType(Of CloudBlockBlob)
Dim myList As New List(Of MyBusinessObject)
For Each blb In BlobList
'Several constructor overloads allow you to specify the encoding here
Using blobData As New StreamReader(New MemoryStream())
blb.DownloadToStream(blobData.Stream)
'Fix the position problem
blobData.Stream.Position = 0
Using Reader As New FileIO.TextFieldParser(blogData)
Reader.TextFieldType = FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(2, 9, 10)
Dim currentRow As String() = Reader.ReadFields()
While Not Reader.EndOfData
Try
myList.Add(New GsmXFileRow() With {
' code to read currentRow and add elements to myList
})
currentRow = Reader.ReadFields()
Catch ex As FileIO.MalformedLineException
End Try
End While
End Using
End Using
Next

Add Image And Text To Existing .pdf Using iText in VB.net

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()

How do I reload the formatted text into RTB?

I have a RTB in VB.NET, and put an event handler to save the formatted text into a file after encrypting it. However, I can't figure out how to reload the formatting - when I open it, it shows the symbols of formatting instead of formatted text. Here's my code:
Dim FileName As String = TextBox1.Text
File.Delete(FileName)
Dim EncryptElement As New TripleDESCryptoServiceProvider
EncryptElement.Key = {AscW("B"c), AscW("A"c), AscW("1"c), AscW("R"c), AscW("3"c), AscW("9"c), AscW("G"c), AscW("V"c), AscW("5"c), AscW("S"c), AscW("P"c), AscW("0"c), AscW("L"c), AscW("Z"c), AscW("4"c), AscW("M"c)} '128 bit Key
EncryptElement.IV = {AscW("N"c), AscW("B"c), AscW("5"c), AscW("3"c), AscW("G"c), AscW("L"c), AscW("2"c), AscW("Q"c)} ' 64 bit Initialization Vector
Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
Dim cStream As New CryptoStream(fStream, New TripleDESCryptoServiceProvider().CreateEncryptor(EncryptElement.Key, EncryptElement.IV), CryptoStreamMode.Write)
Dim sWriter As New StreamWriter(cStream)
sWriter.WriteLine(RichTextBox1.Rtf)
sWriter.Close()
cStream.Close()
fStream.Close()
The above code is for saving, and the below code is for opening.
Dim FileName As String = TextBox1.Text
Dim DecryptElement As New TripleDESCryptoServiceProvider
DecryptElement.Key = {AscW("B"c), AscW("A"c), AscW("1"c), AscW("R"c), AscW("3"c), AscW("9"c), AscW("G"c), AscW("V"c), AscW("5"c), AscW("S"c), AscW("P"c), AscW("0"c), AscW("L"c), AscW("Z"c), AscW("4"c), AscW("M"c)}
DecryptElement.IV = {AscW("N"c), AscW("B"c), AscW("5"c), AscW("3"c), AscW("G"c), AscW("L"c), AscW("2"c), AscW("Q"c)}
Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
Dim cStream As New CryptoStream(fStream, New TripleDESCryptoServiceProvider().CreateDecryptor(DecryptElement.Key, DecryptElement.IV), CryptoStreamMode.Read)
Dim sReader As New StreamReader(cStream)
Dim DecryptedData As String = ""
DecryptedData = sReader.ReadToEnd
RichTextBox1.AppendText(DecryptedData)
RichTextBox1.Enabled = True
Button1.Text = "OK"
sReader.Close()
cStream.Close()
fStream.Close()
Where is the problem?
You need RichTextBox1.SaveFile(SomeStream, RichTextBoxStreamType) I think StreamWriter is stuffing it up.
Oh and seeing as you just gave the world the keys for your encryption you might want to come up with a new one...
Added after comment not proven though.
Replace these two lines in your save routine
Dim sWriter As New StreamWriter(cStream)
sWriter.WriteLine(RichTextBox1.Rtf)
with
RichTextBox1.SaveFile(cStream,RichTextBoxStreamType.RichText);
and get rid of swriter.Close()
I think.