I'm working to refactor a PDF form web application that is using the Active PDF Toolkit and the FDFToolkit from Adobe. My goal is to use iTextSharp to:
Pre-populate the form fields with data from the database
Allow the user to attach a signature and/or barcode image via FDF
Item #1 is not the problem. Item #2 is the biggest challenge. Let me provide some background:
This is a web application which renders the PDF form once. After the initial load, there are 2 key buttons on the form which submit the PDF form to a URL with an action parameter in the query string. These buttons are called "Save" and "Sign". The Save button takes the FDF field dictionary and saves it to the database. The Sign button looks up the signature for the logged-in user and attaches the signature image to the FDF and writes the FDF to the HTTP Response.
The FDFToolkit supports attaching an image to a field using this method:
FDFSetAP(string bstrFieldName, short whichFace, string bstrFileName, short pageNum)
iTextSharp does not offer a comparable method in the FdfWriter class. I've considered subclassing the FdfWriter class and adding my own method to attach an image, but wanted to reach out here to see if anyone has had the same problem.
I have been able to overlay an image on top of a field using this method, but this is in the underlying PDF and not the FDF.
AcroFields.FieldPosition pos = _Stamper.AcroFields.GetFieldPositions("SIGNATUREFIELD").First();
Image signature = Image.GetInstance("Signature.gif");
image.SetAbsolutePosition(pos.position.Left, pos.position.Bottom);
image.ScaleToFit(pos.position.Width, pos.position.Height);
PdfContentByte pcb = _Stamper.GetOverContent(pos.page);
pcb.AddImage(image);
Thanks!
I've put images on forms by using the PdfStamper and making Pushbutton fields. You can replace your existing field with a Pushbutton field and set the Pushbutton to READ_ONLY so that it can't be pressed and it will look like a static image. This will keep the image you're trying to add as a field annotation instead of adding it to the page content.
using (PdfStamper stamper = new PdfStamper(new PdfReader(inputFile), File.Create(outputFile)))
{
AcroFields.FieldPosition fieldPosition = stamper.AcroFields.GetFieldPositions(fieldName)[0];
PushbuttonField imageField = new PushbuttonField(stamper.Writer, fieldPosition.position, fieldName);
imageField.Layout = PushbuttonField.LAYOUT_ICON_ONLY;
imageField.Image = iTextSharp.text.Image.GetInstance(imageFile);
imageField.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS;
imageField.ProportionalIcon = false;
imageField.Options = BaseField.READ_ONLY;
stamper.AcroFields.RemoveField(fieldName);
stamper.AddAnnotation(imageField.Field, fieldPosition.page);
}
Related
I am developing an Android app for flight reservation and i am using firebase Database for storing and retriving data. I need to generate a PDF of Ticket and contents should be changed as per passenger details and stored in local directory. I have a template of Ticket. What should i do?
Thank you in advance.
Since Android 5 you can use PdfDocument and its friend classes to generate a PDF document on Android device. The official documentation is here. There is no library to use a template with PdfDocument. You have to use some drawing primitive to accomplish your task.
Here is a sample to generate a PDF with a single page A4:
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(595, 842, 1).create();
// start a page
Page page = document.startPage(pageInfo);
Canvas canvas=page.getCanvas());
// draw something on the page
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(50, 50, 30, paint);
// finish the page
document.finishPage(page);
// write the document content
document.writeTo(getOutputStream());
// close the document
document.close();
The page content is defined with Canvas object. Just another example. I hope this helps you.
I'm setting the visibility of a PdfFormField to HIDDEN using the setVisibility() method with parameter PdfFormField.HIDDEN. Still, on flattening it, the field does not hide. Below is the code to do so.
File file = new File("path to PDF file");
baos = new ByteArrayOutputStream();
pdfDoc = new PdfDocument(new PdfReader(file.getAbsolutePath()), new PdfWriter("path to flattened PDF file"));
//This function removes all the permissions.
removePdfPermissions();
form = PdfAcroForm.getAcroForm(pdfDoc, true);
fields = form.getFormFields();
fields.get("HumanSubjectsText").setVisibility(PdfFormField.HIDDEN);
fields.get("HumanSubjects").setVisibility(PdfFormField.HIDDEN);
form.flattenFields();
pdfDoc.close();
Setting the values of the fields to empty string "" is a workaround, but not the proper way.
The fields "HumanSubjects" and "HumanSubjectsText" correspond to a checkbox and its correspond text on page 2. (Human Subjects)
Link to PDF file
The fields could not be hidden using iText library. In contrast to Bruno's comment, one of the methods from iText library worked well, the setValue(). I'm not quite sure why the setVisibility() fails.
However, I was able to hide the field using Master PDF editor tool. I've attached a screenshot of this tool, where you can change the visibility for a form field from the General tab.
An observation: In the com.itextpdf.forms.fields.PdfFormField some of the constants defined are as follows:
public static final int HIDDEN = 1;
public static final int VISIBLE_BUT_DOES_NOT_PRINT = 2;
public static final int HIDDEN_BUT_PRINTABLE = 3;
public static final int VISIBLE = 4;
The Master PDF editor also has similar options to hide a field. Please refer to the attached screenshot.
NOTE: My requirement was just to simply hide the field. It could be achieved programmatically by using a library like iText or with some PDF editor tool.
I have to fill PDF form with some data. This form contains a few tables with "Add" button which adds new row with inputs to this table, for example to "FOREIGN PATENT DOCUMENTS".
I need to "click" this button in my code using iText a few times, add necessary rows, get input names there and fill them. How can I do this with iText? Could anybody provide me a code example?
My PDF file with form https://drive.google.com/open?id=0BwtWU1543EbTQ3A3b2dZcW9qYk0
This file is predefined and I can't regenerate it.
You don't "click" a button programmatically. You just provide the data that is necessary, and the form will adapt.
See the FillXFA example. We have a purchase_order.pdf that looks like this:
This document has an "Add item" button to add more line items (which results in creating more pages if necessary). That button only makes sense if there's a GUI, but when you fill out the form programmatically, there aren't any buttons to push. You just provide the XML with the data (e.g. data.xml), like this:
public void manipulatePdf(String src, String dest)
throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader,
new FileOutputStream(dest));
AcroFields form = stamper.getAcroFields();
XfaForm xfa = form.getXfa();
xfa.fillXfaForm(new FileInputStream(XML));
stamper.close();
reader.close();
}
The result looks like this: purchase_order_filled.pdf
As you can see, multiple lines were added, without pushing any button.
Important: I see that you have a hybrid document. I think you should make it a pure XFA form. This code won't work if you keep the AcroForm fields.
I have a number of Dynamic XFA PDFs that were created with Livecycle Designer. These PDFs are used as templates for various individuals to complete. When a user requests a template we have to write a submit button with url pointing back to a .net application for processing and update some of the fields with information from the database into the PDF.
Can I use iText(Sharp) with .net to update the dynamic xfa pdf to write into it a submit button and update fields and then use iText(Sharp) to process the returning form.
We are doing this now with Acroforms but need to do the same for Dynamic XFA forms as well. I can’t find any confirmation information that this is possible. If it is possible does anyone have any code that they can share to show me how to do this?
You can also achieve that putting the pdf's content inside an XmlDocument and working as you were working with an XML.
This is the code I use to replace some placeholders written in textboxes.
PdfReader pdfReader = new PdfReader(path_pdf);
using (PdfStamper pdfStamp = new PdfStamper(pdfReader, new FileStream(temp_path, FileMode.Create), '\0', true))
{
pdfStamp.ViewerPreferences = PdfWriter.AllowModifyContents;
XmlDocument xmlDocument = pdfReader.AcroFields.Xfa.DomDocument;
string pdfContent = xmlDocument.InnerXml;
string newpdfContent = pdfContent
.Replace("$CONTENT_TO_REPLACE_1$", "some_content")
.Replace("$CONTENT_TO_REPLACE_2$", "some_other_content")
xmlDocument.InnerXml = newpdfContent;
Stream stream = GenerateStreamFromString(newpdfContent);
pdfStamp.AcroFields.Xfa.FillXfaForm(stream);
pdfStamp.AcroFields.Xfa.DomDocument = xmlDocument;
pdfStamp.Close();
}
I pieced together some code to insert a dynamic image into a PDF using both ColdFusion and iText, while filling in some form fields as well. After I got it working and blogged about it, I couldn't help but think that there might be a better way to accomplish this. I'm using the basic idea of this in a production app right now so any comments or suggestion would be most welcomed.
<cfscript>
// full path to PDF you want to add image to
readPDF = expandpath(”your.pdf”);
// full path to the PDF we will output. Using creatUUID() to create
// a unique file name so we can delete it afterwards
writePDF = expandpath(”#createUUID()#.pdf”);
// full path to the image you want to add
yourimage = expandpath(”dynamic_image.jpg”);
// JAVA STUFF!!!
// output buffer to write PDF
fileIO = createObject(”java”,”java.io.FileOutputStream”).init(writePDF);
// reader to read our PDF
reader = createObject(”java”,”com.lowagie.text.pdf.PdfReader”).init(readPDF);
// stamper so we can modify our existing PDF
stamper = createObject(”java”,”com.lowagie.text.pdf.PdfStamper”).init(reader, fileIO);
// get the content of our existing PDF
content = stamper.getOverContent(reader.getNumberOfPages());
// create an image object so we can add our dynamic image to our PDF
image = createobject(”java”, “com.lowagie.text.Image”);
// get the form fields
pdfForm = stamper.getAcroFields();
// setting a value to our form field
pdfForm.setField(”our_field”, “whatever you want to put here”);
// initalize our image
img = image.getInstance(yourimage);
// centering our image top center of our existing PDF with a little margin from the top
x = (reader.getPageSize(1).width() - img.scaledWidth()) - 50;
y = (reader.getPageSize(1).height() - img.scaledHeight()) / 2 ;
// now we assign the position to our image
img.setAbsolutePosition(javacast(”float”, y),javacast(”float”, x));
// add our image to the existing PDF
content.addImage(img);
// flattern our form so our values show
stamper.setFormFlattening(true);
// close the stamper and output our new PDF
stamper.close();
// close the reader
reader.close();
</cfscript>
<!— write out new PDF to the browser —>
<cfcontent type=”application/pdf” file = “#writePDF#” deleteFile = “yes”>
<cfpdf> + DDX seems possible.
See http://forums.adobe.com/thread/332697
I have made it in another way with itext library
I don´t want overwrite my existing pdf with the image to insert, so just modify the original pdf inserting the image, just insert with itext doesn´t work for me.
So, I have to insert the image into a blank pdf (http://itextpdf.com/examples/iia.php?id=59)
And then join my original pdf and the new pdf-image. Obtaining one pdf with several pages.
(http://itextpdf.com/examples/iia.php?id=110)
After that you can overlay the pdf pages with this cool concept
http://itextpdf.com/examples/iia.php?id=113