Adding headers with iTextSharp in VB.NET - vb.net

I'm wondering how can I put a header into my PDF file, cause I've tried the tutorials from here:
http://itextsharp.sourceforge.net/tutorial/ch04.html
And it has not worked.
I've done this:
Dim head As New HeaderFooter(New Phrase("This is page: "), False)
head.Border = Rectangle.NO_BORDER
document.Header = head
But VS2008 says that HeaderFooter is not defined (line 1), and Footer it's not a member of "iTextSharp.text.document" (line 3).
I've already included the imports at the beginning of my code and iIdon't have any other problems with the iTextsharps (I mean that it is working apart of the header problem):
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.Data.SQLite
Imports System.IO
So please, can anyone explain to me how can i set a header for my pages?
Regards

The answer to this question depends on which version of the iTextSharp dll you are using.
If you are using a version lower than 5, this should work
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Module Module1
Sub Main()
Dim pdfWrite As PdfWriter
Dim pdfDoc As New Document()
Dim pdfMemoryStream As New IO.FileStream("tryme.pdf", IO.FileMode.Create)
pdfWrite = PdfWriter.GetInstance(pdfDoc, pdfMemoryStream)
Dim pdfHeader As New HeaderFooter(New Phrase("Im at the head: "), False)
pdfHeader.Border = Rectangle.NO_BORDER
pdfDoc.Header = pdfHeader
pdfDoc.Open()
pdfDoc.Add(New Paragraph("Hello World"))
pdfDoc.NewPage()
pdfDoc.Add(New Paragraph("Hello World Again"))
pdfDoc.Close()
End Sub
End Module
Update
For version 5+ of iTextSharp the HeaderFooter property has been removed from iTextSharp. To add Headers/Footers now you must use PageEvents. The following code demonstrates how to do this (very simply!)
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports System.IO
Module Module1
Sub Main()
Dim pdfDoc As New Document()
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("tryme2.pdf", FileMode.Create))
Dim ev As New itsEvents
pdfWrite.PageEvent = ev
pdfDoc.Open()
pdfDoc.Add(New Paragraph("Hello World"))
pdfDoc.NewPage()
pdfDoc.Add(New Paragraph("Hello World Again"))
pdfDoc.Close()
End Sub
End Module
Public Class itsEvents
Inherits PdfPageEventHelper
Public Overrides Sub OnStartPage(ByVal writer As iTextSharp.text.pdf.PdfWriter, ByVal document As iTextSharp.text.Document)
Dim ch As New Chunk("This is my Stack Overflow Header on page " & writer.PageNumber)
document.Add(ch)
End Sub
End Class

Related

How can i display Vietnamese characters in a .pdf document using itextsharp?

