KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pdfbox > TextToPDF


1 /**
2  * Copyright (c) 2005, 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;
32
33 import java.io.BufferedReader JavaDoc;
34 import java.io.File JavaDoc;
35 import java.io.FileReader JavaDoc;
36 import java.io.IOException JavaDoc;
37 import java.io.Reader JavaDoc;
38
39 import org.pdfbox.pdmodel.PDDocument;
40 import org.pdfbox.pdmodel.PDPage;
41
42 import org.pdfbox.pdmodel.edit.PDPageContentStream;
43 import org.pdfbox.pdmodel.font.PDSimpleFont;
44 import org.pdfbox.pdmodel.font.PDTrueTypeFont;
45 import org.pdfbox.pdmodel.font.PDType1Font;
46
47
48 /**
49  * This will take a text file and ouput a pdf with that text.
50  *
51  * @author <a HREF="ben@benlitchfield.com">Ben Litchfield</a>
52  * @version $Revision: 1.4 $
53  */

54 public class TextToPDF
55 {
56     private int fontSize = 10;
57     private PDSimpleFont font = PDType1Font.HELVETICA;
58     
59     /**
60      * Create a PDF document with some text.
61      *
62      * @param text The stream of text data.
63      *
64      * @return The document with the text in it.
65      *
66      * @throws IOException If there is an error writing the data.
67      */

68     public PDDocument createPDFFromText( Reader JavaDoc text ) throws IOException JavaDoc
69     {
70         PDDocument doc = null;
71         try
72         {
73             
74             int margin = 40;
75             float height = font.getFontDescriptor().getFontBoundingBox().getHeight()/1000;
76             
77             //calculate font height and increase by 5 percent.
78
height = height*fontSize*1.05f;
79             doc = new PDDocument();
80             BufferedReader JavaDoc data = new BufferedReader JavaDoc( text );
81             String JavaDoc nextLine = null;
82             PDPage page = new PDPage();
83             PDPageContentStream contentStream = null;
84             float y = -1;
85             float maxStringLength = page.getMediaBox().getWidth() - 2*margin;
86             while( (nextLine = data.readLine()) != null )
87             {
88                 
89                 String JavaDoc[] lineWords = nextLine.trim().split( " " );
90                 int lineIndex = 0;
91                 while( lineIndex < lineWords.length )
92                 {
93                     StringBuffer JavaDoc nextLineToDraw = new StringBuffer JavaDoc();
94                     float lengthIfUsingNextWord = 0;
95                     do
96                     {
97                         nextLineToDraw.append( lineWords[lineIndex] );
98                         nextLineToDraw.append( " " );
99                         lineIndex++;
100                         if( lineIndex < lineWords.length )
101                         {
102                             String JavaDoc lineWithNextWord = nextLineToDraw.toString() + lineWords[lineIndex];
103                             lengthIfUsingNextWord =
104                                 (font.getStringWidth( lineWithNextWord )/1000) * fontSize;
105                         }
106                     }
107                     while( lineIndex < lineWords.length &&
108                            lengthIfUsingNextWord < maxStringLength );
109                     if( y < margin )
110                     {
111                         page = new PDPage();
112                         doc.addPage( page );
113                         if( contentStream != null )
114                         {
115                             contentStream.endText();
116                             contentStream.close();
117                         }
118                         contentStream = new PDPageContentStream(doc, page);
119                         contentStream.setFont( font, fontSize );
120                         contentStream.beginText();
121                         y = page.getMediaBox().getHeight() - margin + height;
122                         contentStream.moveTextPositionByAmount(
123                             margin, y );
124                         
125                     }
126                     //System.out.println( "Drawing string at " + x + "," + y );
127

128                     if( contentStream == null )
129                     {
130                         throw new IOException JavaDoc( "Error:Expected non-null content stream." );
131                     }
132                     contentStream.moveTextPositionByAmount( 0, -height);
133                     y -= height;
134                     contentStream.drawString( nextLineToDraw.toString() );
135                 }
136                 
137                 
138             }
139             if( contentStream != null )
140             {
141                 contentStream.endText();
142                 contentStream.close();
143             }
144         }
145         catch( IOException JavaDoc io )
146         {
147             if( doc != null )
148             {
149                 doc.close();
150             }
151             throw io;
152         }
153         return doc;
154     }
155
156     /**
157      * This will create a PDF document with a single image on it.
158      * <br />
159      * see usage() for commandline
160      *
161      * @param args Command line arguments.
162      *
163      * @throws IOException If there is an error with the PDF.
164      */

165     public static void main(String JavaDoc[] args) throws IOException JavaDoc
166     {
167         TextToPDF app = new TextToPDF();
168         PDDocument doc = null;
169         try
170         {
171             if( args.length < 2 )
172             {
173                 app.usage();
174             }
175             else
176             {
177                 for( int i=0; i<args.length-2; i++ )
178                 {
179                     if( args[i].equals( "-standardFont" ))
180                     {
181                         i++;
182                         app.setFont( PDType1Font.getStandardFont( args[i] ));
183                     }
184                     else if( args[i].equals( "-ttf" ))
185                     {
186                         i++;
187                         PDTrueTypeFont font = PDTrueTypeFont.loadTTF( doc, new File JavaDoc( args[i]));
188                         app.setFont( font );
189                     }
190                     else if( args[i].equals( "-fontSize" ))
191                     {
192                         i++;
193                         app.setFontSize( Integer.parseInt( args[i] ) );
194                     }
195                     else
196                     {
197                         throw new IOException JavaDoc( "Unknown argument:" + args[i] );
198                     }
199                 }
200                 doc = app.createPDFFromText( new FileReader JavaDoc( args[args.length-1] ) );
201                 doc.save( args[args.length-2] );
202             }
203         }
204         catch (Exception JavaDoc e)
205         {
206             e.printStackTrace();
207         }
208         finally
209         {
210             if( doc != null )
211             {
212                 doc.close();
213             }
214         }
215     }
216
217     /**
218      * This will print out a message telling how to use this example.
219      */

220     private void usage()
221     {
222         String JavaDoc[] std14 = PDType1Font.getStandard14Names();
223         System.err.println( "usage: " + this.getClass().getName() + " [options] <output-file> <text-file>" );
224         System.err.println( " -standardFont <name> default:" + PDType1Font.HELVETICA.getBaseFont() );
225         for( int i=0; i<std14.length; i++ )
226         {
227             System.err.println( " " + std14[i] );
228         }
229         System.err.println( " -ttf <ttf file> The TTF font to use.");
230         System.err.println( " -fontSize <fontSize> default:10" );
231         
232         
233     }
234     /**
235      * @return Returns the font.
236      */

237     public PDSimpleFont getFont()
238     {
239         return font;
240     }
241     /**
242      * @param aFont The font to set.
243      */

244     public void setFont(PDSimpleFont aFont)
245     {
246         this.font = aFont;
247     }
248     /**
249      * @return Returns the fontSize.
250      */

251     public int getFontSize()
252     {
253         return fontSize;
254     }
255     /**
256      * @param aFontSize The fontSize to set.
257      */

258     public void setFontSize(int aFontSize)
259     {
260         this.fontSize = aFontSize;
261     }
262 }
Popular Tags