aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/fop/render/afp/AFPRenderer.java
blob: e311e2726d195c798c7e29b3a51a14dc58886ba1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

package org.apache.fop.render.afp;

import java.awt.Color;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.RenderedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;

import org.apache.xmlgraphics.image.loader.ImageException;
import org.apache.xmlgraphics.image.loader.ImageFlavor;
import org.apache.xmlgraphics.image.loader.ImageInfo;
import org.apache.xmlgraphics.image.loader.ImageManager;
import org.apache.xmlgraphics.image.loader.ImageSessionContext;
import org.apache.xmlgraphics.image.loader.impl.ImageGraphics2D;
import org.apache.xmlgraphics.image.loader.impl.ImageRawCCITTFax;
import org.apache.xmlgraphics.image.loader.impl.ImageRendered;
import org.apache.xmlgraphics.image.loader.impl.ImageXMLDOM;
import org.apache.xmlgraphics.image.loader.util.ImageUtil;
import org.apache.xmlgraphics.ps.ImageEncodingHelper;

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.area.Block;
import org.apache.fop.area.CTM;
import org.apache.fop.area.LineArea;
import org.apache.fop.area.OffDocumentItem;
import org.apache.fop.area.PageViewport;
import org.apache.fop.area.Trait;
import org.apache.fop.area.inline.Image;
import org.apache.fop.area.inline.Leader;
import org.apache.fop.area.inline.TextArea;
import org.apache.fop.datatypes.URISpecification;
import org.apache.fop.events.ResourceEventProducer;
import org.apache.fop.fo.Constants;
import org.apache.fop.fo.extensions.ExtensionAttachment;
import org.apache.fop.fonts.FontCollection;
import org.apache.fop.fonts.FontInfo;
import org.apache.fop.fonts.FontManager;
import org.apache.fop.render.AbstractPathOrientedRenderer;
import org.apache.fop.render.AbstractState;
import org.apache.fop.render.Graphics2DAdapter;
import org.apache.fop.render.RendererContext;
import org.apache.fop.render.afp.extensions.AFPElementMapping;
import org.apache.fop.render.afp.extensions.AFPPageSetup;
import org.apache.fop.render.afp.fonts.AFPFont;
import org.apache.fop.render.afp.fonts.AFPFontCollection;
import org.apache.fop.render.afp.modca.AFPConstants;
import org.apache.fop.render.afp.modca.AFPDataStream;
import org.apache.fop.render.afp.modca.PageObject;

/**
 * This is an implementation of a FOP Renderer that renders areas to AFP.
 * <p>
 * A renderer is primarily designed to convert a given area tree into the output
 * document format. It should be able to produce pages and fill the pages with
 * the text and graphical content. Usually the output is sent to an output
 * stream. Some output formats may support extra information that is not
 * available from the area tree or depends on the destination of the document.
 * Each renderer is given an area tree to render to its output format. The area
 * tree is simply a representation of the pages and the placement of text and
 * graphical objects on those pages.
 * </p>
 * <p>
 * The renderer will be given each page as it is ready and an output stream to
 * write the data out. All pages are supplied in the order they appear in the
 * document. In order to save memory it is possible to render the pages out of
 * order. Any page that is not ready to be rendered is setup by the renderer
 * first so that it can reserve a space or reference for when the page is ready
 * to be rendered.The renderer is responsible for managing the output format and
 * associated data and flow.
 * </p>
 * <p>
 * Each renderer is totally responsible for its output format. Because font
 * metrics (and therefore layout) are obtained in two different ways depending
 * on the renderer, the renderer actually sets up the fonts being used. The font
 * metrics are used during the layout process to determine the size of
 * characters.
 * </p>
 * <p>
 * The render context is used by handlers. It contains information about the
 * current state of the renderer, such as the page, the position, and any other
 * miscellaneous objects that are required to draw into the page.
 * </p>
 * <p>
 * A renderer is created by implementing the Renderer interface. However, the
 * AbstractRenderer does most of what is needed, including iterating through the
 * tree parts, so it is this that is extended. This means that this object only
 * need to implement the basic functionality such as text, images, and lines.
 * AbstractRenderer's methods can easily be overridden to handle things in a
 * different way or do some extra processing.
 * </p>
 * <p>
 * The relevant AreaTree structures that will need to be rendered are Page,
 * Viewport, Region, Span, Block, Line, Inline. A renderer implementation
 * renders each individual page, clips and aligns child areas to a viewport,
 * handle all types of inline area, text, image etc and draws various lines and
 * rectangles.
 * </p>
 *
 * Note: There are specific extensions that have been added to the FO. They are
 * specific to their location within the FO and have to be processed accordingly
 * (ie. at the start or end of the page).
 *
 */
public class AFPRenderer extends AbstractPathOrientedRenderer {

    /** Normal PDF resolution (72dpi) */
    public static final int NORMAL_AFP_RESOLUTION = 72;

    private static final int X = 0;

    private static final int Y = 1;

    private static final int X1 = 0;

    private static final int Y1 = 1;

    private static final int X2 = 2;

    private static final int Y2 = 3;

