Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

PDF Form filling with rich text

Posted on 2005-04-21
13
Medium Priority
?
2,102 Views
Last Modified: 2012-05-08
Using iText and Java I am taking a pdf template with form fields and placing content into those form fields. I am trying to find a way to style the content within the form fields. For example... "Initials Required: Some other text is right here" in that sentence I want "initials required" to be bold and italics verdana size 10 and the rest to just be verdana size 10.  Or the other example is have text inside a text box to be centered.

Goal....
Being able to bold, italics, and center text in a PDF form field.

Using: Java, iText, Acrobat Pro

0
Comment
Question by:Isisagate
  • 5
  • 3
  • 3
  • +1
13 Comments
 
LVL 11

Author Comment

by:Isisagate
ID: 13836200
I found the option to center text in a form field within acrobat pro so now the goal is mixed type face styling within a form field via rich text.
0
 
LVL 10

Expert Comment

by:edwardiii
ID: 13837688
Hi, Isisgate.

I don't have Acrobat Pro, so can't help find a solution like I wish I could.  Here are some suggestions:

1)  You can download a PDF from Adobe's site (http://www.adobe.com/misc/pdfs/ext_forms_chptr1.pdf).  The PDF on page 14 (under "An example") provides code for manipulating "txtField" fillColor and textColor.  The Adobe JavaScript guide is offered for sale on page 15; it might contain the code you're looking for.  By the way, I don't think Acrobat supports full Java, just JavaScript.  And it may only provide partial support for JavaScript.  If you could use Java on the font object of the appropriate txtField, you could use something like:

     <insert object name here>.setFont( new Font( "Monospaced", Font.ITALIC, 24));

to set the font as 24-point Monospaced italic.  Does Acrobat Pro poplate available methods when you type a Text field's name followed by a period (e.g. "txtField1.")?

2)  If you haven't already, you may wish to post a pointer to this question in the Adobe Acrobat forum of Experts Exchange.  I've seen several valuable posts regarding usage of JavaScript in Acrobat in that forum.

3)  I was able to manipulate selected text manually by right-clicking it after hightlighting the text with the Touch Up Text tool, then selected Properties and working with the font type.  Does Acrobat Pro have the ability to record a macro, so you can see the code it generates when you change the font type, so maybe you could build on that code to achieve desired results?
0
 
LVL 11

Author Comment

by:Isisagate
ID: 13843378
well that's not really along the lines of what I need. In Acrobat pro I can set the default attributes as it stands to make the text in the field bold or verdana and all that. The problem is it will apply to all of the text. Where as I want to be able to put in a string of text and maybe has only one word of that text be bold. Acrobat pro allows you to specify the form field as allowing rich text formatting. I guess I'm hoping someone can help me figure out how to do the rich text formating of a string for italics bold and plain. Then the next step is filling the form field with that rich text.  So lets say for example this html formatted string... "<b><i>Initials Required:</i></b> Some more text here in plain verdana size 8" the goal would be to figure out how to convert that into rich text that can be inserted. Either through hardcoded java or using itext.

Thanks,
isisagate
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 10

Expert Comment

