KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lowagie > text > pdf > FdfWriter


1 /*
2  * Copyright 2003 by Paulo Soares.
3  *
4  * The contents of this file are subject to the Mozilla Public License Version 1.1
5  * (the "License"); you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
7  *
8  * Software distributed under the License is distributed on an "AS IS" basis,
9  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
10  * for the specific language governing rights and limitations under the License.
11  *
12  * The Original Code is 'iText, a free JAVA-PDF library'.
13  *
14  * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
15  * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
16  * All Rights Reserved.
17  * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
18  * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
19  *
20  * Contributor(s): all the names of the contributors are added in the source code
21  * where applicable.
22  *
23  * Alternatively, the contents of this file may be used under the terms of the
24  * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
25  * provisions of LGPL are applicable instead of those above. If you wish to
26  * allow use of your version of this file only under the terms of the LGPL
27  * License and not to allow others to use your version of this file under
28  * the MPL, indicate your decision by deleting the provisions above and
29  * replace them with the notice and other provisions required by the LGPL.
30  * If you do not delete the provisions above, a recipient may use your version
31  * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
32  *
33  * This library is free software; you can redistribute it and/or modify it
34  * under the terms of the MPL as stated above or under the terms of the GNU
35  * Library General Public License as published by the Free Software Foundation;
36  * either version 2 of the License, or any later version.
37  *
38  * This library is distributed in the hope that it will be useful, but WITHOUT
39  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
40  * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
41  * details.
42  *
43  * If you didn't download this code from the following link, you should check if
44  * you aren't using an obsolete version:
45  * http://www.lowagie.com/iText/
46  */

47 package com.lowagie.text.pdf;
48
49 import java.io.IOException JavaDoc;
50 import java.io.OutputStream JavaDoc;
51 import java.util.ArrayList JavaDoc;
52 import java.util.HashMap JavaDoc;
53 import java.util.Iterator JavaDoc;
54 import java.util.Map JavaDoc;
55 import java.util.StringTokenizer JavaDoc;
56
57 import com.lowagie.text.DocWriter;
58
59 /** Writes an FDF form.
60  * @author Paulo Soares (psoares@consiste.pt)
61  */