    /**
     * The afp data stream object responsible for generating afp data
     */
    private AFPDataStream afpDataStream = null;

    /**
     * The map of page segments
     */
    private Map/*<String,String>*/pageSegmentsMap = null;

    /**
     * The map of saved incomplete pages
     */
    private Map pages = null;

    /** drawing state */
    private AFPState currentState = new AFPState();

    /**
     * Constructor for AFPRenderer.
     */
    public AFPRenderer() {
        super();
    }

    /** {@inheritDoc} */
    public void setupFontInfo(FontInfo inFontInfo) {
        this.fontInfo = inFontInfo;
        FontManager fontManager = userAgent.getFactory().getFontManager();
        FontCollection[] fontCollections = new FontCollection[] {
            new AFPFontCollection(userAgent.getEventBroadcaster(), getFontList())
        };
        fontManager.setup(getFontInfo(), fontCollections);
    }

    /** {@inheritDoc} */
    public void setUserAgent(FOUserAgent agent) {
        super.setUserAgent(agent);
    }

    /** {@inheritDoc} */
    public void startRenderer(OutputStream outputStream) throws IOException {
        currentState.setColor(new Color(255, 255, 255));
        getAFPDataStream().setPortraitRotation(currentState.getPortraitRotation());
        afpDataStream.setLandscapeRotation(currentState.getLandscapeRotation());
        afpDataStream.setOutputStream(outputStream);
    }

    /** {@inheritDoc} */
    public void stopRenderer() throws IOException {
        getAFPDataStream().write();
        afpDataStream = null;
    }

    /** {@inheritDoc} */
    public void startPageSequence(LineArea seqTitle) {
        getAFPDataStream().endPageGroup();
        afpDataStream.startPageGroup();
    }

    /** {@inheritDoc} */
    public boolean supportsOutOfOrder() {
        // return false;
        return true;
    }

    /** {@inheritDoc} */
    public void preparePage(PageViewport page) {
        final int pageRotation = 0;
        int pageWidth = currentState.getPageWidth();
        int pageHeight = currentState.getPageHeight();
        getAFPDataStream().startPage(pageWidth, pageHeight, pageRotation,
                getResolution(), getResolution());

        renderPageObjectExtensions(page);

        PageObject currentPage = getAFPDataStream().savePage();
        getPages().put(page, currentPage);
    }

    private Map/*<PageViewport, PageObject>*/ getPages() {
        if (this.pages == null) {
            this.pages = new java.util.HashMap/*<PageViewport, PageObject>*/();
        }
        return this.pages;
    }

    /** {@inheritDoc} */
    public void processOffDocumentItem(OffDocumentItem odi) {
        // TODO
        log.debug("NYI processOffDocumentItem(" + odi + ")");
    }

    /** {@inheritDoc} */
    public Graphics2DAdapter getGraphics2DAdapter() {
        return new AFPGraphics2DAdapter();
    }

    /** {@inheritDoc} */
    public void startVParea(CTM ctm, Rectangle2D clippingRect) {
        saveGraphicsState();
        if (ctm != null) {
            AffineTransform at = ctm.toAffineTransform();
            concatenateTransformationMatrix(at);
        }
        if (clippingRect != null) {
            clipRect((float)clippingRect.getX() / 1000f,
                    (float)clippingRect.getY() / 1000f,
                    (float)clippingRect.getWidth() / 1000f,
                    (float)clippingRect.getHeight() / 1000f);
        }
    }

    /** {@inheritDoc} */
    public void endVParea() {
        restoreGraphicsState();
    }

    /** {@inheritDoc} */
    protected void concatenateTransformationMatrix(AffineTransform at) {
        if (!at.isIdentity()) {
            currentState.concatenate(at);
        }
    }

    /** {@inheritDoc} */
    public void renderPage(PageViewport pageViewport) throws IOException, FOPException {
        currentState.clear();

        Rectangle2D bounds = pageViewport.getViewArea();

        AffineTransform basicPageTransform = new AffineTransform();
        int resolution = currentState.getResolution();
        double scale = mpt2units(1);
        basicPageTransform.scale(scale, scale);

        currentState.concatenate(basicPageTransform);

        if (getPages().containsKey(pageViewport)) {
            getAFPDataStream().restorePage(
                    (PageObject)getPages().remove(pageViewport));
        } else {
            int pageWidth
                = (int)Math.round(mpt2units((float)bounds.getWidth()));
            currentState.setPageWidth(pageWidth);
            int pageHeight
                = (int)Math.round(mpt2units((float)bounds.getHeight()));
            currentState.setPageHeight(pageHeight);

            final int pageRotation = 0;
            getAFPDataStream().startPage(pageWidth, pageHeight, pageRotation,
                    resolution, resolution);

            renderPageObjectExtensions(pageViewport);
        }

        super.renderPage(pageViewport);

        AFPPageFonts pageFonts = currentState.getPageFonts();
        if (pageFonts != null && !pageFonts.isEmpty()) {
            getAFPDataStream().addFontsToCurrentPage(pageFonts);
        }

        getAFPDataStream().endPage();
    }

