KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pdfbox > examples > persistence > AppendAndFillDoc


1 /**
2  * Copyright (c) 2003, www.pdfbox.org
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright notice,
9  * this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  * 3. Neither the name of pdfbox; nor the names of its
14  * contributors may be used to endorse or promote products derived from this
15  * software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
24  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * http://www.pdfbox.org
29  *
30  */

31 package org.pdfbox.examples.persistence;
32
33 import java.io.IOException JavaDoc;
34 import java.io.OutputStream JavaDoc;
35 import java.io.FileOutputStream JavaDoc;
36 import java.io.InputStream JavaDoc;
37 import java.io.FileInputStream JavaDoc;
38
39 import java.util.Iterator JavaDoc;
40
41 import org.pdfbox.pdfparser.PDFParser;
42
43 import org.pdfbox.pdfwriter.COSWriter;
44
45 import org.pdfbox.cos.COSDocument;
46 import org.pdfbox.cos.COSString;
47 import org.pdfbox.cos.COSBase;
48 import org.pdfbox.cos.COSDictionary;
49 import org.pdfbox.cos.COSObject;
50 import org.pdfbox.cos.COSName;
51 import org.pdfbox.cos.COSArray;
52 import org.pdfbox.cos.COSNumber;
53 import org.pdfbox.cos.COSInteger;
54
55 import org.pdfbox.exceptions.COSVisitorException;
56
57 /**
58  * This concatenates two documents with fields and fills the fields in the two templates using different
59  * values.
60  *
61  * @author Michael Traut
62  * @version $Revision: 1.6 $
63  */

