I have a sample pdf, that I am filling out programmatically as such (using iText7):-
string name = TextBox1.Text.ToString();
string pdfTemplate = #"..\WebApplication1\Sample.pdf";
string newFile = #"..\WebApplication1\completed_sample.pdf";
PdfDocument pdf = new PdfDocument(new PdfReader(pdfTemplate).SetUnethicalReading(true), new PdfWriter(newFile));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
IDictionary<String, PdfFormField> fields = form.GetFormFields();
PdfFormField toSet;
// This doesn't work //
fields.TryGetValue("TypeofApplication.1", out toSet);
toSet.SetValue("/On");
// This works //
fields.TryGetValue("FullName", out toSet);
toSet.SetValue(name);
form.FlattenFields();
pdf.Close();
I am able to fill out the text boxes in the pdf, but not to fill out the radio buttons/checkboxes.
Type of Application has two options in my cshtml page:
#Html.RadioButton("Application_Type", "New") New
#Html.RadioButton("Application_Type", "Renew") Renewal
and when I look through my values dictionary, I see that there are 3 options:
TypeofApplication
TypeofApplication.1
TypeofApplication.2
How do I set the checkboxes as checked = true.
My logic is as follow:
if(dr.Application_Type == "New"){
fields.TryGetValue("TypeofApplication.1", out toSet);
toSet.SetValue("/On");}
But this obviously doesn't work.
So the way I figured this out:-
1) I opened the pdf, set the checkbox as checked and saved it in my workspace folder.
2) Then, I programmatically opened the file and inspected the field value as such:-
string pdfTemplate = #"..\WebApplication1\Sample.pdf";
PdfDocument pdf = new PdfDocument(new PdfReader(pdfTemplate).SetUnethicalReading(true), new PdfWriter(newFile));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
IDictionary<String, PdfFormField> fields = form.GetFormFields();
PdfFormField toSet;
fields.TryGetValue("TypeofApplication", out toSet);
var x = toSet.GetValueAsString();
Now, I know the value of x, which is the checked field. (New or Renew). I used this technique to find all values possible for any given checkbox, radiobutton list, et cetera.
Related
I am using This example for the latest Itext7 to fill in a document and I am getting this error: iText.Kernel.Crypto.BadPasswordException: PdfReader is not opened with owner password
So I looked around the net I found that some people found solution to this error using PdfReader.unethicalreading = true; but when I try to use this same code it says there is no definition in PDFReader named unethicalreading
Here is the Code I have:
string src = #"C:\test1.pdf";
string dest = #"C:\Test2.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
IDictionary<String, PdfFormField> fields = form.GetFormFields();
PdfFormField toSet;
fields.TryGetValue("Name", out toSet);
toSet.SetValue("Some text");
You need to change your code like this:
string src = #"C:\test1.pdf";
string dest = #"C:\Test2.pdf";
PdfReader reader = new PdfReader(src);
reader.setUnethicalReading(true);
PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
IDictionary<String, PdfFormField> fields = form.GetFormFields();
PdfFormField toSet;
fields.TryGetValue("Name", out toSet);
toSet.SetValue("Some text");
This will allow you to go against the permissions that were defined by the original author of the document. This also proves that setting such permissions has become obsolete, because since PDF became an ISO standard, there is no longer a penalty for removing those permissions.
I have problems with editing fields inside of an PDF document.
I created a simple invoice with OpenOffice and added some fields via the form creation tool. I exported it as PDF with forms after that.
One of the fields I want to change is named "{Firma}" and I want to fill this field with a string.
Below is a short example-code which doesnt seem to work, the field "{Firma}" in the output-file is still empty.
public static void ReplacePdfForm()
{
string fileNameExisting = #".\template\templaterechnung.pdf";
string fileNameNew = #".\rechnung.pdf";
using (var existingFileStream = new FileStream(fileNameExisting, FileMode.Open))
using (var newFileStream = new FileStream(fileNameNew, FileMode.Create))
{
// Open existing PDF
var pdfTemplate = new PdfReader(existingFileStream);
// PdfStamper, (PDF to be changed)
var pdfInvoice = new PdfStamper(pdfTemplate, newFileStream);
AcroFields fields = pdfInvoice.AcroFields;
// set form fields
fields.SetField("{Firma}", "Test1");
pdfInvoice.FormFlattening = true;
pdfInvoice.FreeTextFlattening = true;
pdfInvoice.Close();
pdfTemplate.Close();
}
}
(I have some more fields which also don't change but I deleted them from code because they behave the same way.)
Thanks in advance.
EDIT:
Here's my PDF: http://www.file-upload.net/download-11071404/templaterechnung.pdf.html
EDIT2:
This is how I set the property in OpenOffice:
When creating a form with Open Office, Open Office adds a parameter to the PDF instructing software processing the PDF not to create any appearance streams, but to leave it up to the PDF viewer to create those appearances.
This works as long as the form remains interactive, but as soon as you flatten the form, no appearances are created at all.
You can work around this problem by adding the following line:
fields.GenerateAppearances = true;
This way, you force iTextSharp to generate the appearances.
I'm trying to add new page to a PdfStamper but this code doesn't add the template pdf fields to the stamper.
private void InsertNewPage(PdfStamper stamper, int pageNumber)
{
var pdfReader = new PdfReader(UrlTemplateBlankPage);
pdfReader.SelectPages("1");
stamper.InsertPage(pageNumber, pdfReader.GetPageSize(1));
stamper.GetOverContent(pageNumber).AddTemplate(stamper.GetImportedPage(pdfReader, 1), 0, 0);
//This code doesn't work because the code before is not adding the form
var pdfFormFields = stamper.AcroFields;
var fieldKeys = pdfReader.AcroFields.Fields.Keys;
foreach (var k in fieldKeys.ToList())
{
pdfFormFields.RenameField(k, k + string.Format("_{0:000}", pageNumber));
}
}
I searched online but I can't find an answer about my problem.
The PDF template I'm adding has some fields added with Acrobat. I can't attach the template but I can give you all informations.
I cannot see how do you instantiate the stamper. This is an example about how to read a PDF template and assign it to the stamper:
var reader = new PdfReader(TEMPLATE_PATH);
var pdfOutput = new FileStream(PDF_OUTPUT_PATH, FileMode.Create)
var stamper = new PdfStamper(reader, pdfOutput);
After that, you can set the fields using the SetField function:
stamper.AcroFields.SetField("FIELD1", "VALUE")
There is an option to make your fillable PDFs non-editable using:
stamper.FormFlattening = true;
Otherwise, your PDF still fillable.
Once you have finished working with your files, close them:
stamper.Close();
reader.Close();
There is an example about how to use iTextSharp's PdfStamper in the next link: http://www.codeproject.com/Tips/679606/Filling-PDF-Form-using-iText-PDF-Library
In my website, a client will upload different types of PDF templates which contain editable fields. I want to read the text and editable fields from the PDF and display the text with corresponding fields in my web form. I have found solutions for reading the text and fields separately, but I am not able to map the fields against the corresponding text.
Reading text and getting fields using itextsharp but not able to map that text and field. for ex: in the pdf it is specified as FirstName: Thomas. Reading from the PDF and display it in the UI as Firstname(label): Thomas (textbox).
sample code i have used to get all the fields,
public string GetPDFFields()
{
string pdfTemplate = #"d:\1234.pdf";
var pdfReader = new PdfReader(pdfTemplate);
var outStream = new MemoryStream();
var stamper = new PdfStamper(pdfReader, outStream);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
StringBuilder sb = new StringBuilder();
foreach (string fieldKey in fieldKeys)
{
sb.Append(form.GetField(fieldKey)+"\r\n");
}
return sb.ToString();
}
Try to read use this code sample
http://simpledotnetsolutions.wordpress.com/2012/04/08/itextsharp-few-c-examples/
I am trying to find out if it is possible to read PDF Form data (Forms filled in and saved with the form) using iTextSharp. How can I do this?
You would have to find out the field names in the PDF form. Get the fields and then read their value.
string pdfTemplate = "my.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
AcroFields fields = pdfReader.AcroFields.Fields;
string val = fields.GetField("fieldname");
Obviously in the code above, field name is the name of the PDF form field and the GetField method returns a string representation of that value.
Here is an article with example code that you could probably use. It shows how you can both read and write form fields using iTextSharp.
Maybe the iTextSharp library has changed recently but I wasn't able to get the accepted answer to work. Here is my solution:
var pdf_filename = "pdf2read.pdf";
using (var reader = new PdfReader(pdf_filename))
{
var fields = reader.AcroFields.Fields;
foreach (var key in fields.Keys)
{
var value = reader.AcroFields.GetField(key);
Console.WriteLine(key + " : " + value);
}
}
A very subtle difference, due to reader.AcroFields.Fields returning an IDictionary instead of just an AcroFields object.
If you are using Powershell, the discovery code for fields is:
Add-Type -Path C:\Users\Micah\Desktop\PDF_Test\itextsharp.dll
$MyPDF = "C:\Users\Micah\Desktop\PDF_Test\something_important.pdf"
$PDFDoc = New-Object iTextSharp.text.pdf.pdfreader -ArgumentList $MyPDF
$PDFDoc.AcroFields.Fields
That code will give you the names of all the fields on the PDF Document, "something_important.pdf".
This is how you access each field once you know the name of the field:
$PDFDoc.AcroFields.GetField("Name of the field here")
This worked for me!
Note the parameters when defining stamper! '\0', true
string TempFilename = Path.GetTempFileName();
PdfReader pdfReader = new PdfReader(FileName);
//PdfStamper stamper = new PdfStamper(pdfReader, new FileStream(TempFilename, FileMode.Create));
PdfStamper stamper = new PdfStamper(pdfReader, new FileStream(TempFilename, FileMode.Create), '\0', true);
AcroFields fields = stamper.AcroFields;
AcroFields pdfFormFields = pdfReader.AcroFields;
foreach (KeyValuePair<string, AcroFields.Item> kvp in fields.Fields)
{
string FieldValue = GetXMLNode(XMLFile, kvp.Key);
if (FieldValue != "")
{
fields.SetField(kvp.Key, FieldValue);
}
}
stamper.FormFlattening = false;
stamper.Close();
pdfReader.Close()
The PDF name is "report.pdf"..
The data field to be read into TextBox1 is "TextField25" in the PDF..
Dim pdf As String = "report.pdf"
Dim reader As New PdfReader(pdf)
Dim fields As AcroFields = reader.AcroFields
TextBox1.Text = fields.GetField("TextField25")
Important Note: This can be used ONLY IF the PDF is not flattened (means the fields should be editable) while it was created using iTextSharp..
i.e.
pdfStamper.FormFlattening = False
This is very simple.. And it works like a charm.. :)
If anybody is still wondering about this answer, this is how I extracted the text in the field (provided you know the field name):
PdfReader reader = new("filepath");
PdfDocument doc = new(reader);
PdfAcroForm form = PdfAcroForm.GetAcroForm(document, false);
Form.GetField("FieldNameHere").GetValueAsString();
Works for iText 7.1.16