KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > fop > render > txt > TXTRenderer


1 /*
2  * $Id: TXTRenderer.java,v 1.12.2.11 2003/03/02 16:55:18 pietsch Exp $
3  * ============================================================================
4  * The Apache Software License, Version 1.1
5  * ============================================================================
6  *
7  * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without modifica-
10  * tion, are permitted provided that the following conditions are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if any, must
20  * include the following acknowledgment: "This product includes software
21  * developed by the Apache Software Foundation (http://www.apache.org/)."
22  * Alternately, this acknowledgment may appear in the software itself, if
23  * and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "FOP" and "Apache Software Foundation" must not be used to
26  * endorse or promote products derived from this software without prior
27  * written permission. For written permission, please contact
28  * apache@apache.org.
29  *
30  * 5. Products derived from this software may not be called "Apache", nor may
31  * "Apache" appear in their name, without prior written permission of the
32  * Apache Software Foundation.
33  *
34  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
35  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
36  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
37  * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
38  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
39  * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
40  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
41  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  * ============================================================================
45  *
46  * This software consists of voluntary contributions made by many individuals
47  * on behalf of the Apache Software Foundation and was originally created by
48  * James Tauber <jtauber@jtauber.com>. For more information on the Apache
49  * Software Foundation, please see <http://www.apache.org/>.
50  */

51 package org.apache.fop.render.txt;
52
53 // FOP
54
import org.apache.fop.render.PrintRenderer;
55 import org.apache.fop.fo.properties.*;
56 import org.apache.fop.image.FopImage;
57 import org.apache.fop.image.FopImageException;
58 import org.apache.fop.layout.*;
59 import org.apache.fop.layout.inline.*;
60 import org.apache.fop.datatypes.*;
61 import org.apache.fop.pdf.PDFPathPaint;
62 import org.apache.fop.pdf.PDFColor;
63 import org.apache.fop.image.*;
64
65 import org.apache.fop.svg.SVGArea;
66
67 import org.w3c.dom.svg.SVGSVGElement;
68 import org.w3c.dom.svg.SVGDocument;
69
70 // Java
71
import java.io.IOException JavaDoc;
72 import java.io.OutputStream JavaDoc;
73 import java.util.List JavaDoc;
74
75 /**
76  * Renderer that renders areas to plain text.
77  *
78  * @author Art Welch
79  * @author <a HREF="mailto:mark-fop@inomial.com">Mark Lillywhite</a> (to use
80  * the new Renderer interface)
81  */

