KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jimm > datavision > layout > pdf > PDFLE


1 package jimm.datavision.layout.pdf;
2 import jimm.datavision.*;
3 import jimm.datavision.field.*;
4 import jimm.datavision.layout.LayoutEngine;
5 import jimm.datavision.layout.LineDrawer;
6 import jimm.util.StringUtils;
7 import java.io.OutputStream JavaDoc;
8 import java.util.*;
9 import com.lowagie.text.*;
10 import com.lowagie.text.pdf.*;
11
12 /**
13  * A PDF layout engine.
14  *
15  * @author Jim Menard, <a HREF="mailto:jimm@io.com">jimm@io.com</a>
16  */

17 public class PDFLE extends LayoutEngine implements LineDrawer {
18
19 protected OutputStream JavaDoc outStream;
20 protected Document doc;
21 protected PdfContentByte content;
22 protected HashMap baseFonts;
23 protected double prevThickness;
24
25
26 public PDFLE(OutputStream JavaDoc out) {
27     super(null);
28     outStream = out;
29 }
30
31 /**
32  * Outputs the beginning of the document.
33  */

34 protected void doStart() {
35     baseFonts = new HashMap();
36
37     PaperFormat fmt = report.getPaperFormat();
38     doc = new Document(new com.lowagie.text.Rectangle(0, 0,
39                               (int)fmt.getWidth(),
40                               (int)fmt.getHeight()),
41                (float)fmt.getImageableX(),
42                (float)(fmt.getWidth() + fmt.getImageableX()),
43                (float)fmt.getImageableY(),
44                (float)(fmt.getHeight() + fmt.getImageableY()));
45
46     PdfWriter writer = null;
47     try {
48     writer = PdfWriter.getInstance(doc, outStream);
49     baseFonts.put("Helvetica", BaseFont.createFont("Helvetica",
50                                BaseFont.CP1252,
51                                BaseFont.NOT_EMBEDDED));
52     }
53     catch (DocumentException e) {
54     ErrorHandler.error(e);
55     wantsMoreData = false; // Stop!
56
return;
57     }
58     catch (java.io.IOException JavaDoc ioe) {
59     ErrorHandler.error(ioe);
60     wantsMoreData = false; // Stop!
61
return;
62     }
63                
64     String JavaDoc str = null;
65     if ((str = report.getTitle()) != null)
66     doc.addTitle(str);
67     if ((str = report.getAuthor()) != null)
68     doc.addAuthor(str);
69     doc.addCreator("DataVision version " + info.Version
70            + " <" + info.URL + ">");
71     doc.addCreationDate();
72
73     doc.open();
74
75     content = writer.getDirectContent();
76 }
77
78 protected void doEnd() {
79     doc.close();
80 }
81
82 protected void doStartPage() {
83     try {
84     prevThickness = 0;
85     doc.newPage();
86     }
87     catch (DocumentException e) {
88     ErrorHandler.error(e);
89     wantsMoreData = false; // Stop!
90
}
91 }
92
93 /**
94  * Outputs a field.
95  *
96  * @param field the field to output
97  */

98 protected void doOutputField(Field field) {
99     String JavaDoc fieldAsString = field.toString();
100     if (fieldAsString == null || fieldAsString.length() == 0) {
101     makeBorders(field);
102     return;
103     }
104
105     Format format = field.getFormat();
106     BaseFont baseFont = getFontForFormat(format);
107     float fontSize = (float)format.getSize();
108
109     jimm.datavision.Point bottomLeft =
110     bottomLeftOfField(field, format.getSize(), baseFont);
111
112     int align;
113     switch (format.getAlign()) {
114     case Format.ALIGN_CENTER:
115     align = PdfContentByte.ALIGN_CENTER;
116     bottomLeft.x += field.getBounds().width / 2; // x is center of bounds
117
break;
118     case Format.ALIGN_RIGHT:
119     align = PdfContentByte.ALIGN_RIGHT;
120     bottomLeft.x += field.getBounds().width; // x is right side of bounds
121
break;
122     case Format.ALIGN_LEFT: // fall through
123
default:
124     align = PdfContentByte.ALIGN_LEFT;
125     break;
126     }
127
128     content.beginText();
129     content.setFontAndSize(baseFont, fontSize);
130     content.setColorFill(format.getColor());
131
132     java.util.List JavaDoc lines = StringUtils.splitIntoLines(fieldAsString);
133     double lineHeight = field.getOutputHeight() / lines.size();
134     for (Iterator iter = lines.iterator(); iter.hasNext(); ) {
135     String JavaDoc line = (String JavaDoc)iter.next();
136     content.showTextAligned(align, line, (float)bottomLeft.x,
137                 (float)bottomLeft.y, 0f);
138     bottomLeft.y -= lineHeight;
139     }
140
141     content.endText();
142
143     // Borders
144
makeBorders(field);
145 }
146
147 protected jimm.datavision.Point bottomLeftOfField(Field f, double size,
148                           BaseFont baseFont)
149 {
150     jimm.datavision.field.Rectangle r = f.getBounds();
151     jimm.datavision.Point bottomLeft = new jimm.datavision.Point(r.x, r.y);
152
153     // Translate to PDF coordinates, subtract (negative) font descent, and
154
// reflect vertically
155
translateToPDFCoords(bottomLeft);
156     bottomLeft.y -=
157     baseFont.getFontDescriptor(BaseFont.DESCENT, (float)size)
158     + r.height;
159
160     return bottomLeft;
161 }
162
163 protected void translateToPDFCoords(jimm.datavision.Point p) {
164     // Avoid setter methods; no one is observing this point
165
if (currentSection.getArea().getArea() != SectionArea.PAGE_FOOTER)
166     p.y = (pageHeight() - pageHeightUsed) - p.y;
167     else
168     p.y = currentSection.getOutputHeight() - p.y;
169 }
170
171 protected BaseFont getFontForFormat(Format f) {
172     String JavaDoc name = baseFontName(f.getFont());
173
174     BaseFont bf = (BaseFont)baseFonts.get(name);
175     if (bf == null) {
176     try {
177         bf = BaseFont.createFont(name, BaseFont.CP1252,
178                      BaseFont.NOT_EMBEDDED);
179         baseFonts.put(name, bf);
180     }
181     catch (Exception JavaDoc e) { // DocumentException or IOException
182
ErrorHandler.error(e);
183         bf = (BaseFont)baseFonts.get("Helvetica");
184     }
185     }
186     return bf;
187 }
188
189 protected String JavaDoc baseFontName(java.awt.Font JavaDoc font) {
190     String JavaDoc family = font.getFamily().toLowerCase();
191     if (family.startsWith("courier") || family.startsWith("monospace"))
192     return "Courier" + fontAttributes(font, "Bold", "Oblique");
193     else if (family.startsWith("helvetica") || family.startsWith("sansserif"))
194     return "Helvetica" + fontAttributes(font, "Bold", "Oblique");
195     else if (family.startsWith("symbol"))
196     return "Symbol";
197     else if (family.startsWith("zapfdingbats"))
198     return "ZapfDingbats";
199     else {
200     String JavaDoc fontAttrs = fontAttributes(font, "Bold", "Italic");
201     return "Times" + (fontAttrs.length() > 0 ? fontAttrs : "-Roman");
202     }
203 }
204
205 protected String JavaDoc fontAttributes(java.awt.Font JavaDoc font, String JavaDoc bold, String JavaDoc italic)
206 {
207     if (font.isBold() && font.isItalic())
208     return "-" + bold + italic;
209     else if (font.isBold())
210     return "-" + bold;
211     else if (font.isItalic())
212     return "-" + italic;
213     else
214     return "";
215 }
216
217 /**
218  * Ignores image output
219  *
220  * @param field an image field
221  */

222 protected void doOutputImage(ImageField field) {
223     try {
224     Image img = Image.getInstance(field.getImageURL());
225
226     // Translate to PDF coordinates and reflect vertically
227
jimm.datavision.field.Rectangle r = field.getBounds();
228     jimm.datavision.Point p = new jimm.datavision.Point(r.x, r.y);
229     translateToPDFCoords(p);
230     p.y -= field.getOutputHeight();
231
232     img.setAbsolutePosition((float)p.x, (float)p.y);
233     content.addImage(img);
234     }
235     catch (Exception JavaDoc e) { // DocumentException or MalformedURLException
236
wantsMoreData = false;
237     ErrorHandler.error(e);
238     }
239 }
240
241 /**
242  * Outputs a line. Calls {@link #drawLine}.
243  *
244  * @param line a line
245  */

246 protected void doOutputLine(Line line) {
247     drawLine(line, Boolean.TRUE);
248 }
249
250 /**
251  * Outputs borders.
252  */

253 protected void makeBorders(Field field) {
254     field.getBorderOrDefault().eachLine(this, Boolean.FALSE);
255     content.stroke();
256 }
257
258 /**
259  * Draw a single line.
260  *
261  * @param line a line
262  */

263 public void drawLine(Line line, Object JavaDoc arg) {
264     if (line.getThickness() != prevThickness) {
265     prevThickness = line.getThickness();
266     content.setLineWidth((float)prevThickness);
267     }
268     jimm.datavision.Point p0 = new jimm.datavision.Point(line.getPoint(0));
269     jimm.datavision.Point p1 = new jimm.datavision.Point(line.getPoint(1));
270     translateToPDFCoords(p0);
271     translateToPDFCoords(p1);
272     content.moveTo((float)p0.x, (float)p0.y);
273     content.lineTo((float)p1.x, (float)p1.y);
274     if (arg != Boolean.FALSE) // Yes "!=" instead of "equals"
275
content.stroke();
276 }
277
278 }
279
Popular Tags