I have read a number of threads that discuss this and none have come up with a solution for this problem. Most of them revolve around using a suitable font. I have tried every single one of them with no success. I know this string is UTF-8 and Vietnamese because if i paste it into Notepad++ as an ASCII string and then change encoding to UTF-8 it works.
The input string looks like this;
"Có sẵn dịch vụ thông dịch miễn phí khi bạn yêu cầu."
The output string should look like this;
"Có sẵn dịch vụ thông dịch miễn phí khi bạn yêu cầu."
My code just produces the first string.
Any help is greatly appreciated. I am tearing my hair out here
Here is my code;
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO
Imports System.Text
Imports System.Collections.Generic
Module TextToPdf
Dim pdfWrite As PdfWriter
Dim pdfDoc As Document
Dim pdfFont As Font
Sub Main()
pdfDoc = New Document(PageSize.LETTER)
pdfFont = New Font(BaseFont.CreateFont(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "vuArial.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 15)
pdfWrite = PdfWriter.GetInstance(pdfDoc, New FileStream("../tmp/vietnamese.pdf", FileMode.Create))
pdfDoc.Open()
pdfDoc.Add(New Paragraph("Có sẵn dịch vụ thông dịch miễn phí khi bạn yêu cầu.", pdfFont))
pdfDoc.Close()
End Sub
End Module
You could probably just save your source code as UTF-8 and paste in the "output" (UTF-8) string, but assuming the source code is ANSI encoding, maybe you can convert it to UTF-8 manually:
Dim ansi = Encoding.Default.GetBytes("Có sẵn dịch vụ thông dịch miễn phí khi bạn yêu cầu.")
Dim utf8 = Encoding.UTF8.GetString(ansi)
pdfDoc.Add(New Paragraph(utf8, pdfFont))

Acrofields Autofilled with iTextSharp in vb.net Not Visible Until Clicked

I'm working on a vb.net app to fill preexisting pdf forms and I've run in to a frustrating problem. The code below puts the values into the given fields on the pdf form, but in order to see those values in Adobe Reader, the fields themselves have to be selected. I can't share the pdf itself, but from opening it in Acrobat, it seems like security/protection isn't the issue, though I do get a permissions error when I set FormFlattening to True.
Is there a step in the code below which I'm missing?
Imports System
Imports System.IO
Imports System.Xml
Imports iTextSharp
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.xml
Imports iTextSharp.pdfa
Imports System.Security
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pdfTemp As String = "C:\ExampleTemplate.pdf"
Dim newFile As String = "C:\NewFile.Pdf"
Dim pdfReader As New PdfReader(pdfTemp)
Dim pdfStamper As New PdfStamper(pdfReader, New FileStream(newFile,_ FileMode.Create), "\6c", True)
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
pdfFormFields.SetField("Date", "03092014", "03092014")
pdfFormFields.SetField("Contract_No", "1234456", "1234456")
pdfFormFields.SetField("Buyer", "bar, foo", "bar, foo")
pdfFormFields.GenerateAppearances = True
pdfStamper.FormFlattening = True
pdfStamper.Close()
pdfReader.Close()
End Sub
End Class
So it's not 100% clear to me why this worked and my previous efforts didn't, but copying and pasting this code to initialize the PdfStamper
Dim pdfTemplate As String = "Path to fillable pdf"
Dim strFolder As String = "Path to destination Folder"
Dim newFile As String = strFolder & "Name of Completed Form"
Dim pdfReader As New PdfReader(pdfTemplate)
Dim pdfStamper As New PdfStamper(pdfReader, New FileStream(newFile, FileMode.Create))
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
`fields and values as in original question'
pdfStamper.FormFlattening = True
pdfStamper.Close()
from the tutorial here made the project work.
On a side note, it became clear to me that not all .pdf files with fillable fields are "forms", and that itextsharp requires that the file be a form. I realized this when, after applying the above code to two files successfully, the third failed, despite me knowing the names of the fields. To make it into a form, and thus recognizable to itextsharp, I opened it in acrobat and created a form. All the fields and their names were preserved so I saved it and it worked like a charm.

How to get R.Net work with VB.Net

I am trying to get R.Net work with VB.NET. I translated an official example from c# to vb.net but it is not working. There are different things I tried. First I used the SetupHelper as explained on the official page.
Imports System.IO
Namespace RDotNetSetup
Public Class SetupHelper
Public Shared Sub SetupPath()
Dim oldPath = System.Environment.GetEnvironmentVariable("PATH")
Dim rPath = If(System.Environment.Is64BitProcess, "C:\Program Files\R\R-3.0.2\bin\x64", "C:\Program Files\R\R-3.0.2\bin\i386")
If Directory.Exists(rPath) = False Then
Throw New DirectoryNotFoundException(String.Format("Could not found the specified path to the directory containing R.dll: {0}", rPath))
End If
Dim newPath = String.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, oldPath)
System.Environment.SetEnvironmentVariable("PATH", newPath)
End Sub
End Class
End Namespace
and
Imports RDotNet
Imports ConsoleApplication36.RDotNetSetup
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Module Module1
Sub Main()
SetupHelper.SetupPath()
Using engine As REngine = REngine.CreateInstance("RDotNet")
engine.Initialize()
Dim charVec As CharacterVector = engine.CreateCharacterVector({"Hello, R world!, .NET speaking"})
engine.SetSymbol("greetings", charVec)
engine.Evaluate("str(greetings)")
Dim a As String() = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray()
Console.WriteLine("R answered: '{0}'", a(0))
Console.WriteLine("Press any key to exit the program")
Console.ReadKey()
End Using
End Sub
End Module
I dont get an error, using the debugger at engine.Initialize my test stops running ( the green Start arrow reappears).
So I found another example that should (apparentely) works on VB.Net
Imports RDotNet
Imports System.IO
Imports System.Linq
Module Module1
Sub Main()
Dim envPath = System.Environment.GetEnvironmentVariable("PATH")
Dim rBinPath = "C:\Program Files\R\R-3.0.2\bin\i386"
System.Environment.SetEnvironmentVariable("PATH", envPath & Path.PathSeparator & rBinPath)
Dim engine As REngine = REngine.CreateInstance("RDotNet")
Dim group1 As NumericVector = engine.CreateNumericVector(New Double() {30.02, 29.99, 30.11, 29.97, 30.01, 29.99})
engine.SetSymbol("group1", group1)
' Direct parsing from R script.
Dim s = "group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)"
Dim group2 = engine.Evaluate(s).AsNumeric()
Dim testResult As GenericVector = engine.Evaluate("t.test(group1, group2)").AsList()
Dim p As Double = testResult("p.value").AsNumeric().First()
Console.WriteLine("Group1: [{0}]", String.Join(", ", group1))
Console.WriteLine("Group2: [{0}]", String.Join(", ", group2))
Console.WriteLine("P-value = {0:0.000}", p)
End Sub
End Module
Looks like the writer had the same problem and just left the engine.initialize. If I execute the code I get the error: "Value out of range" at Dim group1 As NumericVector = engine.CreateNumericVector(New Double() {30.02, 29.99, 30.11, 29.97, 30.01, 29.99}).
Anyone who could help me get a sample code for VB.NET to work? And explain me why i cannot initialize.
fyi: I checked the path and set all needed references.
Ok, hours of trying and discussion later it works. What I did:
I changed .net 4.5 to .net 4.0
I changed compiler settings from "AnyCPU" to "x86"
First line in the 'SetupPath()' is: System.Environment.SetEnvironmentVariable("R_HOME", "C:\Program Files\R\R-3.0.2")

InvalidOperationException when trying to add XElement to XDocument

I'm getting this error when I try to add a XElement to a XDocument:
An exception of type 'System.InvalidOperationException' occurred in
System.Xml.Linq.ni.dll but was not handled in user code
My code is:
Imports System.Xml
Imports System.Xml.Linq
Imports System.IO.IsolatedStorage
Imports System.IO
Public Sub SaveRecord()
Using myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim doc As XDocument
Using isoStore1 As IsolatedStorageFile = _
IsolatedStorageFile.GetUserStoreForApplication()
Using isoStream1 As IsolatedStorageFileStream = New IsolatedStorageFileStream("file.xml", FileMode.Open, isoStore1)
doc = XDocument.Load(isoStream1)
MessageBox.Show(doc.ToString)
'This gives the right xml-code
doc.Add(New XElement("NewChild", "new content")) 'This is where the error takes place
MessageBox.Show(doc.ToString)
Using isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Using isoStream As IsolatedStorageFileStream = New IsolatedStorageFileStream("file.xml", FileMode.Create, isoStore)
doc.Save(isoStream)
End Using
End Using
End Using
End Using
End Using
Exit Sub
End Sub
The error shows up when the debugger enters the line doc.Add(New XElement("NewChild", "new content"))
Can anyone explain to me what the cause of this error is and how I can solve it?
You need to add your XElement to your XDocuments root.
doc.Root.Add(New XElement("NewChild", "new content"))
Adding it directly to the doc will make your xml invalid as it will be having two roots because you are adding the XElement after your XDocument instead of to the root.

itextsharp: how do i set the background color of the document?

in vb.net please if possible
You can create a Rectangle object and set its BackgroundColor property. Use your Rectangle to initialize your Document.
This tutorial on the iTextSharp site on SourceForge describes this (see the PageSize section).
The same site has a code sample that demonstrates what you need to do. (see 'step 1'). The sample is in C# and I know you want it in VB.NET so I ran it through the C# to VB.NET converter on the developerfusion site. I can't test compile the results from the machine I'm not now, but the code looks reasonable:
Imports System
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Public Class Chap0102
Public Shared Sub Main()
Console.WriteLine("Chapter 1 example 2: PageSize")
' step 1: creation of a document-object
Dim pageSize As New Rectangle(144, 720)
pageSize.BackgroundColor = New Color(&Hff, &Hff, &Hde)
Dim document As New Document(pageSize)
Try
' step 2:
' we create a writer that listens to the document
' and directs a PDF-stream to a file
PdfWriter.getInstance(document, New FileStream("Chap0102.pdf", FileMode.Create))
' step 3: we open the document
document.Open()
' step 4: we Add some paragraphs to the document
For i As Integer = 0 To 4
document.Add(New Paragraph("Hello World"))
Next
Catch de As DocumentException
Console.[Error].WriteLine(de.Message)
Catch ioe As IOException
Console.[Error].WriteLine(ioe.Message)
End Try
' step 5: we close the document
document.Close()
End Sub
End Class
Give it a try.
color does not exist in namespace and the error is in your code:
pageSize.BackgroundColor = New **Color**(&Hff, &Hff, &Hde)