82 public class TXTRenderer extends PrintRenderer {
83
84     /**
85      * the current stream to add Text commands to
86      */

87     TXTStream currentStream;
88     public static final String JavaDoc encodingOptionName = "txt.encoding";
89     private static final String JavaDoc DEFAULT_ENCODING = "UTF-8";
90
91     private int pageHeight = 7920;
92
93     // These variables control the virtual paggination functionality.
94
public int curdiv = 0;
95     private int divisions = -1;
96     private int paperheight = -1; // Paper height in decipoints?
97
public int orientation =
98         -1; // -1=default/unknown, 0=portrait, 1=landscape.
99
public int topmargin = -1; // Top margin in decipoints?
100
public int leftmargin = -1; // Left margin in decipoints?
101
private int fullmargin = 0;
102     final boolean debug = false;
103
104     // Variables for rendering text.
105
StringBuffer JavaDoc charData[];
106     StringBuffer JavaDoc decoData[];
107     public float textCPI = 16.67f;
108     public float textLPI = 8;
109     int maxX = (int)(8.5f * textCPI + 1);
110     int maxY = (int)(11f * textLPI + 1);
111     float xFactor;
112     float yFactor;
113     public String JavaDoc lineEnding =
114         "\r\n"; // Every line except the last line on a page (which will end with pageEnding) will be terminated with this string.
115
public String JavaDoc pageEnding =
116         "\f"; // Every page except the last one will end with this string.
117
public boolean suppressGraphics =
118         false; // If true then graphics/decorations will not be rendered - text only.
119
boolean firstPage = false;
120     /**
121      * options
122      */

123     protected java.util.Map JavaDoc options;
124
125     public TXTRenderer() {}
126
127     /**
128      * set up renderer options
129      */

130     public void setOptions(java.util.Map JavaDoc options) {
131         this.options = options;
132     }
133
134     /**
135      * set the TXT document's producer
136      *
137      * @param producer string indicating application producing PDF
138      */

139     public void setProducer(String JavaDoc producer) {}
140
141
142     void addStr(int row, int col, String JavaDoc str, boolean ischar) {
143         if (debug)
144             System.out.println("TXTRenderer.addStr(" + row + ", " + col
145                                + ", \"" + str + "\", " + ischar + ")");
146         if (suppressGraphics &&!ischar)
147             return;
148         StringBuffer JavaDoc sb;
149         if (row < 0)
150             row = 0;
151         if (ischar)
152             sb = charData[row];
153         else
154             sb = decoData[row];
155         if (sb == null)
156             sb = new StringBuffer JavaDoc();
157         if ((col + str.length()) > maxX)
158             col = maxX - str.length();
159         if (col < 0) {
160             col = 0;
161             if (str.length() > maxX)
162                 str = str.substring(0, maxX);
163         }
164         // Pad to col
165
for (int countr = sb.length(); countr < col; countr++)
166             sb.append(' ');
167         if (debug)
168             System.out.println("TXTRenderer.addStr() sb.length()="
169                                + sb.length());
170         for (int countr = col; countr < (col + str.length()); countr++) {
171             if (countr >= sb.length())
172                 sb.append(str.charAt(countr - col));
173             else {
174                 if (debug)
175                     System.out.println("TXTRenderer.addStr() sb.length()="
176                                        + sb.length() + " countr=" + countr);
177                 sb.setCharAt(countr, str.charAt(countr - col));
178             }
179         }
180
181         if (ischar)
182             charData[row] = sb;
183         else
184             decoData[row] = sb;
185     }
186
187     /**
188      * add a line to the current stream
189      *
190      * @param x1 the start x location in millipoints
191      * @param y1 the start y location in millipoints
192      * @param x2 the end x location in millipoints
193      * @param y2 the end y location in millipoints
194      * @param th the thickness in millipoints
195      * @param stroke the line color
196      */

197     protected void addLine(int x1, int y1, int x2, int y2, int th,
198                            PDFPathPaint stroke) {
199         if (x1 == x2) {
200             addRect(x1, y1, th, y2 - y1 + 1, stroke, stroke);
201         } else if (y1 == y2) {
202             addRect(x1, y1, x2 - x1 + 1, th, stroke, stroke);
203         }
204     }
205
206     /**
207      * add a line to the current stream
208      *
209      * @param x1 the start x location in millipoints
210      * @param y1 the start y location in millipoints
211      * @param x2 the end x location in millipoints
212      * @param y2 the end y location in millipoints
213      * @param th the thickness in millipoints
214      * @param rs the rule style
215      * @param stroke the line color
216      */

217     protected void addLine(int x1, int y1, int x2, int y2, int th, int rs,
218                            PDFPathPaint stroke) {
219         PDFColor lstroke = null;
220         if (rs == org.apache.fop.fo.properties.RuleStyle.DOTTED)
221             lstroke = new PDFColor(0.7f, 0.7f, 0.7f);
222         else
223             lstroke = (PDFColor)stroke;
224         if (x1 == x2) {
225             addRect(x1, y1, th, y2 - y1 + 1, lstroke, lstroke);
226         } else if (y1 == y2) {
227             addRect(x1, y1, x2 - x1 + 1, th, lstroke, lstroke);
228         }
229     }
230
231     protected void addLine(float x1, float y1, float x2, float y2,
232                            PDFColor sc, float sw) {
233         /*
234          * SVG - Not yet implemented
235          * if ( debug )
236          * System.out.println("TXTRenderer.addLine(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + ", " + sc + ", " + sw + ")");
237          * if ( x1 == x2 )
238          * {
239          * addRect(x1 - sw/2, y1, sw, y2 - y1 + 1, 0, 0, sc, null, 0);
240          * }
241          * else if ( y1 == y2 || (Math.abs(y1 - y2) <= 0.24) ) // 72/300=0.24
242          * {
243          * addRect(x1, y1 - sw/2, x2 - x1 + 1, sw, 0, 0, sc, null, 0);
244          * }
245          * else if ( sc != null )
246          * {
247          * // Convert dimensions to characters.
248          * //float cfact = 300f / 72f; // 300 dpi, 1pt=1/72in
249          * int ix1 = (int)(x1 * xFactor);
250          * int iy1 = (int)(y1 * yFactor);
251          * int ix2 = (int)(x2 * xFactor);
252          * int iy2 = (int)(y2 * yFactor);
253          * int isw = (int)(sw * xFactor);
254          * int origix;
255          * // Normalize
256          * if ( iy1 > iy2 )
257          * {
258          * int tmp = ix1;
259          * ix1 = ix2;
260          * ix2 = tmp;
261          * tmp = iy1;
262          * iy1 = iy2;
263          * iy2 = tmp;
264          * }
265          * if ( ix1 > ix2 )
266          * {
267          * origix = ix2;
268          * ix1 -=ix2;
269          * ix2 = 0;
270          * }
271          * else
272          * {
273          * origix = ix1;
274          * ix2 -= ix1;
275          * ix1 = 0;
276          * }
277          * // Convert line width to a pixel run length.
278          * //System.out.println("TXTRenderer.addLine(" + ix1 + ", " + iy1 + ", " + ix2 + ", " + iy2 + ", " + isw + ")");
279          * int runlen = (int)Math.sqrt(Math.pow(isw, 2) * (1 + Math.pow((ix1 - ix2) / (iy1 - iy2), 2)));
280          * if ( runlen < 1 )
281          * runlen = 1;
282          * StringBuffer rlbuff = new StringBuffer();
283          * for ( int countr = 0 ; countr < runlen ; countr++ )
284          * rlbuff.append('*');
285          * String rlstr = rlbuff.toString();
286          * //System.out.println("TXTRenderer.addLine: runlen = " + runlen);
287          * // Draw the line.
288          * int d, dx, dy;
289          * int Aincr, Bincr;
290          * int xincr = 1;
291          * int x, y;
292          * dx = Math.abs(ix2 - ix1);
293          * dy = iy2 - iy1;
294          * if ( dx > dy )
295          * {
296          * xincr = dx / dy;
297          * // Move to starting position.
298          * //currentStream.add("\033*p" + origix + "x" + iy1 + "Y");
299          * x = ix1 - runlen / 2;
300          * iy2 += (isw / 2);
301          * // Start raster graphics
302          * //currentStream.add("\033*t300R\033*r" + dx + "s1A\033*b1M");
303          * }
304          * else
305          * {
306          * // Move to starting position.
307          * //currentStream.add("\033*p" + (origix - runlen / 2) + "x" + iy1 + "Y");
308          * x = ix1;
309          * // Start raster graphics
310          * //currentStream.add("\033*t300R\033*r1A\033*b1M");
311          * }
312          * if ( ix1 > ix2 )
313          * xincr *= -1;
314          * d = 2 * dx - dy;
315          * Aincr = 2 * (dx - dy);
316          * Bincr = 2 * dx;
317          * y = iy1;
318          * xferLineBytes(x, runlen, null, -1);
319          *
320          * for ( y = iy1 + 1 ; y <= iy2 ; y++ )
321          * {
322          * if ( d >= 0 )
323          * {
324          * x += xincr;
325          * d += Aincr;
326          * }
327          * else
328          * d += Bincr;
329          * xferLineBytes(x, runlen, null, -1);
330          * }
331          * // End raster graphics
332          * //currentStream.add("\033*rB");
333          * // Return to regular print mode.
334          * //currentStream.add("\033*v0t0n0O");
335          * }
336          */

337     }
338
339     private void xferLineBytes(int startpos, int bitcount, List JavaDoc save,
340                                int start2) {
341         /*
342          * Not yet implemented
343          * //System.out.println("TXTRenderer.xferLineBytes(" + startpos + ", " + bitcount + ")");
344          * int curbitpos = 0;
345          * if ( start2 > 0 && start2 <= (startpos + bitcount) )
346          * {
347          * bitcount += (start2 - startpos);
348          * start2 = 0;
349          * }
350          * char bytes[] = new char[((start2>startpos?start2:startpos) + bitcount) / 4 + 2];
351          * int dlen = 0;
352          * byte dbyte = 0;
353          * int bytepos = 0;
354          * do
355          * {
356          * int bits2set;
357          * if ( startpos < 0 )
358          * {
359          * bits2set = bitcount + startpos;
360          * startpos = 0;
361          * }
362          * else
363          * bits2set = bitcount;
364          * byte bittype = 0;
365          * do
366          * {
367          * if ( bytepos > 0 )
368          * {
369          * int inc = startpos - curbitpos;
370          * if ( (inc) >= (8 - bytepos) )
371          * {
372          * curbitpos += (8 - bytepos);
373          * bytepos = 0;
374          * bytes[dlen++] = (char)0;
375          * bytes[dlen++] = (char)dbyte;
376          * dbyte = 0;
377          * }
378          * else
379          * {
380          * bytepos += inc;
381          * dbyte = (byte)(dbyte ^ (byte)(Math.pow(2, 8 - bytepos) - 1));
382          * curbitpos += inc;
383          * }
384          * }
385          * // Set runs of whole bytes.
386          * int setbytes = (startpos - curbitpos) / 8;
387          * if ( setbytes > 0 )
388          * {
389          * curbitpos += setbytes * 8;
390          * while ( setbytes > 0 )
391          * {
392          * if ( setbytes > 256 )
393          * {
394          * bytes[dlen++] = 0xFF;
395          * setbytes -= 256;
396          * }
397          * else
398          * {
399          * bytes[dlen++] = (char)((setbytes - 1) & 0xFF);
400          * setbytes = 0;
401          * }
402          * bytes[dlen++] = (char)bittype;
403          * }
404          * }
405          * // move to position in the first byte.
406          * if ( curbitpos < startpos )
407          * {
408          * if ( bytepos == 0 )
409          * dbyte = bittype;
410          * bytepos += startpos - curbitpos;
411          * dbyte = (byte)(dbyte ^ (byte)(Math.pow(2, 8 - bytepos) - 1));
412          * curbitpos += bytepos;
413          * startpos += bits2set;
414          * }
415          * else
416          * {
417          * startpos += bits2set;
418          * }
419          * if ( bittype == 0 )
420          * bittype = (byte)0xFF;
421          * else
422          * bittype = 7;
423          * } while ( bittype != 7 );
424          * if ( start2 > 0 )
425          * {
426          * startpos = start2;
427          * start2 = -1;
428          * }
429          * else
430          * startpos = -1;
431          * } while ( startpos >= 0 );
432          * if ( bytepos > 0 )
433          * {
434          * bytes[dlen++] = (char)0;
435          * bytes[dlen++] = (char)dbyte;
436          * }
437          * if ( save == null )
438          * {
439          * //currentStream.add("\033*b" + dlen + "W");
440          * //currentStream.add(new String(bytes, 0, dlen));
441          * }
442          * else
443          * {
444          * String line = "\033*b" + dlen + "W" + new String(bytes, 0, dlen);
445          * //currentStream.add(line);
446          * save.add(line);
447          * }
448          */

449     }
450
451     /**
452      * add a rectangle to the current stream
453      *
454      * @param x the x position of left edge in millipoints
455      * @param y the y position of top edge in millipoints
456      * @param w the width in millipoints
457      * @param h the height in millipoints
458      * @param stroke the stroke color/gradient
459      */

460     protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke) {
461         if (h < 0)
462             h *= -1;
463
464         if (h < 720 || w < 720) {
465             if (w < 720)
466                 w = 720;
467             if (h < 720)
468                 h = 720;
469             addRect(x, y, w, h, stroke, stroke);
470         } else {
471             addRect(x, y, w, 720, stroke, stroke);
472             addRect(x, y, 720, h, stroke, stroke);
473             addRect(x + w - 720, y, 720, h, stroke, stroke);
474             addRect(x, y - h + 720, w, 720, stroke, stroke);
475         }
476     }
477
478     /**
479      * add a filled rectangle to the current stream
480      *
481      * @param x the x position of left edge in millipoints
482      * @param y the y position of top edge in millipoints
483      * @param w the width in millipoints
484      * @param h the height in millipoints
485      * @param fill the fill color/gradient
486      * @param stroke the stroke color/gradient
487      */