64 public class AppendAndFillDoc
65 {
66     /**
67      * Constructor.
68      */

69     public AppendAndFillDoc()
70     {
71         super();
72     }
73
74     /**
75      * Append all pages from source to destination.
76      *
77      * todo: this method will go to the pdfmodel package one day
78      *
79      * @param destination the document to receive the pages
80      * @param source the document originating the new pages
81      *
82      */

83     public void appendDocument(COSDocument destination, COSDocument source)
84     {
85         COSDictionary pages2 = getPages(source);
86         COSArray kids = (COSArray)pages2.getItem(COSName.getPDFName("Kids"));
87         for (Iterator JavaDoc i = kids.iterator(); i.hasNext();)
88         {
89             COSDictionary page = (COSDictionary)((COSObject)i.next()).getObject();
90             appendPage(destination, page);
91         }
92     }
93     /**
94      * append a page dict to destination.
95      *
96      * todo: this method will go to the pdfmodel package one day
97      *
98      * @param destination the document to receive the page
99      * @param page the page to append to the document
100      *
101      */

102     public void appendPage(COSDocument destination, COSDictionary page)
103     {
104         // get the parent object (pages dictionary)
105
COSDictionary pages = getPages(destination);
106         // and set in the page object
107
page.setItem(COSName.PARENT, pages);
108         // add new page to kids entry in the pages dictionary
109
COSArray kids = (COSArray) pages.getItem(COSName.getPDFName("Kids"));
110         kids.add(page);
111         // and increase count
112
COSNumber count = (COSNumber) pages.getItem(COSName.COUNT);
113         pages.setItem(COSName.COUNT, new COSInteger(count.intValue() + 1));
114     }
115     /**
116      * concat two pdf documents and fill fields in both templates
117      * this is a bit tricky as one has to rename the fields if we use the same template two times.
118      * here we don't user a clever algorithm to create dynamic fieldnames - this is left to the user..
119      *
120      * @param in1 The first template file
121      * @param in2 The second template file
122      * @param out The created fiel with all pages from document one and document two
123      * @param name1 The name of the PDF field (FDF field) in the first template
124      * @param value1 The value to be used for the field in the first template
125      * @param name2 The name of the PDF field (FDF field) in the second template
126      * @param value2 The value to be used for the field in the second template
127      *
128      * @throws IOException If there is an error writing the data.
129      * @throws COSVisitorException If there is an error generating the PDF document.
130      */

131     public void doIt( String JavaDoc in1,
132                       String JavaDoc in2,
133                       String JavaDoc out,
134                       String JavaDoc name1,
135                       String JavaDoc value1,
136                       String JavaDoc name2,
137                       String JavaDoc value2) throws IOException JavaDoc, COSVisitorException
138     {
139         COSDocument doc1 = null;
140         COSDocument doc2 = null;
141         InputStream JavaDoc is1 = null;
142         InputStream JavaDoc is2 = null;
143         PDFParser parser1 = null;
144         PDFParser parser2 = null;
145
146         OutputStream JavaDoc os = null;
147         COSWriter writer = null;
148         try
149         {
150             is1 = new FileInputStream JavaDoc(in1);
151             parser1 = new PDFParser(is1);
152             parser1.parse();
153             doc1 = parser1.getDocument();
154
155             is2 = new FileInputStream JavaDoc(in2);
156             parser2 = new PDFParser(is2);
157             parser2.parse();
158             doc2 = parser2.getDocument();
159
160             setField(doc1, "doc1", new COSString(name1), new COSString(value1));
161             setField(doc2, "doc2", new COSString(name2), new COSString(value2));
162
163             appendDocument(doc1, doc2);
164
165             os = new FileOutputStream JavaDoc(out);
166             writer = new COSWriter(os);
167             writer.write(doc1);
168         }
169         finally
170         {
171             is1.close();
172             doc1.close();
173
174             is2.close();
175             doc2.close();
176
177             os.close();
178             writer.close();
179         }
180     }
181
182     /**
183      * Lookup the pages dictionary in a document.
184      *
185      * todo: this method will go to the pdfmodel package one day
186      *
187      * @param doc the document where the pages dict is searched
188      *
189      * @return The Pages dictionary.
190      */

191     public COSDictionary getPages(COSDocument doc)
192     {
193         // todo should access via catalog instead!
194
for (Iterator JavaDoc i = doc.getObjects().iterator(); i.hasNext();)
195         {
196             COSObject obj = (COSObject) i.next();
197             COSBase base = obj.getObject();
198             if (base instanceof COSDictionary)
199             {
200                 COSDictionary dict = (COSDictionary) base;
201                 COSBase type = dict.getItem(COSName.TYPE);
202                 if (type != null && type.equals(COSName.getPDFName("Pages")))
203                 {
204                     return dict;
205                 }
206             }
207         }
208         return null;
209     }
210     /**
211      * This will concat two pdf documents and fill fields in both.
212      * <br />
213      * see usage() for commandline
214      *
215      * @param args command line arguments
216      */

217     public static void main(String JavaDoc[] args)
218     {
219         AppendAndFillDoc app = new AppendAndFillDoc();
220         try
221         {
222             if( args.length != 7 )
223             {
224                 app.usage();
225             }
226             else
227             {
228                 app.doIt( args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
229             }
230         }
231         catch (Exception JavaDoc e)
232         {
233             e.printStackTrace();
234         }
235     }
236     /**
237      * lookup and fill the field.
238      *
239      * todo: this method will go to the pdfmodel package one day
240      *
241      * @param doc the document where the field resides
242      * @param prefix a prefix to use to make the field name unique in the new document
243      * @param name the name of the PDF Annotation field
244      * @param value The desired value to be used for the field
245      *
246      */

247     public void setField(COSDocument doc, String JavaDoc prefix, COSString name, COSString value)
248     {
249         for (Iterator JavaDoc i = doc.getObjects().iterator(); i.hasNext();)
250         {
251             COSObject obj = (COSObject) i.next();
252             COSBase base = obj.getObject();
253             if (base instanceof COSDictionary)
254             {
255                 COSDictionary dict = (COSDictionary) base;
256                 COSBase type = dict.getItem(COSName.TYPE);
257                 if (type != null && type.equals(COSName.getPDFName("Annot")))
258                 {
259                     COSBase subtype = dict.getItem(COSName.getPDFName("Subtype"));
260                     if (subtype != null && subtype.equals(COSName.getPDFName("Widget")))
261                     {
262                         // we found the field
263
COSBase fname = dict.getItem(COSName.getPDFName("T"));
264                         if (fname != null && fname.equals(name))
265                         {
266                             dict.setItem(COSName.getPDFName("V"), value);
267                             dict.setItem(COSName.getPDFName("T"), new COSString(prefix + name.getString()));
268                         }
269                     }
270                 }
271             }
272         }
273     }
274     /**
275      * This will print out a message telling how to use this example.
276      */

277     private void usage()
278     {
279         System.err.println( "usage: " + this.getClass().getName() +
280         " <input-file1> <input-file2> <output-file> <name1> <value1> <name2> <value2>" );
281     }
282 }
Popular Tags