by:edwardiii
ID: 13843796
I understand.  I did a search ("rich text javascript")in the Adobe Acrobat EE forum (per my item #2 above) and found a possible solution for you here: http://www.experts-exchange.com/Web/Graphics/Adobe_Acrobat/Q_21034273.html?query=rich+text+javascript&topics=246

If that doesn't help you, I really would post a 20-point pointer to this question in the Adobe Acrobat forum--the experts there will likely know immediately if what you're trying to do is possible with Acrobat.
0
 
LVL 44

Expert Comment

by:Karl Heinz Kremer
ID: 13844560
As far as I know, iText does not support Rich Text formatting for form fields. Why are you using form fields? Is it important that the final PDF file contains the form fields, or are you using them only because it's conveniant to get information into a PDF file?

If it's just to get information into the file, you could just get the location and size of the form field, and then create native PDF text in whatever form you want at the location of the form field.
0
 
LVL 11

Author Comment

by:Isisagate
ID: 13844990
Well I admit I haven't gone more indepth then I have needed to into itext and it's abilities. The problem stems from being able to populate data into a custom invoice template in a generic way that doesn't require FOP and XSLT coding to create the invoice rather just using word and arcobat to build the pdf and layout the data fields then have the java fill in whatever fields it recognizes with the correct text.

I think your way could work too, Do you happen to have an example of how to do that replacement? Like say replace a form field with a text field containing mixed styling? bold and plain text or italics and plain text?

0
 
LVL 44

Expert Comment

by:Karl Heinz Kremer
ID: 13845104
Before I work on some samples, do you need to do this in Java, or would it be possible to perform the task in e.g. Acrobat? Or, to rephrase my question: Do you want to run this process automatically (e.g. on a server), or is this something that would always run on somebody's desktop computer?
The reason I'm asking is that first of all, I'm not a Java programmer (I followed your pointer question over in the Acrobat TA), and second, it's much simpler to do this in JavaScript within Acrobat (here you would be able to use Rich Text formatting for form fields). Acrobat can however not be used on a server (or in a server-like environment).
0
 
LVL 1

Expert Comment

by:joneset
ID: 13845609
Hi,
     I think I have an example of what you need in Java.
But first let me tell you this...
You could use Acrobat to create a template pdf complete with form fields.
When you do that, you will specify font info for those fields at that time.

Then you will use iText to either stamp the output pdf or you can use iText to paste text to the field locations specified in
your pdf template.
Which you chose depends on whether or not you need to read info back out of the output pdf.
El

0
 
LVL 44

Expert Comment

by:Karl Heinz Kremer
ID: 13845723
joneset, the problem here is that multiple fonts (or font attributes) need to be used in one form field. With "normal" AcroForm fields, you can only assign one font, one font size, and one color to the field. With Rich Text fields it's possible to change the formatting within one field. This is however not a simple process. You can e.g. create a Rich Text field, bring up the properties toolbar and then create some text with diferent attributes. When you then export the FDF file, and open this file in a text editor you can see how the different attributes are stored as XML information.

Unfortunately iText cannot work with this directly. Therefore I suggested to use the field location and size to find out where to place "normal" PDF content with iText.
0
 
LVL 11

Author Comment

by:Isisagate
ID: 13845853
We are using Java on a server and pulling the information from a database. So it will be an on the fly type of thing. There is a template already built with form fields located in it... I have code to figure out the locations of the form fields and have code that can replace a form field with an image sized and positioned where that form field is.  However I don't know itext or pdfs enough to handle replacing with mixed styled content.
0
 
LVL 1

Expert Comment

by:joneset
ID: 13846319
Isisaqate, will you be extracting field from the output pdf??
El
0
 
LVL 11

Author Comment

by:Isisagate
ID: 13846802
no the goal is a printable invoice to hand to someone
0
 
LVL 1

Accepted Solution

by:
joneset earned 2000 total points
ID: 13846888
This code gives me two fonts  in a "field" (not really a form field, but a text field that is positioned).
To run my code, you'll need a pdf with a couple of form fields (sales2.pdf), a flat copy of sales2.pdf called out.pdf and
named  output file out2.pdf .  I could send you the pdfs if you'd like.  I don't think it matters what the field names are.
Go to section that says " look here" for my hacking. (You'll notice I use tons of the iText example stuff)

/**
 * List the name and position of the fields.
 * @author
 */
import java.io.*;
import java.util.*;

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class pasteTextToPdf {

      private String inFormPdf;
      private String inFlatPdf;
      private String outPdf;
      private HashMap fieldHashMap;

      public pasteTextToPdf(String InFormPdf,String InFlatPdf,String OutPdf){
                  inFormPdf = InFormPdf;
                  inFlatPdf = InFlatPdf;
                  outPdf = OutPdf;

      }
      public void FillBlanks(){
            /* if (args.length < 3) {
                  System.err.println("Overlays text at precise positions in a PDF document.");
                  System.err.println("It is generally used with DumpFields to get the writing positions.");
                  System.err.println("The params file is a text file where the first line is:");
                  System.err.println("page x y font_name font_size red green blue");
                  System.err.println("The second line is the text and so on.");
                  System.err.println("The text color has the range 0-255. The font size is in points.");
                  System.err.println("usage: java FillBlanks pdf_file_in pdf_file_out hash_map_of_params");
                  return;
            } */

            int PAGE = 0;
            int X = 1;
            int Y = 2;
            int FONT_NAME = 3;
            int FONT_SIZE = 4;
            int RED = 5;
            int GREEN = 6;
            int BLUE = 7;
            int TEXT = 8;

            try {

                  PdfReader reader = new PdfReader(inFormPdf);
                  FileOutputStream out = new FileOutputStream(outPdf);
                  /* BufferedReader params = new BufferedReader(new FileReader(args[2])); */
                  String line = "";
                  HashMap map = new HashMap();
                  Set entries = fieldHashMap.entrySet();
                  Iterator entryIter = entries.iterator();

                  while (entryIter.hasNext()) {
                        Map.Entry entry = (Map.Entry)entryIter.next();
                     Object key = entry.getKey();  // Get the key from the entry.
                     Object value = entry.getValue();  // Get the value.
                     /* System.out.println( "   (" + key + "," + value + ")" ); */
                        line = value.toString();
                        if (line.length() < 5)
                              break;
                        System.out.println(line);
                        StringTokenizer tk = new StringTokenizer(line);
                        Object objs[] = new Object[TEXT + 1];
                        objs[PAGE] = new Integer(tk.nextToken());
                        objs[X] = new Float(tk.nextToken());
                        objs[Y] = new Float(tk.nextToken());
                        objs[FONT_NAME] = tk.nextToken();
                        objs[FONT_SIZE] = new Float(tk.nextToken());
                        objs[RED] = new Integer(tk.nextToken());
                        objs[GREEN] = new Integer(tk.nextToken());
                        objs[BLUE] = new Integer(tk.nextToken());
                        /* line = params.readLine(); */
                        if (line == null)
                              break;
                        /* objs[TEXT] = line; */
                        objs[TEXT] = "aaa bbb ccc";

                        if (map.containsKey(objs[PAGE])) {
                              ArrayList arr = (ArrayList)map.get(objs[PAGE]);
                              arr.add(objs);
                        }
                        else {
                              ArrayList arr = new ArrayList();
                              arr.add(objs);
                              map.put(objs[PAGE], arr);
                        }
                  }
                  /* params.close(); */
                  Document document = new Document(reader.getPageSize(1));
                  PdfWriter writer = PdfWriter.getInstance(document, out);
                  document.open();
                  for (int cnt = 0 ; cnt < 2; cnt++)
                  {
                        for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
                              if (page != 1) {
                                    document.setPageSize(reader.getPageSize(2));
                                    document.newPage();
                              }
                              PdfContentByte cb = writer.getDirectContent();
                              cb.addTemplate(writer.getImportedPage(reader, page), 0, 0);
                              ArrayList arr = (ArrayList)map.get(new Integer(page));
                              if (arr == null)
                                    continue;
                              cb.beginText();
                              System.out.println("Got here 1.");
                              for (int k = 0; k < arr.size(); ++k) {
/* look right here */
                                    Object objs[] = (Object[])arr.get(k);
                                    cb.setRGBColorFill(((Integer)objs[RED]).intValue(), ((Integer)objs[GREEN]).intValue(), ((Integer)objs[BLUE]).intValue());
                                    BaseFont bf = BaseFont.createFont((String)objs[FONT_NAME], BaseFont.WINANSI, true);
                                    cb.setFontAndSize(bf, ((Float)objs[FONT_SIZE]).floatValue());
                                    cb.setTextMatrix(((Float)objs[X]).floatValue(), ((Float)objs[Y]).floatValue());
                                    cb.showText((String)objs[TEXT]);

                                    cb.setRGBColorFill(((Integer)objs[RED]).intValue(), ((Integer)objs[GREEN]).intValue(), ((Integer)objs[BLUE]).intValue());
                                    cb.setFontAndSize(bf, ((Float)objs[FONT_SIZE]).floatValue()+2);
                                    cb.setTextMatrix((((Float)objs[X]).floatValue())+55, ((Float)objs[Y]).floatValue());
                                    cb.showText("Sample");
/* to right here */

                              }
                              cb.endText();
                        }
                        document.newPage();
                  }
                  document.close();
                  /* System.out.println("Finished."); */
            }
            catch(Exception e) {
                  e.printStackTrace();
            }
      }


    /**
     * @param args the command line arguments
     */
    public void getPdfFields() {
        /* if (args.length < 1) {
            System.err.println("Dumps the field positions of a PDF document.");
            System.err.println("The output format is a text file where the first line is the field");
            System.err.println("field_name page x1 y1");
            System.err.println("This is repeated for each field.");
            System.err.println("usage: java getPdfFields pdf_file");
            return;
        } */
        try {
            PdfReader reader = new PdfReader(inFormPdf);
            /* PrintWriter out = new PrintWriter(new FileOutputStream(outPdf)); */
            PRAcroForm form = reader.getAcroForm();
            if (form == null) {
                        /* out.close(); */
                System.out.println("This document has no fields.");
            }
            PdfLister list = new PdfLister(System.out);
            HashMap refToField = new HashMap();
            ArrayList fields = form.getFields();
            String tmpStr;
            String fName;
            for (int k = 0; k < fields.size(); ++k) {
                PRAcroForm.FieldInformation field = (PRAcroForm.FieldInformation)fields.get(k);
                refToField.put(new Integer(field.getRef().getNumber()), field);
            }
            for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
                fieldHashMap = new HashMap();
                PdfDictionary dPage = reader.getPageN(page);
                PdfArray annots = (PdfArray)reader.getPdfObject((PdfObject)dPage.get(PdfName.ANNOTS));
                if (annots == null)
                    continue;
                ArrayList ali = annots.getArrayList();
                for (int annot = 0; annot < ali.size(); ++annot) {
                    PdfObject refObj = (PdfObject)ali.get(annot);
                    PRIndirectReference ref = null;
                    PdfDictionary an = (PdfDictionary)reader.getPdfObject(refObj);
                    PdfName name = (PdfName)an.get(PdfName.SUBTYPE);
                    tmpStr = "";
                    fName = "";
                    if (name == null || !name.equals(PdfName.WIDGET))
                        continue;
                    PdfArray rect = (PdfArray)reader.getPdfObject(an.get(PdfName.RECT));
                    PRAcroForm.FieldInformation field = null;
                    while (an != null) {
                        PdfString tName = (PdfString)an.get(PdfName.T);
                        if (tName != null)
                            fName = tName.toString() + "." + fName;
                        if (refObj.type() == PdfObject.INDIRECT && field == null) {
                            ref = (PRIndirectReference)refObj;
                            field = (PRAcroForm.FieldInformation)refToField.get(new Integer(ref.getNumber()));
                        }
                        refObj = (PdfObject)an.get(PdfName.PARENT);
                        an = (PdfDictionary)reader.getPdfObject(refObj);
                    }
                    if (fName.endsWith("."))
                        fName = fName.substring(0, fName.length() - 1);
                    /* System.out.println(fName); */
                    /*out.print(page); */

                    ArrayList arr = rect.getArrayList();
                    tmpStr = "";
                    for (int r = 0; r < 2; ++r) {
                        PdfNumber num = (PdfNumber)reader.getPdfObject((PdfObject)arr.get(r));
                        /* out.print(" " + num.floatValue()); */
                          tmpStr = tmpStr + " " + num.floatValue();
                    }
                    tmpStr = tmpStr + " Helvetica 9 0 0 0";
                    System.out.println(fName+" "+page+" "+tmpStr);
                    fieldHashMap.put(fName,page+" "+tmpStr);

                }
            }
            /* out.close();
            System.out.println("Finished."+fieldMap); */

        }
        catch(Exception e) {
            e.printStackTrace();

        }
    }

}




USE THIS TO RUN THIS CLASS ...

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;


public class dothis4 {

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

            pasteTextToPdf pasteIt = new pasteTextToPdf("sales2.pdf","out.pdf","out2.pdf");

            pasteIt.getPdfFields();
            pasteIt.FillBlanks();
      }



}
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month11 days, 11 hours left to enroll

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question