    /** {@inheritDoc} */
    public void clip() {
        // TODO
        log.debug("NYI clip()");
    }

    /** {@inheritDoc} */
    public void clipRect(float x, float y, float width, float height) {
        // TODO
        log.debug("NYI clipRect(x=" + x + ",y=" + y + ",width=" + width + ", height=" + height + ")");
    }

    /** {@inheritDoc} */
    public void moveTo(float x, float y) {
        // TODO
        log.debug("NYI moveTo(x=" + x + ",y=" + y + ")");
    }

    /** {@inheritDoc} */
    public void lineTo(float x, float y) {
        // TODO
        log.debug("NYI lineTo(x=" + x + ",y=" + y + ")");
    }

    /** {@inheritDoc} */
    public void closePath() {
        // TODO
        log.debug("NYI closePath()");
    }

    private int[] mpts2units(float[] srcPts, float[] dstPts) {
        return transformPoints(srcPts, dstPts, true);
    }

    private int[] pts2units(float[] srcPts, float[] dstPts) {
        return transformPoints(srcPts, dstPts, false);
    }

    private int[] mpts2units(float[] srcPts) {
        return transformPoints(srcPts, null, true);
    }

    private int[] pts2units(float[] srcPts) {
        return transformPoints(srcPts, null, false);
    }

    private float mpt2units(float mpt) {
        return mpt / ((float)AFPConstants.DPI_72_MPTS / currentState.getResolution());
    }

    /** {@inheritDoc} */
    public void fillRect(float x, float y, float width, float height) {
        float[] srcPts = new float[] {x * 1000, y * 1000};
        float[] dstPts = new float[srcPts.length];
        int[] coords = mpts2units(srcPts, dstPts);
        int x2 = coords[X] + Math.round(mpt2units(width * 1000));
        LineDataInfo lineDataInfo = new LineDataInfo();
        lineDataInfo.x1 = coords[X];
        lineDataInfo.y1 = coords[Y];
        lineDataInfo.x2 = x2;
        lineDataInfo.y2 = coords[Y];
        lineDataInfo.thickness = Math.round(mpt2units(height * 1000));
        lineDataInfo.color = currentState.getColor();
        getAFPDataStream().createLine(lineDataInfo);
    }