488     protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke,
489                            PDFPathPaint fill) {
490         // System.out.println("TXTRenderer.addRect(" + x + ", " + y + ", " + w + ", " + h + ", " + r + ", " + g + ", " + b + ", " + fr + ", " + fg + ", " + fb + ")");
491
if ((w == 0) || (h == 0))
492             return;
493         if (h < 0)
494             h *= -1;
495
496         int row = (int)((pageHeight - (y / 100)) * 100 * yFactor);
497         int col = (int)(x * xFactor);
498
499         PDFColor sc = (PDFColor)stroke;
500         PDFColor fc = (PDFColor)fill;
501
502         sc.setColorSpace(ColorSpace.DEVICE_RGB);
503         fc.setColorSpace(ColorSpace.DEVICE_RGB);
504
505         int lineshade =
506             (int)(100
507                   - ((0.3f * sc.red() + 0.59f * sc.green() + 0.11f * sc.blue())
508                      * 100f));
509         int fillshade =
510             (int)(100
511                   - ((0.3f * fc.red() + 0.59f * fc.green() + 0.11f * fc.blue())
512                      * 100f));
513         if (debug)
514             System.out.println("TXTRenderer.addRect(" + x + ", " + y + ", "
515                                + w + ", " + h + ", " + stroke + ", " + fill
516                                + ") fillshade=" + fillshade);
517         char fillchar = ' ';
518         if (fillshade >= 75)
519             fillchar = '#';
520         else if (fillshade >= 50)
521             fillchar = '*';
522         else if (fillshade >= 25)
523             fillchar = ':';
524
525
526         if (fillchar != ' ') {
527             StringBuffer JavaDoc linefill = new StringBuffer JavaDoc();
528             int sw = (int)(w * xFactor);
529             int sh = (int)(h * yFactor);
530             if (sw == 0 || sh == 0) {
531                 if (fillshade >= 50) {
532                     if (h > w)
533                         fillchar = '|';
534                     else
535                         fillchar = '-';
536                 } else {
537                     if (h > w)
538                         fillchar = ':';
539                     else
540                         fillchar = '.';
541                 }
542             }
543             if (sw == 0)
544                 linefill.append(fillchar);
545             else
546                 for (int countr = 0; countr < sw; countr++)
547                     linefill.append(fillchar);
548             if (sh == 0)
549                 addStr(row, col, linefill.toString(), false);
550             else
551                 for (int countr = 0; countr < sh; countr++)
552                     addStr(row + countr, col, linefill.toString(), false);
553         }
554
555         if (lineshade >= 25) {
556             char vlinechar = '|';
557             char hlinechar = '-';
558             if (lineshade < 50) {
559                 vlinechar = ':';
560                 hlinechar = '.';
561             }
562             StringBuffer JavaDoc linefill = new StringBuffer JavaDoc();
563             int sw = (int)(w * xFactor);
564             for (int countr = 0; countr < sw; countr++)
565                 linefill.append(hlinechar);
566             int sh = (int)(h * yFactor);
567
568             if (w > h) {
569                 for (int countr = 1; countr < (sh - 1); countr++) {
570                     addStr(row + countr, col, String.valueOf(vlinechar),
571                            false);
572                     addStr(row + countr, col + sw, String.valueOf(vlinechar),
573                            false);
574                 }
575                 addStr(row, col, linefill.toString(), false);
576                 addStr(row + sh, col, linefill.toString(), false);
577
578             } else {
579                 addStr(row, col, linefill.toString(), false);
580                 addStr(row + sh, col, linefill.toString(), false);
581                 for (int countr = 1; countr < (sh - 1); countr++) {
582                     addStr(row + countr, col, String.valueOf(vlinechar),
583                            false);
584                     addStr(row + countr, col + sw, String.valueOf(vlinechar),
585                            false);
586                 }
587
588             }
589         }
590     }
591
592
593     /**
594      * add a filled rectangle to the current stream
595      *
596      * @param x the x position of left edge in millipoints
597      * @param y the y position of top edge in millipoints
598      * @param w the width in millipoints
599      * @param h the height in millipoints
600      * @param r the red component of edges
601      * @param g the green component of edges
602      * @param b the blue component of edges
603      * @param fr the red component of the fill
604      * @param fg the green component of the fill
605      * @param fb the blue component of the fill
606      */

607     protected void addRect(float x, float y, float w, float h, float rx,
608                            float ry, PDFColor fc, PDFColor sc, float sw) {
609         /*
610          * SVG - Not yet implemented
611          * if ( debug )
612          * System.out.println("TXTRenderer.addRect(" + x + ", " + y + ", " + w + ", " + h + ", " + rx + ", " + ry + ", " + fc + ", " + sc + ", " + sw + ")");
613          * float sr = 1;
614          * float sg = 1;
615          * float sb = 1;
616          * float fr = 1;
617          * float fg = 1;
618          * float fb = 1;
619          * if ( sc != null && sw > 0 )
620          * {
621          * sr = (float)sc.red();
622          * sg = (float)sc.green();
623          * sb = (float)sc.blue();
624          * }
625          * if ( fc != null )
626          * {
627          * fr = (float)fc.red();
628          * fg = (float)fc.green();
629          * fb = (float)fc.blue();
630          * }
631          * addRect((int)(x * 1000), (int)(pageHeight * 100 - y * 1000), (int)(w * 1000), (int)(h * 1000), sr, sg, sb, fr, fg, fb);
632          * fc = null;
633          * sc = null;
634          * if ( rx == 0 || ry == 0 )
635          * {
636          * if ( fc != null )
637          * {
638          * int fillshade = (int)(100 - ((0.3f * fc.red() + 0.59f * fc.green() + 0.11f * fc.blue()) * 100f));
639          * currentStream.add("\033*v0n1O\033&a" + (x * 10) + "h" + ((y * 10)) + "V"
640          * + "\033*c" + (w * 10) + "h" + (h * 10) + "v" + fillshade + "g2P\033*v0n0O");
641          * }
642          * if ( sc != null && sw > 0 )
643          * {
644          * String lend = "v" + String.valueOf((int)(100 - ((0.3f * sc.red() + 0.59f * sc.green() + 0.11f * sc.blue()) * 100f))) + "g2P";
645          * currentStream.add("\033*v0n1O");
646          * currentStream.add("\033&a" + ((x - sw/2) * 10) + "h" + (((y - sw/2)) * 10) + "V"
647          * + "\033*c" + ((w + sw) * 10) + "h" + ((sw) * 10) + lend);
648          * currentStream.add("\033&a" + ((x - sw/2) * 10) + "h" + (((y - sw/2)) * 10) + "V"
649          * + "\033*c" + ((sw) * 10) + "h" + ((h + sw) * 10) + lend);
650          * currentStream.add("\033&a" + ((x + w - sw/2) * 10) + "h" + (((y - sw/2)) * 10) + "V"
651          * + "\033*c" + ((sw) * 10) + "h" + ((h + sw) * 10) + lend);
652          * currentStream.add("\033&a" + ((x - sw/2) * 10) + "h" + (((y + h - sw/2)) * 10) + "V"
653          * + "\033*c" + ((w + sw) * 10) + "h" + ((sw) * 10) + lend);
654          * currentStream.add("\033*v0n0O");
655          * }
656          * }
657          * else
658          * {
659          * // Convert dimensions to pixels.
660          * float cfact = 300f / 72f; // 300 dpi, 1pt=1/72in
661          * int ix = (int)(x * cfact);
662          * int iy = (int)(y * cfact);
663          * int iw = (int)(w * cfact);
664          * int ih = (int)(h * cfact);
665          * int irx = (int)(rx * cfact);
666          * int iry = (int)(ry * cfact);
667          * int isw = (int)(sw * cfact);
668          * int longwidth = 0;
669          * int pass = 0;
670          * PDFColor thecolor = null;
671          * do
672          * {
673          * if ( pass == 0 && fc != null )
674          * {
675          * thecolor = fc;
676          * }
677          * else if ( pass == 1 && sc != null )
678          * {
679          * int iswdiv2 = isw / 2;
680          * thecolor = sc;
681          * ix -= iswdiv2;
682          * iy -= iswdiv2;
683          * irx += iswdiv2;
684          * iry += iswdiv2;
685          * iw += isw;
686          * ih += isw;
687          * longwidth = (int)(isw * 1.414);
688          * }
689          * else
690          * thecolor = null;
691          * if ( thecolor != null )
692          * {
693          * int tx = 0;
694          * int ty = iry;
695          * long a = irx;
696          * long b = iry;
697          * long Asquared = (long)Math.pow(a, 2);
698          * long TwoAsquared = 2 * Asquared;
699          * long Bsquared = (long)Math.pow(b, 2);
700          * long TwoBsquared = 2 * Bsquared;
701          * long d = Bsquared - Asquared * b + Asquared / 4;
702          * long dx = 0;
703          * long dy = TwoAsquared * b;
704          * int rectlen = iw - 2 * irx;
705          * List bottomlines = new java.util.ArrayList();
706          * int x0 = tx;
707          * // Set Transparency modes and select shading.
708          * currentStream.add("\033*v0n1O\033*c" + (int)(100 - ((0.3f * thecolor.red() + 0.59f * thecolor.green() + 0.11f * thecolor.blue()) * 100f)) + "G\033*v2T");
709          * // Move to starting position.
710          * currentStream.add("\033*p" + ix + "x" + iy + "Y");
711          * // Start raster graphics
712          * currentStream.add("\033*t300R\033*r" + iw + "s1A\033*b1M");
713          * while ( dx < dy )
714          * {
715          * if ( d > 0 )
716          * {
717          * if ( pass == 0 || ty > (iry - isw) )
718          * xferLineBytes(irx - x0, rectlen + 2 * x0, bottomlines, -1);
719          * else
720          * xferLineBytes(irx - x0, longwidth, bottomlines, iw - irx + x0 - longwidth);
721          * x0 = tx + 1;
722          * ty--;
723          * dy -= TwoAsquared;
724          * d -= dy;
725          * }
726          * tx++;
727          * dx += TwoBsquared;
728          * d += Bsquared + dx;
729          * }
730          * d += (3 * (Asquared - Bsquared) / 2 - (dx + dy)) / 2;
731          * while ( ty > 0 )
732          * {
733          * if ( pass == 0 || ty >= (iry - isw) )
734          * xferLineBytes(irx - tx, rectlen + 2 * tx, bottomlines, -1);
735          * else
736          * xferLineBytes(irx - tx, isw, bottomlines, iw - irx + tx - isw);
737          *
738          * if ( d < 0 )
739          * {
740          * tx++;
741          * dx += TwoBsquared;
742          * d += dx;
743          * }
744          * ty--;
745          * dy -= TwoAsquared;
746          * d += Asquared - dy;
747          * }
748          * // Draw the middle part of the rectangle
749          * int midlen = ih - 2 * iry;
750          * if ( midlen > 0 )
751          * {
752          * if ( pass == 0 )
753          * xferLineBytes(0, iw, null, -1);
754          * else
755          * xferLineBytes(0, isw, null, iw - isw);
756          * currentStream.add("\033*b3M");
757          * for ( int countr = midlen - 1 ; countr > 0 ; countr-- )
758          * currentStream.add("\033*b0W");
759          * currentStream.add("\033*b1M");
760          * }
761          * // Draw the bottom.
762          * for ( int countr = bottomlines.size() - 1 ; countr >= 0 ; countr-- )
763          * currentStream.add((String)bottomlines.get(countr));
764          * // End raster graphics
765          * currentStream.add("\033*rB");
766          * // Return to regular print mode.
767          * currentStream.add("\033*v0t0n0O");
768          * }
769          * pass++;
770          * } while ( pass < 2 );
771          * }
772          */

773     }
774
775     // Add a polyline or polygon. Does not support fills yet!!!
776
protected void addPolyline(List JavaDoc points, int posx, int posy,
777                                PDFColor fc, PDFColor sc, float sw,
778                                boolean close) {}
779
780     /**
781      * Renders an image, scaling it to the given width and height.
782      * If the scaled width and height is the same intrinsic size
783      * of the image, the image is not scaled.
784      *
785      * @param x the x position of left edge in millipoints
786      * @param y the y position of top edge in millipoints
787      * @param w the width in millipoints
788      * @param h the height in millipoints
789      * @param image the image to be rendered
790      * @param fs the font state to use when rendering text
791      * in non-bitmapped images.
792      */