62 public class FdfWriter {
63     private static final byte[] HEADER_FDF = DocWriter.getISOBytes("%FDF-1.2\n%\u00e2\u00e3\u00cf\u00d3\n");
64     HashMap JavaDoc fields = new HashMap JavaDoc();
65
66     /** The PDF file associated with the FDF. */
67     private String JavaDoc file;
68     
69     /** Creates a new FdfWriter. */
70     public FdfWriter() {
71     }
72
73     /** Writes the content to a stream.
74      * @param os the stream
75      * @throws IOException on error
76      */

77     public void writeTo(OutputStream JavaDoc os) throws IOException JavaDoc {
78         Wrt wrt = new Wrt(os, this);
79         wrt.writeTo();
80     }
81     
82     boolean setField(String JavaDoc field, PdfObject value) {
83         HashMap JavaDoc map = fields;
84         StringTokenizer JavaDoc tk = new StringTokenizer JavaDoc(field, ".");
85         if (!tk.hasMoreTokens())
86             return false;
87         while (true) {
88             String JavaDoc s = tk.nextToken();
89             Object JavaDoc obj = map.get(s);
90             if (tk.hasMoreTokens()) {
91                 if (obj == null) {
92                     obj = new HashMap JavaDoc();
93                     map.put(s, obj);
94                     map = (HashMap JavaDoc)obj;
95                     continue;
96                 }
97                 else if (obj instanceof HashMap JavaDoc)
98                     map = (HashMap JavaDoc)obj;
99                 else
100                     return false;
101             }
102             else {
103                 if (!(obj instanceof HashMap JavaDoc)) {
104                     map.put(s, value);
105                     return true;
106                 }
107                 else
108                     return false;
109             }
110         }
111     }
112     
113     void iterateFields(HashMap JavaDoc values, HashMap JavaDoc map, String JavaDoc name) {
114         for (Iterator JavaDoc it = map.entrySet().iterator(); it.hasNext();) {
115             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
116             String JavaDoc s = (String JavaDoc) entry.getKey();
117             Object JavaDoc obj = entry.getValue();
118             if (obj instanceof HashMap JavaDoc)
119                 iterateFields(values, (HashMap JavaDoc)obj, name + "." + s);
120             else
121                 values.put((name + "." + s).substring(1), obj);
122         }
123     }
124     
125     /** Removes the field value.
126      * @param field the field name
127      * @return <CODE>true</CODE> if the field was found and removed,
128      * <CODE>false</CODE> otherwise
129      */

130     public boolean removeField(String JavaDoc field) {
131         HashMap JavaDoc map = fields;
132         StringTokenizer JavaDoc tk = new StringTokenizer JavaDoc(field, ".");
133         if (!tk.hasMoreTokens())
134             return false;
135         ArrayList JavaDoc hist = new ArrayList JavaDoc();
136         while (true) {
137             String JavaDoc s = tk.nextToken();
138             Object JavaDoc obj = map.get(s);
139             if (obj == null)
140                 return false;
141             hist.add(map);
142             hist.add(s);
143             if (tk.hasMoreTokens()) {
144                 if (obj instanceof HashMap JavaDoc)
145                     map = (HashMap JavaDoc)obj;
146                 else
147                     return false;
148             }
149             else {
150                 if (obj instanceof HashMap JavaDoc)
151                     return false;
152                 else
153                     break;
154             }
155         }
156         for (int k = hist.size() - 2; k >= 0; k -= 2) {
157             map = (HashMap JavaDoc)hist.get(k);
158             String JavaDoc s = (String JavaDoc)hist.get(k + 1);
159             map.remove(s);
160             if (!map.isEmpty())
161                 break;
162         }
163         return true;
164     }
165     
166     /** Gets all the fields. The map is keyed by the fully qualified
167      * field name and the values are <CODE>PdfObject</CODE>.
168      * @return a map with all the fields
169      */

170     public HashMap JavaDoc getFields() {
171         HashMap JavaDoc values = new HashMap JavaDoc();
172         iterateFields(values, fields, "");
173         return values;
174     }
175     
176     /** Gets the field value.
177      * @param field the field name
178      * @return the field value or <CODE>null</CODE> if not found
179      */

180     public String JavaDoc getField(String JavaDoc field) {
181         HashMap JavaDoc map = fields;
182         StringTokenizer JavaDoc tk = new StringTokenizer JavaDoc(field, ".");
183         if (!tk.hasMoreTokens())
184             return null;
185         while (true) {
186             String JavaDoc s = tk.nextToken();
187             Object JavaDoc obj = map.get(s);
188             if (obj == null)
189                 return null;
190             if (tk.hasMoreTokens()) {
191                 if (obj instanceof HashMap JavaDoc)
192                     map = (HashMap JavaDoc)obj;
193                 else
194                     return null;
195             }
196             else {
197                 if (obj instanceof HashMap JavaDoc)
198                     return null;
199                 else {
200                     if (((PdfObject)obj).isString())
201                         return ((PdfString)obj).toUnicodeString();
202                     else
203                         return PdfName.decodeName(obj.toString());
204                 }
205             }
206         }
207     }
208     
209     /** Sets the field value as a name.
210      * @param field the fully qualified field name
211      * @param value the value
212      * @return <CODE>true</CODE> if the value was inserted,
213      * <CODE>false</CODE> if the name is incompatible with
214      * an existing field
215      */

216     public boolean setFieldAsName(String JavaDoc field, String JavaDoc value) {
217         return setField(field, new PdfName(value));
218     }
219     
220     /** Sets the field value as a string.
221      * @param field the fully qualified field name
222      * @param value the value
223      * @return <CODE>true</CODE> if the value was inserted,
224      * <CODE>false</CODE> if the name is incompatible with
225      * an existing field
226      */

227     public boolean setFieldAsString(String JavaDoc field, String JavaDoc value) {
228         return setField(field, new PdfString(value, PdfObject.TEXT_UNICODE));
229     }
230     
231     /** Sets all the fields from this <CODE>FdfReader</CODE>
232      * @param fdf the <CODE>FdfReader</CODE>
233      */

234     public void setFields(FdfReader fdf) {
235         HashMap JavaDoc map = fdf.getFields();
236         for (Iterator JavaDoc it = map.entrySet().iterator(); it.hasNext();) {
237             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
238             String JavaDoc key = (String JavaDoc) entry.getKey();
239             PdfDictionary dic = (PdfDictionary) entry.getValue();
240             PdfObject v = dic.get(PdfName.V);
241             if (v != null) {
242                 setField(key, v);
243             }
244         }
245     }
246     
247     /** Sets all the fields from this <CODE>PdfReader</CODE>
248      * @param pdf the <CODE>PdfReader</CODE>
249      */

250     public void setFields(PdfReader pdf) {
251         setFields(pdf.getAcroFields());
252     }
253     
254     /** Sets all the fields from this <CODE>AcroFields</CODE>
255      * @param af the <CODE>AcroFields</CODE>
256      */

257     public void setFields(AcroFields af) {
258         for (Iterator JavaDoc it = af.getFields().entrySet().iterator(); it.hasNext();) {
259             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)it.next();
260             String JavaDoc fn = (String JavaDoc)entry.getKey();
261             AcroFields.Item item = (AcroFields.Item)entry.getValue();
262             PdfDictionary dic = (PdfDictionary)item.merged.get(0);
263             PdfObject v = PdfReader.getPdfObjectRelease(dic.get(PdfName.V));
264             if (v == null)
265                 continue;
266             PdfObject ft = PdfReader.getPdfObjectRelease(dic.get(PdfName.FT));
267             if (ft == null || PdfName.SIG.equals(ft))
268                 continue;
269             setField(fn, v);
270         }
271     }
272     
273     /** Gets the PDF file name associated with the FDF.
274      * @return the PDF file name associated with the FDF
275      */