    /** {@inheritDoc} */
    public void drawBorderLine(float x1, float y1, float x2, float y2,
            boolean horz, boolean startOrBefore, int style, Color col) {
        float[] srcPts = new float[] {x1 * 1000, y1 * 1000, x2 * 1000, y2 * 1000};
        float[] dstPts = new float[srcPts.length];
        int[] coords = mpts2units(srcPts, dstPts);

        float width = dstPts[X2] - dstPts[X1];
        float height = dstPts[Y2] - dstPts[Y1];
        if ((width < 0) || (height < 0)) {
            log.error("Negative extent received. Border won't be painted.");
            return;
        }

        LineDataInfo lineDataInfo = new LineDataInfo();
        lineDataInfo.color = col;

        switch (style) {
        
        case Constants.EN_DOUBLE:
            
            lineDataInfo.x1 = coords[X1];
            lineDataInfo.y1 = coords[Y1];

            if (horz) {
                float h3 = height / 3;
                lineDataInfo.thickness = Math.round(h3);
                
                lineDataInfo.x2 = coords[X2];
                lineDataInfo.y2 = coords[Y1];
                afpDataStream.createLine(lineDataInfo);
                                
                int ym2 = Math.round(dstPts[Y1] + h3 + h3);
                lineDataInfo.y1 = ym2;
                lineDataInfo.y2 = ym2;
                afpDataStream.createLine(lineDataInfo);
            } else {
                float w3 = width / 3;
                lineDataInfo.thickness = Math.round(w3);

                lineDataInfo.x2 = coords[X1];
                lineDataInfo.y2 = coords[Y2];                
                afpDataStream.createLine(lineDataInfo);
                
                int xm2 = Math.round(dstPts[X1] + w3 + w3);
                lineDataInfo.x1 = xm2;
                lineDataInfo.x2 = xm2;
                afpDataStream.createLine(lineDataInfo);
            }
            break;
            
        case Constants.EN_DASHED:
            lineDataInfo.x1 = coords[X1];

            if (horz) {
                float w2 = 2 * height;

                lineDataInfo.y1 = coords[Y1];
                lineDataInfo.x2 = coords[X1] + Math.round(w2);
                lineDataInfo.y2 = coords[Y1];
                lineDataInfo.thickness = Math.round(height);
                
                while (lineDataInfo.x1 + w2 < coords[X2]) {
                    afpDataStream.createLine(lineDataInfo);                    
                    lineDataInfo.x1 += 2 * w2; 
                }
            } else {
                float h2 = 2 * width;

                lineDataInfo.y1 = coords[Y2];
                lineDataInfo.x2 = coords[X1];
                lineDataInfo.y2 = coords[Y1] + Math.round(h2);
                lineDataInfo.thickness = Math.round(width);

                while (lineDataInfo.y2 < coords[Y2]) {
                    afpDataStream.createLine(lineDataInfo);
                    lineDataInfo.y2 += 2 * h2;
                }
            }
            break;
            
        case Constants.EN_DOTTED:

            lineDataInfo.x1 = coords[X1];
            lineDataInfo.y1 = coords[Y1];

            if (horz) {
                lineDataInfo.thickness = Math.round(height);
                lineDataInfo.x2 = coords[X1] + lineDataInfo.thickness;
                lineDataInfo.y2 = coords[Y1];
                while (lineDataInfo.x2 < coords[X2]) {
                    afpDataStream.createLine(lineDataInfo);
                    coords[X1] += 2 * height;
                    lineDataInfo.x1 = coords[X1];
                    lineDataInfo.x2 = coords[X1] + lineDataInfo.thickness;
                }
            } else {
                lineDataInfo.thickness = Math.round(width);
                lineDataInfo.x2 = coords[X1];
                lineDataInfo.y2 = coords[Y1] + lineDataInfo.thickness;
                
                while (lineDataInfo.y2 < coords[Y2]) {
                    afpDataStream.createLine(lineDataInfo);
                    coords[Y1] += 2 * width;
                    lineDataInfo.y1 = coords[Y1];
                    lineDataInfo.y2 = coords[Y1] + lineDataInfo.thickness;
                }
            }
            break;
        case Constants.EN_GROOVE:
        case Constants.EN_RIDGE: {
            
            float colFactor = (style == EN_GROOVE ? 0.4f : -0.4f);
            if (horz) {

                lineDataInfo.x1 = coords[X1];
                lineDataInfo.x2 = coords[X2];                

                float h3 = height / 3;
                
                lineDataInfo.color = lightenColor(col, -colFactor);
                lineDataInfo.thickness = Math.round(h3);
                lineDataInfo.y1 = lineDataInfo.y2 = coords[Y1];
                afpDataStream.createLine(lineDataInfo);
                
                lineDataInfo.color = col;                 
                lineDataInfo.y1 = lineDataInfo.y2 = Math.round(dstPts[Y1] + h3);
                afpDataStream.createLine(lineDataInfo);
                
                lineDataInfo.color = lightenColor(col, colFactor);
                lineDataInfo.y1 = lineDataInfo.y2 = Math.round(dstPts[Y1] + h3 + h3);                
                afpDataStream.createLine(lineDataInfo);
                
            } else {

                lineDataInfo.y1 = coords[Y1];
                lineDataInfo.y2 = coords[Y2];                

                float w3 = width / 3;
                float xm1 = dstPts[X1] + (w3 / 2);

                lineDataInfo.color = lightenColor(col, -colFactor);
                lineDataInfo.x1 = lineDataInfo.x2 = Math.round(xm1);
                afpDataStream.createLine(lineDataInfo);
                
                lineDataInfo.color = col;
                lineDataInfo.x1 = lineDataInfo.x2 = Math.round(xm1 + w3);
                afpDataStream.createLine(lineDataInfo);

                lineDataInfo.color = lightenColor(col, colFactor);
                lineDataInfo.x1 = lineDataInfo.x2 = Math.round(xm1 + w3 + w3);
                afpDataStream.createLine(lineDataInfo);
            }
            break;
        }
        
        case Constants.EN_HIDDEN:
            break;
            
        case Constants.EN_INSET:
        case Constants.EN_OUTSET:
        default:
              lineDataInfo.x1 = coords[X1]; 
              lineDataInfo.y1 = coords[Y1];
              if (horz) {
                  lineDataInfo.thickness = Math.round(height); 
                  lineDataInfo.x2 = coords[X2];
                  lineDataInfo.y2 = coords[Y1];
              } else {
                  lineDataInfo.thickness = Math.round(width); 
                  lineDataInfo.x2 = coords[X1];
                  lineDataInfo.y2 = coords[Y2];                  
              }
              lineDataInfo.x2 = (horz ? coords[X2] : coords[X1]);
              lineDataInfo.y2 = (horz ? coords[Y1] : coords[Y2]);
              afpDataStream.createLine(lineDataInfo);
        }
    }

    /** {@inheritDoc} */
    protected RendererContext createRendererContext(int x, int y, int width,
            int height, Map foreignAttributes) {
        RendererContext context;
        context = super.createRendererContext(x, y, width, height,
                foreignAttributes);
        context.setProperty(AFPRendererContextConstants.AFP_FONT_INFO,
                this.fontInfo);
        context.setProperty(AFPRendererContextConstants.AFP_DATASTREAM,
                getAFPDataStream());
        context.setProperty(AFPRendererContextConstants.AFP_STATE, getState());
        return context;
    }

    private static final ImageFlavor[] FLAVORS = new ImageFlavor[] {
            ImageFlavor.RAW_CCITTFAX, ImageFlavor.GRAPHICS2D,
            ImageFlavor.BUFFERED_IMAGE, ImageFlavor.RENDERED_IMAGE,
            ImageFlavor.XML_DOM };

    /** {@inheritDoc} */
    public void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
        uri = URISpecification.getURL(uri);
        currentState.setImageUri(uri);
        Rectangle posInt = new Rectangle((int) pos.getX(), (int) pos.getY(),
                (int) pos.getWidth(), (int) pos.getHeight());
        Point origin = new Point(currentIPPosition, currentBPPosition);
        int x = origin.x + posInt.x;
        int y = origin.y + posInt.y;