793     protected void drawImageScaled(int x, int y, int w, int h,
794                    FopImage image,
795                    FontState fs) {
796     // XXX: implement this
797
}
798
799     /**
800      * Renders an image, clipping it as specified.
801      *
802      * @param x the x position of left edge in millipoints.
803      * @param y the y position of top edge in millipoints.
804      * @param clipX the left edge of the clip in millipoints
805      * @param clipY the top edge of the clip in millipoints
806      * @param clipW the clip width in millipoints
807      * @param clipH the clip height in millipoints
808      * @param fill the image to be rendered
809      * @param fs the font state to use when rendering text
810      * in non-bitmapped images.
811      */

812     protected void drawImageClipped(int x, int y,
813                     int clipX, int clipY,
814                     int clipW, int clipH,
815                     FopImage image,
816                     FontState fs) {
817     // XXX: implement this
818
}
819
820     boolean printBMP(FopImage img, int x, int y, int w,
821                      int h) throws FopImageException {
822         if (debug)
823             System.out.println("TXTRenderer.printBMP(" + img + ", " + x
824                                + ", " + y + ", " + w + ", " + h + ")");
825         addRect(x, y, w, h, new PDFColor(1f, 1f, 1f),
826                 new PDFColor(0f, 0f, 0f));
827         int nameh = (int)(h * yFactor / 2);
828         if (nameh > 0) {
829             int namew = (int)(w * xFactor);
830
831             if (namew > 4) {
832                 String JavaDoc iname = img.getURL();
833                 if (iname.length() >= namew)
834                     addStr((int)((pageHeight - (y / 100)) * 100 * yFactor)
835                            + nameh, (int)(x * xFactor),
836                            iname.substring(iname.length() - namew),
837                            true);
838                 else
839                     addStr((int)((pageHeight - (y / 100)) * 100 * yFactor)
840                            + nameh, (int)(x * xFactor
841                                           + (namew - iname.length())
842                                           / 2), iname, true);
843
844             }
845         }
846         return (true);
847     }
848
849     /**
850      * render image area to PCL
851      *
852      * @param area the image area to render
853      */

854     public void renderImageArea(ImageArea area) {
855         int x = this.currentAreaContainerXPosition + area.getXOffset();
856         int y = this.currentYPosition;
857         int w = area.getContentWidth();
858         int h = area.getHeight();
859
860         this.currentYPosition -= h;
861
862         FopImage img = area.getImage();
863
864         try {
865             printBMP(img, x, y, w, h);
866         } catch (FopImageException e) {
867             // e.printStackTrace(System.out);
868
log.error("TXTRenderer.renderImageArea() printing BMP ("
869                                    + e.toString() + ").", e);
870         }
871     }
872
873     public void renderImage(FontState fontState, String JavaDoc href, float x,
874                             float y, float width, float height) {
875         try {
876             if (href.indexOf(":") == -1)
877                 href = "file:" + href;
878             FopImage img = FopImageFactory.Make(href);
879             if (img != null) {
880                 if (img instanceof SVGImage) {
881                     SVGSVGElement svg =
882                         ((SVGImage)img).getSVGDocument().getRootElement();
883                     renderSVG(fontState, svg, (int)x * 1000, (int)y * 1000);
884                 } else {
885                     printBMP(img, (int)x, (int)y, (int)width, (int)height);
886                 }
887             }
888         } catch (Exception JavaDoc e) {
889             log.error("could not add image to SVG: " + href, e);
890         }
891     }
892
893     /**
894      * render a foreign object area
895      */

896     public void renderForeignObjectArea(ForeignObjectArea area) {
897         // if necessary need to scale and align the content
898
this.currentXPosition = this.currentXPosition + area.getXOffset();
899         this.currentYPosition = this.currentYPosition;
900         switch (area.getAlign()) {
901         case TextAlign.START:
902             break;
903         case TextAlign.END:
904             break;
905         case TextAlign.CENTER:
906         case TextAlign.JUSTIFY:
907             break;
908         }
909         switch (area.getVerticalAlign()) {
910         case VerticalAlign.BASELINE:
911             break;
912         case VerticalAlign.MIDDLE:
913             break;
914         case VerticalAlign.SUB:
915             break;
916         case VerticalAlign.SUPER:
917             break;
918         case VerticalAlign.TEXT_TOP:
919             break;
920         case VerticalAlign.TEXT_BOTTOM:
921             break;
922         case VerticalAlign.TOP:
923             break;
924         case VerticalAlign.BOTTOM:
925             break;
926         }
927         // in general the content will not be text
928

929         // align and scale
930

931         switch (area.scalingMethod()) {
932         case Scaling.UNIFORM:
933             break;
934         case Scaling.NON_UNIFORM:
935             break;
936         }
937         // if the overflow is auto (default), scroll or visible
938
// then the contents should not be clipped, since this
939
// is considered a printing medium.
940
switch (area.getOverflow()) {
941         case Overflow.VISIBLE:
942         case Overflow.SCROLL:
943         case Overflow.AUTO:
944             break;
945         case Overflow.HIDDEN:
946             break;
947         }
948         area.getObject().render(this);
949
950         this.currentXPosition += area.getEffectiveWidth();
951         // this.currentYPosition -= area.getEffectiveHeight();
952
}
953
954
955     void renderSVG(FontState fontState, SVGSVGElement svg, int x, int y) {
956         /*
957          * SVG - Not yet implemented
958          * NodeList nl = svg.getChildNodes();
959          * for(int count = 0; count < nl.getLength(); count++) {
960          * Node n = nl.item(count);
961          * if(n instanceof SVGElement) {
962          * renderElement(fontState, (SVGElement)n, x, y);
963          * }
964          * }
965          */

966     }
967
968     /**
969      * render SVG area to Text
970      *
971      * @param area the SVG area to render
972      */

