I have a pdf document already created with some textfields.I can fill those text fields using Adobe reader and save those values with that file.
My problem is ,can i do that programmatically using iText?If it is possible ,please tell me where i can find some examples?
That's explained in the iText 7 Jump-start tutorial, more specifically in chapter 4:
This form:
Can be filled out like this:
PdfDocument pdf =
new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
Map<String, PdfFormField> fields = form.getFormFields();
fields.get("name").setValue("James Bond");
fields.get("language").setValue("English");
fields.get("experience1").setValue("Off");
fields.get("experience2").setValue("Yes");
fields.get("experience3").setValue("Yes");
fields.get("shift").setValue("Any");
fields.get("info").setValue("I was 38 years old when I became an MI6 agent.");
// form.flattenFields();
pdf.close();
The result looks like this:
If you uncomment the line form.flattenFields(); then you get this:
When the form is flattened, the fields are removed, and only the content is left.
If by any chance the PDF is a dynamic XFA form, then you should provide an XML stream, and you should read the FAQ: How to fill out a pdf file programmatically? (Dynamic XFA)
As you seem to be new to iText, it is assumed that you'll use the latest version of iText (which is iText 7) as opposed to a version that is being phased out (iText 5) or obsolete (all versions prior to iText 2). However, if for any reason you choose to use iText 5, then your question is a duplicate of How to fill out a pdf file programatically? (in which case your question should be closed as a duplicate).
Related
I need to input XFA form field values into a LiveCycle reader-enabled PDF using iText 7. I can do this successfully but if I don't open the PDF in append mode then it appears the Adobe signature gets broken and the form values cannot be further edited by a user and saved again. If I open the PDF with iText 7 in append mode and change the XFA form field values, the signature from being reader-enabled does not get broken but the changed values aren't showing up on the form. It seems like a bug with iText 7 and changing XFA form field values with append mode possibly. Has anyone successfully done this?
There was a bug in filling XFA Forms in append mode in iText7. This has been fixed in 7.0.2 (and 7.0.2-SNAPSHOT).
The fill a form in append mode, you need the following piece of code:
PdfDocument pdfdoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST),
new StampingProperties().useAppendMode());
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfdoc, true);
XfaForm xfa = form.getXfaForm();
xfa.fillXfaForm(new FileInputStream(XML));
xfa.write(pdfdoc);
pdfdoc.close();
I am using iText7(java) and am looking for a way to convert a pdf page to image.
In older iText versions you could do this :
PdfImportedPage page = writer.getImportedPage(reader, 1);
Image image = Image.getInstance(page);
But iText7 does not have PdfImportedPage .
My use case, I have a one page pdf file. I need to add a table and resize the pdf contents to fit a single page. In old iText I would create a page , add table, convert existing pdf page to image, resize image and add that resized image to new page. Is there a new way to do this in iText7.
Thanks to Bruno's answer I got this working with following code :
PdfPage origPage = readerDoc.getPage(1);
Rectangle rect = origPage.getPageSize();
Document document = new Document(writerDoc);
Table wrapperTable = new Table(1);
Table containerTable = new Table(new float[]{0.5f,0.5f});
containerTable.setWidthPercent(100);
containerTable.addCell( "col1");
containerTable.addCell("col2");
PdfFormXObject pageCopy = origPage.copyAsFormXObject(writerDoc);
Image image = new Image(pageCopy);
image.setBorder(Border.NO_BORDER);
image.setAutoScale(true);
image.setHeight(rect.getHeight()-250);
wrapperTable.addCell(new Cell().add(containerTable).setBorder(Border.NO_BORDER));
wrapperTable.addCell(new Cell().add(image).setBorder(Border.NO_BORDER));
document.add(wrapperTable);
document.close();
readerDoc.close();
Please read the official documentation for iText 7, more specifically Chapter 6: Reusing existing PDF documents
In PDF, there's the concept of Form XObjects. A Form XObject is a piece of PDF content that is stored outside the content stream of a page, hence XObject which stands for eXternal Object. The use of the word Form in Form XObject could be confusing, because people might be thinking of a form as in a fillable form with fields. To avoid that confusing, we introduced the term PdfTemplate in iText 5.
The class PdfImportedPage you refer to was a subclass of PdfTemplate: it was a piece of PDF syntax that could be reused in another page. Over the years, we noticed that people also got confused by the word PdfTemplate.
In iText 7, we returned to the basics. When talking about a Form XObject, we use the class PdfFormXObject. When talking about a page in a PDF file, we use the class PdfPage.
This is how we get a PdfPage from an existing document:
PdfDocument origPdf = new PdfDocument(new PdfReader(src));
PdfPage origPage = origPdf.getPage(1);
This is how we use that page in a new document:
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
If you want to use that pageCopy as an Image, just create it like this:
Image image = new Image(pageCopy);
We have a number of dynamically generated printable forms files on our site that use iText 4.2.0. However, we also have a large number of users that have print disabilities and use screen readers, like JAWS, to render our PDFs. We use the .setTagged() method to tag the PDFs, but some elements of the PDF appear out of order. Some even become more jumbled after calling setTagged!
I read about PDF/UA in a 2013 interview about iText with Bruno Lowagie, and this seems like something that might help with our problem. However, I have not been able to find a good example of how to generate a PDF/UA document. Can you provide an example? Also, what is the minimum version of iText we will need to generate a PDF/UA compliant PDF document?
Please take a look at the PdfUA example. It explains step by step what is needed to be compliant with PDF/UA. A similar example was presented at the iText Summit in 2014 and at JavaOne. Watch the iText Summit video tutorial.
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document(PageSize.A4.rotate());
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
writer.setPdfVersion(PdfWriter.VERSION_1_7);
//TAGGED PDF
//Make document tagged
writer.setTagged();
//===============
//PDF/UA
//Set document metadata
writer.setViewerPreferences(PdfWriter.DisplayDocTitle);
document.addLanguage("en-US");
document.addTitle("English pangram");
writer.createXmpMetadata();
//=====================
document.open();
Paragraph p = new Paragraph();
//PDF/UA
//Embed font
Font font = FontFactory.getFont(FONT, BaseFont.WINANSI, BaseFont.EMBEDDED, 20);
p.setFont(font);
//==================
Chunk c = new Chunk("The quick brown ");
p.add(c);
Image i = Image.getInstance(FOX);
c = new Chunk(i, 0, -24);
//PDF/UA
//Set alt text
c.setAccessibleAttribute(PdfName.ALT, new PdfString("Fox"));
//==============
p.add(c);
p.add(new Chunk(" jumps over the lazy "));
i = Image.getInstance(DOG);
c = new Chunk(i, 0, -24);
//PDF/UA
//Set alt text
c.setAccessibleAttribute(PdfName.ALT, new PdfString("Dog"));
//==================
p.add(c);
document.add(p);
p = new Paragraph("\n\n\n\n\n\n\n\n\n\n\n\n", font);
document.add(p);
List list = new List(true);
list.add(new ListItem("quick", font));
list.add(new ListItem("brown", font));
list.add(new ListItem("fox", font));
list.add(new ListItem("jumps", font));
list.add(new ListItem("over", font));
list.add(new ListItem("the", font));
list.add(new ListItem("lazy", font));
list.add(new ListItem("dog", font));
document.add(list);
document.close();
}
You make the document tagged with the setTagged document, but that's not sufficient. You also need to set document data: the document title needs to be displayed and you need to indicate the language used in the document. XMP metadata is mandatory.
Furthermore you need to embed all fonts. When you have images, you need a alternate description. In the example, we replace the words "dog" and "fox" by an image. To make sure that these images are "read out loud" correctly, we need to use the setAccessibleAttribute() method.
At the end of the example, I added a numbered list. In your duplicate question https://stackoverflow.com/questions/28222490/numbered-list-across-a-page-break-causes-jaws-to-read-numbers-out-of-order-in-it, you claim that the list is not read out loud correctly by JAWS. If you check the PDF file created with the above example, more specifically pdfua.pdf, you'll discover that JAWS reads the document as expected, with the numbers and the text in the right order.
The reason why "it doesn't work" when you try this, is simple. You claim that you are using iText, but you are not. You are using a "gork" of iText. A "gork" is an unofficial "fork" of which God Only Really Knows what's inside. You need the latest iText version to achieve what you want because PDF/UA is a standard dating from 2012 and you are using a version of iText that dates from 2009.
I suggest that you delete that other question because:
it is a duplicate of this question (if you disagree, read my answer: isn't it exactly what you're asking in both questions?),
it is off-topic in the sense that it sounds like "I am using an ancient DVD player and it doesn't want to play my blue ray disks." (I know that you downvoted my correct answer because you don't believe this to be true. So be it. Other people will find this answer valuable and understand that your vote was unfair.)
Please read the final question in The Best iText Questions on StackOverflow to find out what I think about people using unofficial, rogue, obsolete versions of iText.
See also https://stackoverflow.com/questions/25696851/can-itext-2-1-7-or-earlier-can-be-used-commercially
I am using iTextSharp 5.5.3 i have a PDF with named fields i created with Adobe lifecycle I am able to fill the fields using iTextSharp but when i change the textcolor for a field it does not change. i really dont know why this is so. here is my code below
form.SetField("name", "Michael Okpara");
form.SetField("session", "2014/2015");
form.SetField("term", "1st Term");
form.SetFieldProperty("name", "textcolor", BaseColor.RED, null);
form.RegenerateField("name");
If your form is created using Adobe LifeCycle, then there are two options:
You have a pure XFA form. XFA stands for the XML Forms Architecture and your PDF is nothing more than a container of an XML stream. There is hardly any PDF syntax in the document and there are no AcroForm fields. I don't think this is the case, because you are still able to fill out the fields (which wouldn't work if you had a pure XFA form).
You have a hybrid form. In this case, the form is described twice inside the PDF file: once using an XML stream (XFA) and once using PDF syntax (AcroForm). iText will fill out the fields in both descriptions, but the XFA description gets preference when rendering the document. Changing the color of a field (or other properties) would require changing the XML and iText(Sharp) can not do that.
If I may make an educated guess, I would say that you have a hybrid form and that you are only changing the text color of the AcroForm field without changing the text color in the XFA field (which is really hard to achieve).
Please try adding this line:
form.RemoveXfa();
This will remove the XFA stream, resulting in a form that only keeps the AcroForm description.
I have written a small example named RemoveXFA using the form you shared to demonstrate this. This is the C#/iTextSharp version of that example:
public void ManipulatePdf(String src, String dest)
{
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
AcroFields form = stamper.AcroFields;
form.RemoveXfa();
IDictionary<String, AcroFields.Item> fields = form.Fields;
foreach (String name in fields.Keys)
{
if (name.IndexOf("Total") > 0)
form.SetFieldProperty(name, "textcolor", BaseColor.RED, null);
form.SetField(name, "X");
}
stamper.Close();
reader.Close();
}
In this example, I remove the XFA stream and I look over all the remaining AcroFields. I change the textcolor of all the fields with the word "Total" in their name, and I fill out every field with an "X".
The result looks like this: reportcard.pdf
All the fields show the letter "X", but the fields in the TOTAL column are written in red.
I finally found a way, guess the problem was coming from using Adobe LC, so i switched to Open Office it all worked but when i flatten the form everything disappears. I found a solution to that here ITextSharp PDFTemplate FormFlattening removes filled data
Thanks Mr Lowagie for your help
I'm using iTextSharp to create pdf files on the fly for my users to save on their computers. Currently the way it works is that I had several pdf templates that iTextSharp opens, sets fields from the database and save on user computer.
I'm having real problems with adding rich content into the body field which the users enter using a Rich Text editor (NiceEdit). It contains really simple options such as bullets, bold, italic, font colors, sizes etc. which is all what they need. I tried all possible options out there but nothing seem to help.
PdfReader reader = new PdfReader(originalReport.ToString());
PdfStamper stamper = new PdfStamper(reader, new FileStream(report, FileMode.Create));
AcroFields fields = stamper.AcroFields;
fields.SetFieldProperty("body", "setfflags", PdfFormField.FF_RICHTEXT, null);
fields.SetFieldRichValue("body", bodyValue.ToString());
fields.GenerateAppearances = false;
I tried flattening the form but it doesn't display the field at all. If I didn't flatten the form then the field displays the content but with no format at all (even new lines are removed) and if I used the SetField option instead of the SetFieldRichValue I get a string of the html content
I also tried allowing the pdf template field to "Allow Rich Text" from acrobat pro but this gives an exception and halts the pdf :)
Also please note that since I'm using a template that depends on the type of the user, the SetField option is used, I don't create the document from scratch hence I don't use paragraphs which I can get if I used the HTMLWorker and simply add to a document
Any help please?