        String name = (String)getPageSegments().get(uri);
        if (name != null) {
            float[] srcPts = {x, y};
            int[] coords = mpts2units(srcPts);
            getAFPDataStream().createIncludePageSegment(name, coords[X], coords[Y]);
        } else {
            ImageManager manager = getUserAgent().getFactory().getImageManager();
            ImageInfo info = null;
            InputStream in = null;
            try {
                ImageSessionContext sessionContext = getUserAgent()
                        .getImageSessionContext();
                info = manager.getImageInfo(uri, sessionContext);

                // Only now fully load/prepare the image
                Map hints = ImageUtil.getDefaultHints(sessionContext);
                org.apache.xmlgraphics.image.loader.Image img = manager
                        .getImage(info, FLAVORS, hints, sessionContext);

                // ...and process the image
                if (img instanceof ImageGraphics2D) {
                    ImageGraphics2D imageG2D = (ImageGraphics2D) img;
                    RendererContext context = createRendererContext(posInt.x,
                            posInt.y, posInt.width, posInt.height,
                            foreignAttributes);
                    getGraphics2DAdapter().paintImage(
                            imageG2D.getGraphics2DImagePainter(), context,
                            origin.x + posInt.x, origin.y + posInt.y,
                            posInt.width, posInt.height);
                } else if (img instanceof ImageRendered) {
                    ImageRendered imgRend = (ImageRendered) img;
                    RenderedImage ri = imgRend.getRenderedImage();
                    drawBufferedImage(info, ri, getResolution(), posInt.x
                            + currentIPPosition, posInt.y + currentBPPosition,
                            posInt.width, posInt.height, foreignAttributes);
                } else if (img instanceof ImageRawCCITTFax) {
                    ImageRawCCITTFax ccitt = (ImageRawCCITTFax) img;
                    in = ccitt.createInputStream();
                    byte[] buf = IOUtils.toByteArray(in);
                    float[] srcPts = new float[] {
                            posInt.x + currentIPPosition,
                            posInt.y + currentBPPosition,
                            (float)posInt.getWidth(),
                            (float)posInt.getHeight()
                    };
                    int[] coords = mpts2units(srcPts);
                    
                    // create image object parameters
                    ImageObjectInfo imageObjectInfo = new ImageObjectInfo();
                    imageObjectInfo.setBuffered(false);
                    imageObjectInfo.setUri(uri);
                    
                    String mimeType = info.getMimeType();
                    if (mimeType != null) {
                        imageObjectInfo.setMimeType(mimeType);
                    }

                    ObjectAreaInfo objectAreaInfo = new ObjectAreaInfo();
                    objectAreaInfo.setX(coords[X]);
                    objectAreaInfo.setY(coords[Y]);
                    int resolution = currentState.getResolution();
                    int w = Math.round(mpt2units((float)posInt.getWidth() * 1000));
                    int h = Math.round(mpt2units((float)posInt.getHeight() * 1000));
                    objectAreaInfo.setWidth(w);
                    objectAreaInfo.setHeight(h);
                    objectAreaInfo.setWidthRes(resolution);
                    objectAreaInfo.setHeightRes(resolution);
                    imageObjectInfo.setObjectAreaInfo(objectAreaInfo);

                    imageObjectInfo.setData(buf);
                    imageObjectInfo.setDataHeight(ccitt.getSize().getHeightPx());
                    imageObjectInfo.setDataWidth(ccitt.getSize().getWidthPx());
                    imageObjectInfo.setColor(currentState.isColorImages());
                    imageObjectInfo.setBitsPerPixel(currentState.getBitsPerPixel());
                    imageObjectInfo.setCompression(ccitt.getCompression());
                    imageObjectInfo.setResourceInfoFromForeignAttributes(foreignAttributes);
                    getAFPDataStream().createObject(imageObjectInfo);
                } else if (img instanceof ImageXMLDOM) {
                    ImageXMLDOM imgXML = (ImageXMLDOM) img;
                    renderDocument(imgXML.getDocument(), imgXML
                            .getRootNamespace(), pos, foreignAttributes);
                } else {
                    throw new UnsupportedOperationException(
                            "Unsupported image type: " + img);
                }

            } catch (ImageException ie) {
                ResourceEventProducer eventProducer = ResourceEventProducer.Provider
                        .get(getUserAgent().getEventBroadcaster());
                eventProducer.imageError(this, (info != null ? info.toString()
                        : uri), ie, null);
            } catch (FileNotFoundException fe) {
                ResourceEventProducer eventProducer = ResourceEventProducer.Provider
                        .get(getUserAgent().getEventBroadcaster());
                eventProducer.imageNotFound(this, (info != null ? info
                        .toString() : uri), fe, null);
            } catch (IOException ioe) {
                ResourceEventProducer eventProducer = ResourceEventProducer.Provider
                        .get(getUserAgent().getEventBroadcaster());
                eventProducer.imageIOError(this, (info != null ? info
                        .toString() : uri), ioe, null);
            } finally {
                if (in != null) {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    }

    /**
     * Writes a RenderedImage to an OutputStream as raw sRGB bitmaps.
     *
     * @param image
     *            the RenderedImage
     * @param out
     *            the OutputStream
     * @throws IOException
     *             In case of an I/O error.
     * @deprecated use ImageEncodingHelper.encodeRenderedImageAsRGB(image, out)
     *             directly instead
     */
    public static void writeImage(RenderedImage image, OutputStream out)
            throws IOException {
        ImageEncodingHelper.encodeRenderedImageAsRGB(image, out);
    }

    /**
     * Draws a BufferedImage to AFP.
     *
     * @param imageInfo
     *            the image info
     * @param image
     *            the RenderedImage
     * @param imageRes
     *            the resolution of the BufferedImage
     * @param x
     *            the x coordinate (in mpt)
     * @param y
     *            the y coordinate (in mpt)
     * @param width
     *            the width of the viewport (in mpt)
     * @param height
     *            the height of the viewport (in mpt)
     * @param foreignAttributes
     *            a mapping of foreign attributes
     */
    public void drawBufferedImage(ImageInfo imageInfo, RenderedImage image,
            int imageRes, int x, int y, int width, int height, Map foreignAttributes) {
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        try {
            // Serialize image
            // TODO Eventually, this should be changed not to buffer as this
            // increases the
            // memory consumption (see PostScript output)
            ImageEncodingHelper.encodeRenderedImageAsRGB(image, baout);
        } catch (IOException ioe) {
            ResourceEventProducer eventProducer = ResourceEventProducer.Provider
                    .get(getUserAgent().getEventBroadcaster());
            eventProducer.imageWritingError(this, ioe);
            return;
        }

        // create image object parameters
        ImageObjectInfo imageObjectInfo = new ImageObjectInfo();
        imageObjectInfo.setBuffered(true);
        if (imageInfo != null) {
            imageObjectInfo.setUri(imageInfo.getOriginalURI());
            imageObjectInfo.setMimeType(imageInfo.getMimeType());
        }

        ObjectAreaInfo objectAreaInfo = new ObjectAreaInfo();

        float[] srcPts = new float[] {x, y};
        int[] coords = mpts2units(srcPts);
        objectAreaInfo.setX(coords[X]);
        objectAreaInfo.setY(coords[Y]);
        int w = Math.round(mpt2units(width));
        int h = Math.round(mpt2units(height));
        objectAreaInfo.setWidth(w);
        objectAreaInfo.setHeight(h);

        objectAreaInfo.setWidthRes(imageRes);
        objectAreaInfo.setHeightRes(imageRes);
        imageObjectInfo.setObjectAreaInfo(objectAreaInfo);

        imageObjectInfo.setData(baout.toByteArray());
        imageObjectInfo.setDataHeight(image.getHeight());
        imageObjectInfo.setDataWidth(image.getWidth());
        imageObjectInfo.setColor(currentState.isColorImages());
        imageObjectInfo.setBitsPerPixel(currentState.getBitsPerPixel());
        imageObjectInfo.setResourceInfoFromForeignAttributes(foreignAttributes);
        getAFPDataStream().createObject(imageObjectInfo);
    }

    /** {@inheritDoc} */
    public void updateColor(Color col, boolean fill) {
        if (fill) {
            currentState.setColor(col);
        }
    }

    /** {@inheritDoc} */
    public void restoreStateStackAfterBreakOut(List breakOutList) {
        log.debug("Block.FIXED --> restoring context after break-out");
        AbstractState.AbstractData data;
        Iterator it = breakOutList.iterator();
        while (it.hasNext()) {
            data = (AbstractState.AbstractData)it.next();
            saveGraphicsState();
            concatenateTransformationMatrix(data.getTransform());
        }
    }

    /** {@inheritDoc} */
    protected List breakOutOfStateStack() {
        log.debug("Block.FIXED --> break out");
        List breakOutList = new java.util.ArrayList();
        AbstractState.AbstractData data;
        while (true) {
            data = currentState.getData();
            if (currentState.pop() == null) {
                break;
            }
            breakOutList.add(0, data); //Insert because of stack-popping
        }
        return breakOutList;
    }

    /** {@inheritDoc} */
    public void saveGraphicsState() {
        currentState.push();
    }

    /** {@inheritDoc} */
    public void restoreGraphicsState() {
        currentState.pop();
    }

    /** Indicates the beginning of a text object. */
    public void beginTextObject() {
        //TODO maybe?
        log.debug("NYI beginTextObject()");
    }

    /** Indicates the end of a text object. */
    public void endTextObject() {
        //TODO maybe?
        log.debug("NYI endTextObject()");
    }

    /** {@inheritDoc} */
    public void renderImage(Image image, Rectangle2D pos) {
        drawImage(image.getURL(), pos, image.getForeignAttributes());
    }

    /** {@inheritDoc} */
    public void renderText(TextArea text) {
//        log.debug(text.getText());
        renderInlineAreaBackAndBorders(text);

        String name = getInternalFontNameForArea(text);
        int fontSize = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue();
        currentState.setFontSize(fontSize);
        AFPFont font = (AFPFont)fontInfo.getFonts().get(name);

        // Set letterSpacing
        // float ls = fs.getLetterSpacing() / this.currentFontSize;

        // Create an AFPFontAttributes object from the current font details
        AFPFontAttributes afpFontAttributes
            = new AFPFontAttributes(name, font, fontSize);

        AFPPageFonts pageFonts = currentState.getPageFonts();
        if (!pageFonts.containsKey(afpFontAttributes.getFontKey())) {
            // Font not found on current page, so add the new one
            afpFontAttributes.setFontReference(currentState.incrementPageFontCount());
            pageFonts.put(afpFontAttributes.getFontKey(), afpFontAttributes);
        } else {
            // Use the previously stored font attributes
            afpFontAttributes = (AFPFontAttributes) pageFonts.get(afpFontAttributes.getFontKey());
        }

        // Try and get the encoding to use for the font
        String encoding = null;

        try {
            encoding = font.getCharacterSet(fontSize).getEncoding();
        } catch (Throwable ex) {
            encoding = AFPConstants.EBCIDIC_ENCODING;
            log.warn("renderText():: Error getting encoding for font '"
                    + font.getFullName() + "' - using default encoding "
                    + encoding);
        }

        byte[] data = null;
        try {
            String worddata = text.getText();
            data = worddata.getBytes(encoding);
        } catch (UnsupportedEncodingException usee) {
            log.error("renderText:: Font " + afpFontAttributes.getFontKey()
                    + " caused UnsupportedEncodingException");
            return;
        }

        int fontReference = afpFontAttributes.getFontReference();

        int x = (currentIPPosition + text.getBorderAndPaddingWidthStart());
        int y = (currentBPPosition + text.getOffset() + text.getBaselineOffset());
        float[] srcPts = new float[] {x, y};
        int[] coords = mpts2units(srcPts);

        Color color = (Color) text.getTrait(Trait.COLOR);

        int variableSpaceCharacterIncrement = font.getWidth(' ', fontSize) / 1000
          + text.getTextWordSpaceAdjust()
          + text.getTextLetterSpaceAdjust();
        variableSpaceCharacterIncrement = Math.round(mpt2units(variableSpaceCharacterIncrement));

        int interCharacterAdjustment = Math.round(mpt2units(text.getTextLetterSpaceAdjust()));

        TextDataInfo textDataInfo = new TextDataInfo();
        textDataInfo.setFontReference(fontReference);
        textDataInfo.setX(coords[X]);
        textDataInfo.setY(coords[Y]);
        textDataInfo.setColor(color);
        textDataInfo.setVariableSpaceCharacterIncrement(variableSpaceCharacterIncrement);
        textDataInfo.setInterCharacterAdjustment(interCharacterAdjustment);
        textDataInfo.setData(data);
        textDataInfo.setOrientation(currentState.getOrientation());
        getAFPDataStream().createText(textDataInfo);
        // word.getOffset() = only height of text itself
        // currentBlockIPPosition: 0 for beginning of line; nonzero
        // where previous line area failed to take up entire allocated space

        super.renderText(text);

        renderTextDecoration(font, fontSize, text, coords[Y], coords[X]);
    }

    /**
     * Render leader area. This renders a leader area which is an area with a
     * rule.
     *
     * @param area
     *            the leader area to render
     */
    public void renderLeader(Leader area) {
        renderInlineAreaBackAndBorders(area);

        int style = area.getRuleStyle();
        float startx = (currentIPPosition + area
                .getBorderAndPaddingWidthStart()) / 1000f;
        float starty = (currentBPPosition + area.getOffset()) / 1000f;
        float endx = (currentIPPosition + area.getBorderAndPaddingWidthStart() + area
                .getIPD()) / 1000f;
        float ruleThickness = area.getRuleThickness() / 1000f;
        Color col = (Color) area.getTrait(Trait.COLOR);

        switch (style) {
        case EN_SOLID:
        case EN_DASHED:
        case EN_DOUBLE:
        case EN_DOTTED:
        case EN_GROOVE:
        case EN_RIDGE:
            drawBorderLine(startx, starty, endx, starty + ruleThickness, true,
                    true, style, col);
            break;
        default:
            throw new UnsupportedOperationException("rule style not supported");
        }
        super.renderLeader(area);
    }

    /**
     * Sets the rotation to be used for portrait pages, valid values are 0
     * (default), 90, 180, 270.
     *
     * @param rotation
     *            The rotation in degrees.
     */
    public void setPortraitRotation(int rotation) {
        currentState.setPortraitRotation(rotation);
    }

    /**
     * Sets the rotation to be used for landsacpe pages, valid values are 0, 90,
     * 180, 270 (default).
     *
     * @param rotation
     *            The rotation in degrees.
     */
    public void setLandscapeRotation(int rotation) {
        currentState.setLandscapeRotation(rotation);
    }

    /**
     * Get the MIME type of the renderer.
     *
     * @return The MIME type of the renderer
     */
    public String getMimeType() {
        return MimeConstants.MIME_AFP;
    }

    /**
     * Returns the page segments map
     * 
     * @return the page segments map
     */
    private Map/*<String,String>*/getPageSegments() {
        if (pageSegmentsMap == null) {
            pageSegmentsMap = new java.util.HashMap/*<String,String>*/();
        }
        return pageSegmentsMap;
    }

    /**
     * Method to render the page extension.
     * <p>
     *
     * @param pageViewport
     *            the page object
     */
    private void renderPageObjectExtensions(PageViewport pageViewport) {
        this.pageSegmentsMap = null;
        if (pageViewport.getExtensionAttachments() != null
                && pageViewport.getExtensionAttachments().size() > 0) {
            // Extract all AFPPageSetup instances from the attachment list on
            // the s-p-m
            Iterator it = pageViewport.getExtensionAttachments().iterator();
            while (it.hasNext()) {
                ExtensionAttachment attachment = (ExtensionAttachment) it.next();
                if (AFPPageSetup.CATEGORY.equals(attachment.getCategory())) {
                    AFPPageSetup aps = (AFPPageSetup) attachment;
                    String element = aps.getElementName();
                    if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(element)) {
                        String overlay = aps.getName();
                        if (overlay != null) {
                            getAFPDataStream()
                                    .createIncludePageOverlay(overlay);
                        }
                    } else if (AFPElementMapping.INCLUDE_PAGE_SEGMENT
                            .equals(element)) {
                        String name = aps.getName();
                        String source = aps.getValue();
                        getPageSegments().put(source, name);
                    } else if (AFPElementMapping.TAG_LOGICAL_ELEMENT
                            .equals(element)) {
                        String name = aps.getName();
                        String value = aps.getValue();
                        getAFPDataStream().createTagLogicalElement(name, value);
                    } else if (AFPElementMapping.NO_OPERATION.equals(element)) {
                        String content = aps.getContent();
                        if (content != null) {
                            getAFPDataStream().createNoOperation(content);
                        }
                    }
                }
            }
        }

    }

    /**
     * Sets the number of bits used per pixel
     *
     * @param bitsPerPixel
     *            number of bits per pixel
     */
    public void setBitsPerPixel(int bitsPerPixel) {
        currentState.setBitsPerPixel(bitsPerPixel);
    }

    /**
     * Sets whether images are color or not
     *
     * @param colorImages
     *            color image output
     */
    public void setColorImages(boolean colorImages) {
        currentState.setColorImages(colorImages);
    }

    /**
     * Returns the AFPDataStream
     *
     * @return the AFPDataStream
     */
    public AFPDataStream getAFPDataStream() {
        if (afpDataStream == null) {
            this.afpDataStream = new AFPDataStream();
        }
        return afpDataStream;
    }

    /**
     * Sets the output/device resolution
     *
     * @param resolution
     *            the output resolution (dpi)
     */
    public void setResolution(int resolution) {
        ((AFPState)getState()).setResolution(resolution);
    }

    /**
     * Returns the output/device resolution.
     *
     * @return the resolution in dpi
     */
    public int getResolution() {
        return ((AFPState)getState()).getResolution();
    }

    /**
     * Returns the current AFP state
     * 
     * @return the current AFP state
     */
    protected AbstractState getState() {
        if (currentState == null) {
            currentState = new AFPState();
        }
        return currentState;
    }

    // TODO: remove this and use the superclass implementation
    /** {@inheritDoc} */
    protected void renderReferenceArea(Block block) {
        // save position and offset
        int saveIP = currentIPPosition;
        int saveBP = currentBPPosition;

        //Establish a new coordinate system
        AffineTransform at = new AffineTransform();
        at.translate(currentIPPosition, currentBPPosition);
        at.translate(block.getXOffset(), block.getYOffset());
        at.translate(0, block.getSpaceBefore());

        if (!at.isIdentity()) {
            saveGraphicsState();
            concatenateTransformationMatrix(at);
        }

        currentIPPosition = 0;
        currentBPPosition = 0;
        handleBlockTraits(block);

        List children = block.getChildAreas();
        if (children != null) {
            renderBlocks(block, children);
        }

        if (!at.isIdentity()) {
            restoreGraphicsState();
        }

        // stacked and relative blocks effect stacking
        currentIPPosition = saveIP;
        currentBPPosition = saveBP;
    }

    protected int[] transformPoints(float[] srcPts, float[] dstPts) {
        return transformPoints(srcPts, dstPts, true);
    }

    protected int[] transformPoints(float[] srcPts, float[] dstPts, boolean milli) {
        if (dstPts == null) {
            dstPts = new float[srcPts.length];
        }
        AbstractState state = (AbstractState)getState();
        AffineTransform at = state.getData().getTransform();
        at.transform(srcPts, 0, dstPts, 0, srcPts.length / 2);
        int[] coords = new int[srcPts.length];
        for (int i = 0; i < srcPts.length; i++) {
            if (!milli) {
                dstPts[i] *= 1000;
            }
            coords[i] = Math.round(dstPts[i]);
        }
        return coords;
    }

}