973     public void renderSVGArea(SVGArea area) {
974         if (debug)
975             System.out.println("TXTRenderer.renderSVGArea(" + area + ")");
976         int x = this.currentAreaContainerXPosition;
977         int y = this.currentYPosition;
978         SVGSVGElement svg =
979             ((SVGDocument)area.getSVGDocument()).getRootElement();
980         int w = (int)(svg.getWidth().getBaseVal().getValue() * 1000);
981         int h = (int)(svg.getHeight().getBaseVal().getValue() * 1000);
982
983         // currentStream.add("ET\n");
984
/*
985          * Clip to the svg area.
986          * Note: To have the svg overlay (under) a text area then use
987          * an fo:block-container
988          */

989         // currentStream.add("q\n");
990
// currentStream.add(x / 1000f + " " + y / 1000f + " m\n");
991
// currentStream.add((x + w) / 1000f + " " + y / 1000f + " l\n");
992
// currentStream.add((x + w) / 1000f + " " + (y - h) / 1000f + " l\n");
993
// currentStream.add(x / 1000f + " " + (y - h) / 1000f + " l\n");
994
// currentStream.add("h\n");
995
// currentStream.add("W\n");
996
// currentStream.add("n\n");
997
// transform so that the coordinates (0,0) is from the top left
998
// and positive is down and to the right
999
// currentStream.add(1 + " " + 0 + " " + 0 + " " + (-1) + " " + x / 1000f + " " + y / 1000f + " cm\n");
1000

1001        // TODO - translate and clip to viewbox
1002

1003        renderSVG(area.getFontState(), svg, x, y);
1004
1005        // Enumeration e = area.getChildren().elements();
1006
// while (e.hasMoreElements()) {
1007
// Object o = e.nextElement();
1008
// if(o instanceof GraphicImpl) {
1009
// renderElement(area, (GraphicImpl)o, x, y);
1010
// }
1011
// }
1012

1013        // currentStream.add("Q\n");
1014
// currentStream.add("BT\n");
1015
// this.currentYPosition -= h;
1016
}
1017
1018    /*
1019     * SVG - Not yet implemented
1020     * public void renderElement(FontState fontState, SVGElement area, int posx, int posy)
1021     * {
1022     * if ( debug )
1023     * System.out.println("TXTRenderer.renderElement(" + fontState + ", " + area + ", " + posx + ", " + posy + ")");
1024     * int x = posx;
1025     * int y = posy;
1026     * CSSStyleDeclaration style = null;
1027     * if ( area instanceof SVGStylable )
1028     * style = ((SVGStylable)area).getStyle();
1029     * PDFColor fillColour = null;
1030     * PDFColor strokeColour = null;
1031     * float strokeWidth = 0;
1032     * //currentStream.add("q\n");
1033     * //if( area instanceof SVGTransformable ) {
1034     * // SVGTransformable tf = (SVGTransformable)area;
1035     * // SVGAnimatedTransformList trans = tf.getTransform();
1036     * // SVGRect bbox = tf.getBBox();
1037     * // if(trans != null) {
1038     * // applyTransform(trans, bbox);
1039     * // }
1040     * //}
1041     * if(style != null)
1042     * {
1043     * CSSValue sp = style.getPropertyCSSValue("fill");
1044     * if(sp != null)
1045     * {
1046     * if( sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
1047     * {
1048     * if( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_RGBCOLOR )
1049     * {
1050     * RGBColor col = ((CSSPrimitiveValue)sp).getRGBColorValue();
1051     * CSSPrimitiveValue val;
1052     * val = col.getRed();
1053     * float red = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
1054     * val = col.getGreen();
1055     * float green = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
1056     * val = col.getBlue();
1057     * float blue = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
1058     * fillColour = new PDFColor(red, green, blue);
1059     * }
1060     * }
1061     * //if(sp instanceof ColorType)
1062     * //{
1063     * // ColorType ct = (ColorType)sp;
1064     * // fillColour = new PDFColor(ct.red(), ct.green(), ct.blue());
1065     * //}
1066     * }
1067     * else
1068     * fillColour = new PDFColor(0, 0, 0);
1069     * sp = style.getPropertyCSSValue("stroke");
1070     * if(sp != null)
1071     * {
1072     * if( sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
1073     * {
1074     * if( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_RGBCOLOR )
1075     * {
1076     * RGBColor col = ((CSSPrimitiveValue)sp).getRGBColorValue();
1077     * CSSPrimitiveValue val;
1078     * val = col.getRed();
1079     * float red = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
1080     * val = col.getGreen();
1081     * float green = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
1082     * val = col.getBlue();
1083     * float blue = val.getFloatValue(CSSPrimitiveValue.CSS_NUMBER);
1084     * strokeColour = new PDFColor(red, green, blue);
1085     * }
1086     * }
1087     * //if(sp instanceof ColorType)
1088     * //{
1089     * // ColorType ct = (ColorType)sp;
1090     * // strokeColour = new PDFColor(ct.red(), ct.green(), ct.blue());
1091     * //}
1092     * }
1093     * sp = style.getPropertyCSSValue("stroke-width");
1094     * if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE)
1095     * {
1096     * strokeWidth = ((CSSPrimitiveValue)sp).getFloatValue(CSSPrimitiveValue.CSS_PT);
1097     * //PDFNumber pdfNumber = new PDFNumber();
1098     * //currentStream.add(pdfNumber.doubleOut(width) + " w\n");
1099     * //strokeWidth = ((SVGLengthImpl)sp).getValue();
1100     * }
1101     * else
1102     * strokeWidth = 1;
1103     * }
1104     * if (area instanceof SVGRectElement)
1105     * {
1106     * SVGRectElement rg = (SVGRectElement)area;
1107     * float rectx = rg.getX().getBaseVal().getValue() + posx / 1000;
1108     * float recty = ((pageHeight / 10) - posy/1000) + rg.getY().getBaseVal().getValue();
1109     * float rx = rg.getRx().getBaseVal().getValue();
1110     * float ry = rg.getRy().getBaseVal().getValue();
1111     * float rw = rg.getWidth().getBaseVal().getValue();
1112     * float rh = rg.getHeight().getBaseVal().getValue();
1113     * addRect(rectx, recty, rw, rh, rx, ry, fillColour, strokeColour, strokeWidth);
1114     * }
1115     * else if (area instanceof SVGLineElement)
1116     * {
1117     * SVGLineElement lg = (SVGLineElement)area;
1118     * float x1 = lg.getX1().getBaseVal().getValue() + posx / 1000;
1119     * float y1 = ((pageHeight / 10) - posy/1000) + lg.getY1().getBaseVal().getValue();
1120     * float x2 = lg.getX2().getBaseVal().getValue() + posx / 1000;
1121     * float y2 = ((pageHeight / 10) - posy/1000) + lg.getY2().getBaseVal().getValue();
1122     * addLine(x1,y1,x2,y2, strokeColour, strokeWidth);
1123     * }
1124     * else if (area instanceof SVGTextElementImpl)
1125     * {
1126     * //currentStream.add("BT\n");
1127     * renderText(fontState, (SVGTextElementImpl)area, posx / 1000f, ((float)(pageHeight / 10) - posy/1000f));
1128     * //currentStream.add("ET\n");
1129     * }
1130     * else if (area instanceof SVGCircleElement)
1131     * {
1132     * SVGCircleElement cg = (SVGCircleElement)area;
1133     * float cx = cg.getCx().getBaseVal().getValue() + posx / 1000;
1134     * float cy = ((pageHeight / 10) - posy/1000) + cg.getCy().getBaseVal().getValue();
1135     * float r = cg.getR().getBaseVal().getValue();
1136     * //addCircle(cx,cy,r, di);
1137     * addRect(cx - r, cy - r, 2 * r, 2 * r, r, r, fillColour, strokeColour, strokeWidth);
1138     * }
1139     * else if (area instanceof SVGEllipseElement)
1140     * {
1141     * SVGEllipseElement cg = (SVGEllipseElement)area;
1142     * float cx = cg.getCx().getBaseVal().getValue() + posx / 1000;
1143     * float cy = ((pageHeight / 10) - posy/1000) + cg.getCy().getBaseVal().getValue();
1144     * float rx = cg.getRx().getBaseVal().getValue();
1145     * float ry = cg.getRy().getBaseVal().getValue();
1146     * //addEllipse(cx,cy,rx,ry, di);
1147     * addRect(cx - rx, cy - ry, 2 * rx, 2 * ry, rx, ry, fillColour, strokeColour, strokeWidth);
1148     * }
1149     * else if (area instanceof SVGPathElementImpl)
1150     * {
1151     * //addPath(((SVGPathElementImpl)area).pathElements, posx, posy, di);
1152     * }
1153     * else if (area instanceof SVGPolylineElementImpl)
1154     * {
1155     * addPolyline(((SVGPolylineElementImpl)area).points, posx, posy, fillColour, strokeColour, strokeWidth, false);
1156     * }
1157     * else if (area instanceof SVGPolygonElementImpl)
1158     * {
1159     * addPolyline(((SVGPolylineElementImpl)area).points, posx, posy, fillColour, strokeColour, strokeWidth, true);
1160     * }
1161     * else if (area instanceof SVGGElementImpl)
1162     * {
1163     * renderGArea(fontState, (SVGGElementImpl)area, x, y);
1164     * }
1165     * else if(area instanceof SVGUseElementImpl)
1166     * {
1167     * SVGUseElementImpl ug = (SVGUseElementImpl)area;
1168     * String ref = ug.link;
1169     * ref = ref.substring(1, ref.length());
1170     * SVGElement graph = null;
1171     * //GraphicImpl graph = null;
1172     * //graph = area.locateDef(ref);
1173     * if(graph != null) {
1174     * // probably not the best way to do this, should be able
1175     * // to render without the style being set.
1176     * //GraphicImpl parent = graph.getGraphicParent();
1177     * //graph.setParent(area);
1178     * // need to clip (if necessary) to the use area
1179     * // the style of the linked element is as if is was
1180     * // a direct descendant of the use element.
1181     * renderElement(fontState, graph, posx, posy);
1182     * //graph.setParent(parent);
1183     * }
1184     * }
1185     * else if (area instanceof SVGImageElementImpl)
1186     * {
1187     * SVGImageElementImpl ig = (SVGImageElementImpl)area;
1188     * renderImage(fontState, ig.link, ig.x, ig.y, ig.width, ig.height);
1189     * }
1190     * else if (area instanceof SVGSVGElement)
1191     * {
1192     * // the x and y pos will be wrong!
1193     * renderSVG(fontState, (SVGSVGElement)area, x, y);
1194     * }
1195     * else if (area instanceof SVGAElement)
1196     * {
1197     * SVGAElement ael = (SVGAElement)area;
1198     * org.w3c.dom.NodeList nl = ael.getChildNodes();
1199     * for ( int count = 0 ; count < nl.getLength() ; count++ )
1200     * {
1201     * org.w3c.dom.Node n = nl.item(count);
1202     * if ( n instanceof SVGElement )
1203     * {
1204     * if ( n instanceof GraphicElement )
1205     * {
1206     * SVGRect rect = ((GraphicElement)n).getBBox();
1207     * if ( rect != null )
1208     * {
1209     * // currentAnnotList = this.pdfDoc.makeAnnotList();
1210     * // currentPage.setAnnotList(currentAnnotList);
1211     * // String dest = linkSet.getDest();
1212     * // int linkType = linkSet.getLinkType();
1213     * // currentAnnotList.addLink(
1214     * // this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType));
1215     * // currentAnnotList = null;
1216     * //}
1217     * }
1218     * renderElement(fontState, (SVGElement)n, posx, posy);
1219     * }
1220     * }
1221     * }
1222     * else if ( area instanceof SVGSwitchElement )
1223     * {
1224     * handleSwitchElement(fontState, posx, posy, (SVGSwitchElement)area);
1225     * }
1226     * // should be done with some cleanup code, so only
1227     * // required values are reset.
1228     * //currentStream.add("Q\n");
1229     * }
1230     */