276     public String JavaDoc getFile() {
277         return this.file;
278     }
279     
280     /** Sets the PDF file name associated with the FDF.
281      * @param file the PDF file name associated with the FDF
282      *
283      */

284     public void setFile(String JavaDoc file) {
285         this.file = file;
286     }
287     
288     static class Wrt extends PdfWriter {
289         private FdfWriter fdf;
290        
291         Wrt(OutputStream JavaDoc os, FdfWriter fdf) throws IOException JavaDoc {
292             super(new PdfDocument(), os);
293             this.fdf = fdf;
294             this.os.write(HEADER_FDF);
295             body = new PdfBody(this);
296         }
297         
298         void writeTo() throws IOException JavaDoc {
299             PdfDictionary dic = new PdfDictionary();
300             dic.put(PdfName.FIELDS, calculate(fdf.fields));
301             if (fdf.file != null)
302                 dic.put(PdfName.F, new PdfString(fdf.file, PdfObject.TEXT_UNICODE));
303             PdfDictionary fd = new PdfDictionary();
304             fd.put(PdfName.FDF, dic);
305             PdfIndirectReference ref = addToBody(fd).getIndirectReference();
306             os.write(getISOBytes("trailer\n"));
307             PdfDictionary trailer = new PdfDictionary();
308             trailer.put(PdfName.ROOT, ref);
309             trailer.toPdf(null, os);
310             os.write(getISOBytes("\n%%EOF\n"));
311             os.close();
312         }
313         
314         
315         PdfArray calculate(HashMap JavaDoc map) throws IOException JavaDoc {
316             PdfArray ar = new PdfArray();
317             for (Iterator JavaDoc it = map.entrySet().iterator(); it.hasNext();) {
318                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
319                 String JavaDoc key = (String JavaDoc) entry.getKey();
320                 Object JavaDoc v = entry.getValue();
321                 PdfDictionary dic = new PdfDictionary();
322                 dic.put(PdfName.T, new PdfString(key, PdfObject.TEXT_UNICODE));
323                 if (v instanceof HashMap JavaDoc) {
324                     dic.put(PdfName.KIDS, calculate((HashMap JavaDoc)v));
325                 }
326                 else {
327                     dic.put(PdfName.V, (PdfObject)v);
328                 }
329                 ar.add(dic);
330             }
331             return ar;
332         }
333     }
334 }
335
Popular Tags