1231
1232    private void setFont(String JavaDoc name, float size) {
1233        return;
1234    }
1235
1236    /*
1237     * SVG - Not implemented yet.
1238     * public void renderText(FontState fontState, SVGTextElementImpl tg, float x, float y)
1239     * {
1240     * PDFNumber pdfNumber = new PDFNumber();
1241     * CSSStyleDeclaration styles;
1242     * styles = tg.getStyle();
1243     * //applyStyle(tg, styles);
1244     * // apply transform
1245     * // text has a Tm and need to handle each element
1246     * SVGTransformList trans = tg.getTransform().getBaseVal();
1247     * SVGMatrix matrix = trans.consolidate().getMatrix();
1248     * String transstr = (pdfNumber.doubleOut(matrix.getA())
1249     * + " " + pdfNumber.doubleOut(matrix.getB())
1250     * + " " + pdfNumber.doubleOut(matrix.getC())
1251     * + " " + pdfNumber.doubleOut(-matrix.getD()) + " ");
1252     * String fontFamily = null;
1253     * CSSValue sp = styles.getPropertyCSSValue("font-family");
1254     * if ( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
1255     * {
1256     * if ( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING )
1257     * fontFamily = sp.getCssText();
1258     * }
1259     * if ( fontFamily == null )
1260     * fontFamily = fontState.getFontFamily();
1261     * String fontStyle = null;
1262     * sp = styles.getPropertyCSSValue("font-style");
1263     * if ( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
1264     * {
1265     * if ( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING )
1266     * fontStyle = sp.getCssText();
1267     * }
1268     * if ( fontStyle == null )
1269     * fontStyle = fontState.getFontStyle();
1270     * String fontWeight = null;
1271     * sp = styles.getPropertyCSSValue("font-weight");
1272     * if( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
1273     * {
1274     * if ( ((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING )
1275     * fontWeight = sp.getCssText();
1276     * }
1277     * if( fontWeight == null )
1278     * fontWeight = fontState.getFontWeight();
1279     * float fontSize;
1280     * sp = styles.getPropertyCSSValue("font-size");
1281     * if( sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE )
1282     * {
1283     * //if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_NUMBER) {
1284     * fontSize = ((CSSPrimitiveValue)sp).getFloatValue(CSSPrimitiveValue.CSS_PT);
1285     * //}
1286     * }
1287     * else
1288     * {
1289     * fontSize = fontState.getFontSize() / 1000f;
1290     * }
1291     * FontState fs = fontState;
1292     * try
1293     * {
1294     * fs = new FontState(fontState.getFontInfo(), fontFamily, fontStyle,
1295     * fontWeight, (int)(fontSize * 1000));
1296     * }
1297     * catch( Exception fope )
1298     * {
1299     * // fope.printStackTrace();
1300     * }
1301     * //currentStream.add("/" + fs.getFontName() + " " + fontSize + " Tf\n");
1302     * setFont(fs.getFontName(), fontSize * 1000);
1303     * float tx = tg.x;
1304     * float ty = tg.y;
1305     * float currentX = x + tx;
1306     * float currentY = y + ty;
1307     * List list = tg.textList;
1308     * for ( Enumeration e = list.elements() ; e.hasMoreElements() ; )
1309     * {
1310     * Object o = e.nextElement();
1311     * styles = tg.getStyle();
1312     * //applyStyle(tg, styles);
1313     * if( o instanceof String )
1314     * {
1315     * String str = (String)o;
1316     * //currentStream.add(transstr
1317     * // + (currentX + matrix.getE()) + " "
1318     * // + (y+ty + matrix.getF()) + " Tm "
1319     * // + "(");
1320     * boolean spacing = "preserve".equals(tg.getXMLspace());
1321     * //currentX = addSVGStr(fs, currentX, str, spacing);
1322     * //currentStream.add(") Tj\n");
1323     * // for(int count = 0; count < str.length(); count++) {
1324     * // }
1325     * // currentX += fs.width(' ') / 1000f;
1326     * currentStream.add("\033&a" + (currentX + matrix.getE())*10 + "h" + (y+ty + matrix.getF())*10 + "V" + str);
1327     * for ( int count = 0; count < str.length(); count++ )
1328     * {
1329     * currentX += fs.width(str.charAt(count)) / 1000f;
1330     * }
1331     * currentX += fs.width(' ') / 1000f;
1332     * } else if(o instanceof SVGTextPathElementImpl) {
1333     * SVGTextPathElementImpl tpg = (SVGTextPathElementImpl)o;
1334     * String ref = tpg.str;
1335     * SVGElement graph = null;
1336     * // graph = tpg.locateDef(ref);
1337     * if(graph != null && graph instanceof SVGPathElementImpl) {
1338     * // probably not the best way to do this, should be able
1339     * // to render without the style being set.
1340     * // GraphicImpl parent = graph.getGraphicParent();
1341     * // graph.setParent(tpg);
1342     * // set text path??
1343     * // how should this work
1344     * // graph.setParent(parent);
1345     * }
1346     * } else if(o instanceof SVGTRefElementImpl) {
1347     * SVGTRefElementImpl trg = (SVGTRefElementImpl)o;
1348     * String ref = trg.ref;
1349     * ref = ref.substring(1, ref.length());
1350     * SVGElement graph = null;
1351     * // graph = trg.locateDef(ref);
1352     * if(graph != null && graph instanceof SVGTextElementImpl) {
1353     * // GraphicImpl parent = graph.getGraphicParent();
1354     * // graph.setParent(trg);
1355     * SVGTextElementImpl te = (SVGTextElementImpl)graph;
1356     * renderText(fs, te, (int)(x + tx), (int)(y + ty));
1357     * // graph.setParent(parent);
1358     * }
1359     * } else if(o instanceof SVGTSpanElementImpl) {
1360     * SVGTSpanElementImpl tsg = (SVGTSpanElementImpl)o;
1361     * styles = tsg.getStyle();
1362     * //applyStyle(tsg, styles);
1363     * boolean changed = false;
1364     * String newprop = null;
1365     * sp = styles.getPropertyCSSValue("font-family");
1366     * if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
1367     * if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING) {
1368     * newprop = sp.getCssText();
1369     * }
1370     * }
1371     * if(newprop != null && !newprop.equals(fontFamily)) {
1372     * fontFamily = newprop;
1373     * changed = true;
1374     * }
1375     * sp = styles.getPropertyCSSValue("font-style");
1376     * if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
1377     * if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING) {
1378     * newprop = sp.getCssText();
1379     * }
1380     * }
1381     * if(newprop != null && !newprop.equals(fontStyle)) {
1382     * fontStyle = newprop;
1383     * changed = true;
1384     * }
1385     * sp = styles.getPropertyCSSValue("font-weight");
1386     * if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
1387     * if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_STRING) {
1388     * newprop = sp.getCssText();
1389     * }
1390     * }
1391     * if(newprop != null && !newprop.equals(fontWeight)) {
1392     * fontWeight = newprop;
1393     * changed = true;
1394     * }
1395     * float newSize = fontSize;
1396     * sp = styles.getPropertyCSSValue("font-size");
1397     * if(sp != null && sp.getValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
1398     * // if(((CSSPrimitiveValue)sp).getPrimitiveType() == CSSPrimitiveValue.CSS_NUMBER) {
1399     * newSize = ((CSSPrimitiveValue)sp).getFloatValue(CSSPrimitiveValue.CSS_PT);
1400     * // }
1401     * }
1402     * if ( fontSize != newSize )
1403     * {
1404     * fontSize = newSize;
1405     * changed = true;
1406     * }
1407     * FontState oldfs = null;
1408     * if ( changed )
1409     * {
1410     * oldfs = fs;
1411     * try
1412     * {
1413     * fs = new FontState(fontState.getFontInfo(), fontFamily, fontStyle,
1414     * fontWeight, (int)(fontSize * 1000));
1415     * }
1416     * catch(Exception fope)
1417     * {
1418     * }
1419     * setFont(fs.getFontName(), fontSize * 1000);
1420     * //currentStream.add("/" + fs.getFontName() + " " + fontSize + " Tf\n");
1421     * }
1422     * float baseX;
1423     * float baseY;
1424     * StringBuffer pdf = new StringBuffer();
1425     * boolean spacing = "preserve".equals(tsg.getXMLspace());
1426     * boolean inbetween = false;
1427     * boolean addedspace = false;
1428     * int charPos = 0;
1429     * float xpos = currentX;
1430     * float ypos = currentY;
1431     * for ( int i=0 ; i < tsg.str.length() ; i++ )
1432     * {
1433     * char ch = tsg.str.charAt(i);
1434     * xpos = currentX;
1435     * ypos = currentY;
1436     * if ( tsg.ylist.size() > charPos )
1437     * ypos = y + ty + ((Float)tsg.ylist.get(charPos)).floatValue();
1438     * if ( tsg.dylist.size() > charPos )
1439     * ypos = ypos + ((Float)tsg.dylist.get(charPos)).floatValue();
1440     * if ( tsg.xlist.size() > charPos )
1441     * xpos = x + tx + ((Float)tsg.xlist.get(charPos)).floatValue();
1442     * if ( tsg.dxlist.size() > charPos )
1443     * xpos = xpos + ((Float)tsg.dxlist.get(charPos)).floatValue();
1444     * switch (ch)
1445     * {
1446     * case ' ':
1447     * case ' ':
1448     * if ( spacing )
1449     * {
1450     * currentX = xpos + fs.width(' ') / 1000f;
1451     * currentY = ypos;
1452     * charPos++;
1453     * }
1454     * else
1455     * {
1456     * if ( inbetween && !addedspace)
1457     * {
1458     * addedspace = true;
1459     * currentX = xpos + fs.width(' ') / 1000f;
1460     * currentY = ypos;
1461     * charPos++;
1462     * }
1463     * }
1464     * break;
1465     * case '\n':
1466     * case '\r':
1467     * if ( spacing )
1468     * {
1469     * currentX = xpos + fs.width(' ') / 1000f;
1470     * currentY = ypos;
1471     * charPos++;
1472     * }
1473     * break;
1474     * default:
1475     * addedspace = false;
1476     * pdf = pdf.append(transstr
1477     * + (xpos + matrix.getE()) + " "
1478     * + (ypos + matrix.getF()) + " Tm "
1479     * + "(" + ch + ") Tj\n");
1480     * pdf = pdf.append("\033&a" + (xpos + matrix.getE())*10 + "h" + (ypos + matrix.getF())*10 + "V" + ch);
1481     * currentX = xpos + fs.width(ch) / 1000f;
1482     * currentY = ypos;
1483     * charPos++;
1484     * inbetween = true;
1485     * break;
1486     * }
1487     * //currentStream.add(pdf.toString());
1488     * }
1489     * // currentX += fs.width(' ') / 1000f;
1490     * if ( changed )
1491     * {
1492     * fs = oldfs;
1493     * setFont(fs.getFontName(), fs.getFontSize() * 1000);
1494     * //currentStream.add("/" + fs.getFontName() + " " + fs.getFontSize() / 1000f + " Tf\n");
1495     * }
1496     * }
1497     * else
1498     * {
1499     * System.err.println("Error: unknown text element " + o);
1500     * }
1501     * }
1502     * }
1503     */

1504
1505    /*
1506     * SVG - Not yet implemented
1507     * public void renderGArea(FontState fontState, SVGGElement area, int posx, int posy)
1508     * {
1509     * NodeList nl = area.getChildNodes();
1510     * for ( int count = 0 ; count < nl.getLength() ; count++ )
1511     * {
1512     * Node n = nl.item(count);
1513     * if ( n instanceof SVGElement )
1514     * renderElement(fontState, (SVGElement)n, posx, posy);
1515     * }
1516     * }
1517     */

1518
1519    /*
1520     * SVG - Not yet implemented
1521     * void handleSwitchElement(FontState fontState, int posx, int posy, SVGSwitchElement ael)
1522     * {
1523     * SVGList relist = ael.getRequiredExtensions();
1524     * SVGList rflist = ael.getRequiredFeatures();
1525     * SVGList sllist = ael.getSystemLanguage();
1526     * org.w3c.dom.NodeList nl = ael.getChildNodes();
1527     * for(int count = 0; count < nl.getLength(); count++) {
1528     * org.w3c.dom.Node n = nl.item(count);
1529     * // only render the first child that has a valid
1530     * // test data
1531     * if(n instanceof GraphicElement) {
1532     * GraphicElement graphic = (GraphicElement)n;
1533     * SVGList grelist = graphic.getRequiredExtensions();
1534     * // if null it evaluates to true
1535     * if(grelist != null) {
1536     * for(int i = 0; i < grelist.getNumberOfItems(); i++) {
1537     * String str = (String)grelist.getItem(i);
1538     * if(relist == null) {
1539     * // use default extension set
1540     * // currently no extensions are supported
1541     * // if(!(str.equals("http:// ??"))) {
1542     * continue;
1543     * // }
1544     * } else {
1545     * }
1546     * }
1547     * }
1548     * SVGList grflist = graphic.getRequiredFeatures();
1549     * if(grflist != null) {
1550     * for(int i = 0; i < grflist.getNumberOfItems(); i++) {
1551     * String str = (String)grflist.getItem(i);
1552     * if(rflist == null) {
1553     * // use default feature set
1554     * if(!(str.equals("org.w3c.svg.static")
1555     * || str.equals("org.w3c.dom.svg.all"))) {
1556     * continue;
1557     * }
1558     * } else {
1559     * boolean found = false;
1560     * for(int j = 0; j < rflist.getNumberOfItems(); j++) {
1561     * if(rflist.getItem(j).equals(str)) {
1562     * found = true;
1563     * break;
1564     * }
1565     * }
1566     * if(!found)
1567     * continue;
1568     * }
1569     * }
1570     * }
1571     * SVGList gsllist = graphic.getSystemLanguage();
1572     * if(gsllist != null) {
1573     * for(int i = 0; i < gsllist.getNumberOfItems(); i++) {
1574     * String str = (String)gsllist.getItem(i);
1575     * if(sllist == null) {
1576     * // use default feature set
1577     * if(!(str.equals("en"))) {
1578     * continue;
1579     * }
1580     * } else {
1581     * boolean found = false;
1582     * for(int j = 0; j < sllist.getNumberOfItems(); j++) {
1583     * if(sllist.getItem(j).equals(str)) {
1584     * found = true;
1585     * break;
1586     * }
1587     * }
1588     * if(!found)
1589     * continue;
1590     * }
1591     * }
1592     * }
1593     * renderElement(fontState, (SVGElement)n, posx, posy);
1594     * // only render the first valid one
1595     * break;
1596     * }
1597     * }
1598     * }
1599     */

1600
1601    /**
1602     * render inline area to Text
1603     *
1604     * @param area inline area to render
1605     */

1606    public void renderWordArea(WordArea area) {
1607        // System.out.println("TXTRenderer.renderInlineArea: currentXPosition=" + this.currentXPosition + " currentYPosition=" + this.currentYPosition + " text=" + area.getText());
1608
int rx = this.currentXPosition;
1609        int bl = this.currentYPosition;
1610
1611        String JavaDoc s = area.getText();
1612
1613        if (debug)
1614            System.out.println("TXTRenderer.renderInlineArea: rx=" + rx
1615                               + " bl=" + bl + " pageHeight=" + pageHeight);
1616        addStr((int)((pageHeight - (bl / 100)) * 100 * yFactor) - 1,
1617               (int)(rx * xFactor), s, true);
1618
1619        this.currentXPosition += area.getContentWidth();
1620    }
1621
1622    /**
1623     * render inline space to Text
1624     *
1625     * @param space space to render
1626     */

1627    public void renderInlineSpace(InlineSpace space) {
1628        this.currentXPosition += space.getSize();
1629    }
1630
1631    /**
1632     * render page into Text
1633     *
1634     * @param page page to render
1635     */

1636    public void renderPage(Page page) {
1637        if (debug)
1638            System.out.println("TXTRenderer.renderPage() page.getHeight() = "
1639                               + page.getHeight());
1640
1641        maxX = (int)(textCPI * page.getWidth() / 72000 + 1);
1642        maxY = (int)(textLPI * page.getHeight() / 72000 + 1);
1643        xFactor = (float)(maxX - 1) / (float)page.getWidth();
1644        yFactor = (float)(maxY - 1) / (float)page.getHeight();
1645        charData = new StringBuffer JavaDoc[maxY + 1];
1646        decoData = new StringBuffer JavaDoc[maxY + 1];
1647
1648        if (paperheight > 0)
1649            pageHeight = paperheight;
1650        else
1651            pageHeight = page.getHeight() / 100;
1652
1653        if (debug)
1654            System.out.println("TXTRenderer.renderPage() maxX=" + maxX
1655                               + " maxY=" + maxY + " xFactor=" + xFactor
1656                               + " yFactor=" + yFactor + " paperHeight="
1657                               + pageHeight);
1658
1659        this.currentFontName = "";
1660        this.currentFontSize = 0;
1661
1662        // currentStream.add("BT\n");
1663
renderRegions(page);
1664
1665        // Write out the buffers.
1666
for (int row = 0; row <= maxY; row++) {
1667            StringBuffer JavaDoc cr = charData[row];
1668            StringBuffer JavaDoc dr = decoData[row];
1669            StringBuffer JavaDoc outr = null;
1670
1671            if (cr != null && dr == null)
1672                outr = cr;
1673            else if (dr != null && cr == null)
1674                outr = dr;
1675            else if (cr != null && dr != null) {
1676                int len = dr.length();
1677                if (cr.length() > len)
1678                    len = cr.length();
1679                outr = new StringBuffer JavaDoc();
1680                for (int countr = 0; countr < len; countr++) {
1681                    if (countr < cr.length() && cr.charAt(countr) != ' ')
1682                        outr.append(cr.charAt(countr));
1683                    else if (countr < dr.length())
1684                        outr.append(dr.charAt(countr));
1685                    else
1686                        outr.append(' ');
1687                }
1688            }
1689
1690            if (outr != null)
1691                currentStream.add(outr.toString());
1692            if (row < maxY)
1693                currentStream.add(lineEnding);
1694        }
1695
1696        // End page.
1697
// if ( ++curdiv == divisions || divisions == -1 )
1698
// {
1699
// curdiv = 0;
1700
// currentStream.add("\f");
1701
// }
1702

1703        // Links, etc not implemented...
1704
/*
1705         * currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream,
1706         * page.getWidth()/1000,
1707         * page.getHeight()/1000, page);
1708         * if (page.hasLinks()) {
1709         * currentAnnotList = this.pdfDoc.makeAnnotList();
1710         * currentPage.setAnnotList(currentAnnotList);
1711         * Enumeration e = page.getLinkSets().elements();
1712         * while (e.hasMoreElements()) {
1713         * LinkSet linkSet = (LinkSet) e.nextElement();
1714         * linkSet.align();
1715         * String dest = linkSet.getDest();
1716         * int linkType = linkSet.getLinkType();
1717         * Enumeration f = linkSet.getRects().elements();
1718         * while (f.hasMoreElements()) {
1719         * LinkedRectangle lrect = (LinkedRectangle) f.nextElement();
1720         * currentAnnotList.addLink(
1721         * this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType));
1722         * }
1723         * }
1724         * } else {
1725         * // just to be on the safe side
1726         * currentAnnotList = null;
1727         * }
1728         */

1729    }
1730    public void startRenderer(OutputStream JavaDoc outputStream)
1731    throws IOException JavaDoc {
1732        log.info("rendering areas to TEXT");
1733        currentStream = new TXTStream(outputStream);
1734        String JavaDoc encoding;
1735        if (options != null && (encoding=(String JavaDoc)options.get(encodingOptionName))!=null) {
1736            try {
1737                byte buff[] = " ".getBytes(encoding);
1738            } catch (java.io.UnsupportedEncodingException JavaDoc uee) {
1739                log.warn("Encoding '"+encoding+"' is not supported, so defaulted to " + DEFAULT_ENCODING);
1740                encoding = DEFAULT_ENCODING;
1741            }
1742        }
1743        else
1744            encoding = DEFAULT_ENCODING;
1745        currentStream.setEncoding(encoding);
1746        firstPage=true;
1747    }
1748
1749    /**
1750      * In Mark's patch, this is endRenderer
1751      * However, I couldn't see how it builds that way, so
1752      * i changed it. - Steve gears@apache.org
1753      */

1754
1755    public void stopRenderer(OutputStream JavaDoc outputStream)
1756    throws IOException JavaDoc {
1757        log.info("writing out TEXT");
1758        outputStream.flush();
1759    }
1760
1761    public void render(Page page, OutputStream JavaDoc outputStream) {
1762        idReferences = page.getIDReferences();
1763
1764        if ( firstPage )
1765            firstPage = false;
1766        else
1767            currentStream.add(pageEnding);
1768        this.renderPage(page);
1769        currentStream.add(lineEnding);
1770    }
1771}
1772
Popular Tags