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
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
|
/*
* 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.Point2D;
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.ArrayList;
import java.util.HashMap;
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.codec.tiff.TIFFImage;
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.FOUserAgent;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.area.Block;
import org.apache.fop.area.BlockViewport;
import org.apache.fop.area.BodyRegion;
import org.apache.fop.area.CTM;
import org.apache.fop.area.NormalFlow;
import org.apache.fop.area.OffDocumentItem;
import org.apache.fop.area.PageViewport;
import org.apache.fop.area.RegionReference;
import org.apache.fop.area.RegionViewport;
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.SpaceArea;
import org.apache.fop.area.inline.TextArea;
import org.apache.fop.area.inline.WordArea;
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.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.ImageObject;
import org.apache.fop.render.afp.modca.PageObject;
import org.apache.fop.util.ColorUtil;
/**
* 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 {
/**
* The default afp renderer output resolution
*/
private static final int DEFAULT_DPI_RESOLUTION = 240;
/**
* The afp factor for calculating resolutions (e.g. 72000/240 = 300)
*/
private static final int DPI_CONVERSION_FACTOR = 72000;
/**
* The afp data stream object responsible for generating afp data
*/
private AFPDataStream afpDataStream = null;
/**
* The map of afp root extensions
*/
// UNUSED
// private HashMap rootExtensionMap = null;
/**
* The map of page segments
*/
private HashMap pageSegmentsMap = null;
/**
* The fonts on the current page
*/
private HashMap currentPageFonts = null;
/**
* The current color object
*/
private Color currentColor = null;
/**
* The page font number counter, used to determine the next font reference
*/
private int pageFontCounter = 0;
/**
* The current font family
*/
// UNUSED
// private String currentFontFamily = "";
/**
* The current font size
*/
private int currentFontSize = 0;
/**
* The Options to be set on the AFPRenderer
*/
// UNUSED
// private Map afpOptions = null;
/**
* The page width
*/
private int pageWidth = 0;
/**
* The page height
*/
private int pageHeight = 0;
/**
* The current page sequence id
*/
// UNUSED
// private String pageSequenceId = null;
/**
* The portrait rotation
*/
private int portraitRotation = 0;
/**
* The landscape rotation
*/
private int landscapeRotation = 270;
/**
* The line cache, avoids drawing duplicate lines in tables.
*/
// UNUSED
// private HashSet lineCache = null;
/**
* The current x position for line drawing
*/
// UNUSED
// private float x;
/**
* The current y position for line drawing
*/
// UNUSED
// private float y;
/**
* The map of saved incomplete pages
*/
private Map pages = null;
/**
* Flag to the set the output object type for images
*/
private boolean colorImages = false;
/**
* Default value for image depth
*/
private int bitsPerPixel = 8;
/**
* The output resolution
*/
private int resolution = DEFAULT_DPI_RESOLUTION;
/**
* Constructor for AFPRenderer.
*/
public AFPRenderer() {
super();
}
/**
* Set up the font info
*
* @param inFontInfo font info to set up
*/
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 {
currentPageFonts = new HashMap();
currentColor = new Color(255, 255, 255);
afpDataStream = new AFPDataStream();
afpDataStream.setPortraitRotation(portraitRotation);
afpDataStream.setLandscapeRotation(landscapeRotation);
afpDataStream.startDocument(outputStream);
}
/**
* {@inheritDoc}
*/
public void stopRenderer() throws IOException {
afpDataStream.endDocument();
}
/**
* {@inheritDoc}
*/
public boolean supportsOutOfOrder() {
//return false;
return true;
}
/**
* Prepare a page for rendering. This is called if the renderer supports
* out of order rendering. The renderer should prepare the page so that a
* page further on in the set of pages can be rendered. The body of the
* page should not be rendered. The page will be rendered at a later time
* by the call to render page.
*
* {@inheritDoc}
*/
public void preparePage(PageViewport page) {
// initializeRootExtensions(page);
// this.currentFontFamily = "";
this.currentFontSize = 0;
this.pageFontCounter = 0;
this.currentPageFonts.clear();
// this.lineCache = new HashSet();
Rectangle2D bounds = page.getViewArea();
this.pageWidth = mpts2units(bounds.getWidth());
this.pageHeight = mpts2units(bounds.getHeight());
// renderPageGroupExtensions(page);
final int pageRotation = 0;
this.afpDataStream.startPage(pageWidth, pageHeight, pageRotation,
getResolution(), getResolution());
renderPageObjectExtensions(page);
if (this.pages == null) {
this.pages = new HashMap();
}
this.pages.put(page, afpDataStream.savePage());
}
/**
* {@inheritDoc}
*/
public void processOffDocumentItem(OffDocumentItem odi) {
// TODO
}
/** {@inheritDoc} */
public Graphics2DAdapter getGraphics2DAdapter() {
return new AFPGraphics2DAdapter();
}
/**
* {@inheritDoc}
*/
public void startVParea(CTM ctm, Rectangle2D clippingRect) {
// dummy not used
}
/**
* {@inheritDoc}
*/
public void endVParea() {
// dummy not used
}
/**
* Renders a region viewport. <p>
*
* The region may clip the area and it establishes a position from where
* the region is placed.</p>
*
* @param port The region viewport to be rendered
*/
public void renderRegionViewport(RegionViewport port) {
if (port != null) {
Rectangle2D view = port.getViewArea();
// The CTM will transform coordinates relative to
// this region-reference area into page coords, so
// set origin for the region to 0,0.
currentBPPosition = 0;
currentIPPosition = 0;
RegionReference regionReference = port.getRegionReference();
handleRegionTraits(port);
/*
_afpDataStream.startOverlay(mpts2units(view.getX())
, mpts2units(view.getY())
, mpts2units(view.getWidth())
, mpts2units(view.getHeight())
, rotation);
*/
pushViewPortPos(new ViewPortPos(view, regionReference.getCTM()));
if (regionReference.getRegionClass() == FO_REGION_BODY) {
renderBodyRegion((BodyRegion) regionReference);
} else {
renderRegion(regionReference);
}
/*
_afpDataStream.endOverlay();
*/
popViewPortPos();
}
}
/** {@inheritDoc} */
protected void renderBlockViewport(BlockViewport bv, List children) {
// clip and position viewport if necessary
// save positions
int saveIP = currentIPPosition;
int saveBP = currentBPPosition;
CTM ctm = bv.getCTM();
int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();
//This is the content-rect
float width = (float)bv.getIPD() / 1000f;
float height = (float)bv.getBPD() / 1000f;
if (bv.getPositioning() == Block.ABSOLUTE
|| bv.getPositioning() == Block.FIXED) {
//For FIXED, we need to break out of the current viewports to the
//one established by the page. We save the state stack for restoration
//after the block-container has been painted. See below.
List breakOutList = null;
if (bv.getPositioning() == Block.FIXED) {
breakOutList = breakOutOfStateStack();
}
AffineTransform positionTransform = new AffineTransform();
positionTransform.translate(bv.getXOffset(), bv.getYOffset());
//"left/"top" (bv.getX/YOffset()) specify the position of the content rectangle
positionTransform.translate(-borderPaddingStart, -borderPaddingBefore);
//skipping fox:transform here
//saveGraphicsState();
//Viewport position
//concatenateTransformationMatrix(mptToPt(positionTransform));
//Background and borders
float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd()) / 1000f;
float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter()) / 1000f;
Point2D ptSrc = new Point(0, 0);
Point2D ptDst = positionTransform.transform(ptSrc, null);
Rectangle2D borderRect = new Rectangle2D.Double(ptDst.getX(), ptDst.getY(),
1000 * (width + bpwidth), 1000 * (height + bpheight));
pushViewPortPos(new ViewPortPos(borderRect, new CTM(positionTransform)));
drawBackAndBorders(bv, 0, 0, width + bpwidth, height + bpheight);
//Shift to content rectangle after border painting
AffineTransform contentRectTransform = new AffineTransform();
contentRectTransform.translate(borderPaddingStart, borderPaddingBefore);
//concatenateTransformationMatrix(mptToPt(contentRectTransform));
ptSrc = new Point(0, 0);
ptDst = contentRectTransform.transform(ptSrc, null);
Rectangle2D contentRect = new Rectangle2D.Double(ptDst.getX(), ptDst.getY(),
1000 * width, 1000 * height);
pushViewPortPos(new ViewPortPos(contentRect, new CTM(contentRectTransform)));
//Clipping is not supported, yet
//Rectangle2D clippingRect = null;
//clippingRect = new Rectangle(0, 0, bv.getIPD(), bv.getBPD());
//saveGraphicsState();
//Set up coordinate system for content rectangle
AffineTransform contentTransform = ctm.toAffineTransform();
//concatenateTransformationMatrix(mptToPt(contentTransform));
contentRect = new Rectangle2D.Double(0, 0, 1000 * width, 1000 * height);
pushViewPortPos(new ViewPortPos(contentRect, new CTM(contentTransform)));
currentIPPosition = 0;
currentBPPosition = 0;
renderBlocks(bv, children);
popViewPortPos();
popViewPortPos();
//restoreGraphicsState();
popViewPortPos();
//restoreGraphicsState();
if (breakOutList != null) {
restoreStateStackAfterBreakOut(breakOutList);
}
currentIPPosition = saveIP;
currentBPPosition = saveBP;
} else {
currentBPPosition += bv.getSpaceBefore();
//borders and background in the old coordinate system
handleBlockTraits(bv);
//Advance to start of content area
currentIPPosition += bv.getStartIndent();
CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
ctm = tempctm.multiply(ctm);
//Now adjust for border/padding
currentBPPosition += borderPaddingBefore;
Rectangle2D clippingRect = null;
clippingRect = new Rectangle(currentIPPosition, currentBPPosition,
bv.getIPD(), bv.getBPD());
//startVParea(ctm, clippingRect);
pushViewPortPos(new ViewPortPos(clippingRect, ctm));
currentIPPosition = 0;
currentBPPosition = 0;
renderBlocks(bv, children);
//endVParea();
popViewPortPos();
currentIPPosition = saveIP;
currentBPPosition = saveBP;
currentBPPosition += (int)(bv.getAllocBPD());
}
}
/** {@inheritDoc} */
protected void renderReferenceArea(Block block) {
//TODO Remove this method once concatenateTransformationMatrix() is implemented
// 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()) {
Rectangle2D contentRect
= new Rectangle2D.Double(at.getTranslateX(), at.getTranslateY(),
block.getAllocIPD(), block.getAllocBPD());
pushViewPortPos(new ViewPortPos(contentRect, new CTM(at)));
}
currentIPPosition = 0;
currentBPPosition = 0;
handleBlockTraits(block);
List children = block.getChildAreas();
if (children != null) {
renderBlocks(block, children);
}
if (!at.isIdentity()) {
popViewPortPos();
}
// stacked and relative blocks effect stacking
currentIPPosition = saveIP;
currentBPPosition = saveBP;
}
/** {@inheritDoc} */
protected void renderFlow(NormalFlow flow) {
// save position and offset
int saveIP = currentIPPosition;
int saveBP = currentBPPosition;
//Establish a new coordinate system
AffineTransform at = new AffineTransform();
at.translate(currentIPPosition, currentBPPosition);
if (!at.isIdentity()) {
Rectangle2D contentRect
= new Rectangle2D.Double(at.getTranslateX(), at.getTranslateY(),
flow.getAllocIPD(), flow.getAllocBPD());
pushViewPortPos(new ViewPortPos(contentRect, new CTM(at)));
}
currentIPPosition = 0;
currentBPPosition = 0;
super.renderFlow(flow);
if (!at.isIdentity()) {
popViewPortPos();
}
// stacked and relative blocks effect stacking
currentIPPosition = saveIP;
currentBPPosition = saveBP;
}
/** {@inheritDoc} */
protected void concatenateTransformationMatrix(AffineTransform at) {
//Not used here since AFPRenderer defines its own renderBlockViewport() method.
throw new UnsupportedOperationException("NYI");
}
/**
* {@inheritDoc}
*/
public void renderPage(PageViewport pageViewport) {
// initializeRootExtensions(page);
// this.currentFontFamily = "";
this.currentFontSize = 0;
this.pageFontCounter = 0;
this.currentPageFonts.clear();
// this.lineCache = new HashSet();
Rectangle2D bounds = pageViewport.getViewArea();
this.pageWidth = mpts2units(bounds.getWidth());
this.pageHeight = mpts2units(bounds.getHeight());
if (pages != null && pages.containsKey(pageViewport)) {
this.afpDataStream.restorePage((PageObject) pages.remove(pageViewport));
} else {
// renderPageGroupExtensions(page);
final int pageRotation = 0;
this.afpDataStream.startPage(pageWidth, pageHeight, pageRotation,
getResolution(), getResolution());
renderPageObjectExtensions(pageViewport);
}
pushViewPortPos(new ViewPortPos());
renderPageAreas(pageViewport.getPage());
Iterator i = currentPageFonts.values().iterator();
while (i.hasNext()) {
AFPFontAttributes afpFontAttributes = (AFPFontAttributes) i.next();
afpDataStream.createFont(
(byte)afpFontAttributes.getFontReference(),
afpFontAttributes.getFont(),
afpFontAttributes.getPointSize());
}
try {
afpDataStream.endPage();
} catch (IOException ioex) {
// TODO What shall we do?
}
popViewPortPos();
}
/**
* {@inheritDoc}
*/
public void clip() {
// TODO
}
/**
* {@inheritDoc}
*/
public void clipRect(float x, float y, float width, float height) {
// TODO
}
/**
* {@inheritDoc}
*/
public void moveTo(float x, float y) {
// TODO
}
/**
* {@inheritDoc}
*/
public void lineTo(float x, float y) {
// TODO
}
/**
* {@inheritDoc}
*/
public void closePath() {
// TODO
}
/**
* {@inheritDoc}
*/
public void fillRect(float x, float y, float width, float height) {
/*
afpDataStream.createShading(
pts2units(x),
pts2units(y),
pts2units(width),
pts2units(height),
currentColor.getRed(),
currentColor.getGreen(),
currentColor.getBlue());
*/
afpDataStream.createLine(
pts2units(x),
pts2units(y),
pts2units(x + width),
pts2units(y),
pts2units(height),
currentColor);
}
/**
* {@inheritDoc}
*/
public void drawBorderLine(float x1, float y1, float x2, float y2,
boolean horz, boolean startOrBefore, int style, Color col) {
float w = x2 - x1;
float h = y2 - y1;
if ((w < 0) || (h < 0)) {
log.error("Negative extent received. Border won't be painted.");
return;
}
switch (style) {
case Constants.EN_DOUBLE:
if (horz) {
float h3 = h / 3;
float ym1 = y1;
float ym2 = ym1 + h3 + h3;
afpDataStream.createLine(
pts2units(x1),
pts2units(ym1),
pts2units(x2),
pts2units(ym1),
pts2units(h3),
col
);
afpDataStream.createLine(
pts2units(x1),
pts2units(ym2),
pts2units(x2),
pts2units(ym2),
pts2units(h3),
col
);
} else {
float w3 = w / 3;
float xm1 = x1;
float xm2 = xm1 + w3 + w3;
afpDataStream.createLine(
pts2units(xm1),
pts2units(y1),
pts2units(xm1),
pts2units(y2),
pts2units(w3),
col
);
afpDataStream.createLine(
pts2units(xm2),
pts2units(y1),
pts2units(xm2),
pts2units(y2),
pts2units(w3),
col
);
}
break;
case Constants.EN_DASHED:
if (horz) {
float w2 = 2 * h;
while (x1 + w2 < x2) {
afpDataStream.createLine(
pts2units(x1),
pts2units(y1),
pts2units(x1 + w2),
pts2units(y1),
pts2units(h),
col
);
x1 += 2 * w2;
}
} else {
float h2 = 2 * w;
while (y1 + h2 < y2) {
afpDataStream.createLine(
pts2units(x1),
pts2units(y1),
pts2units(x1),
pts2units(y1 + h2),
pts2units(w),
col
);
y1 += 2 * h2;
}
}
break;
case Constants.EN_DOTTED:
if (horz) {
while (x1 + h < x2) {
afpDataStream.createLine(
pts2units(x1),
pts2units(y1),
pts2units(x1 + h),
pts2units(y1),
pts2units(h),
col
);
x1 += 2 * h;
}
} else {
while (y1 + w < y2) {
afpDataStream.createLine(
pts2units(x1),
pts2units(y1),
pts2units(x1),
pts2units(y1 + w),
pts2units(w),
col
);
y1 += 2 * w;
}
}
break;
case Constants.EN_GROOVE:
case Constants.EN_RIDGE:
{
float colFactor = (style == EN_GROOVE ? 0.4f : -0.4f);
if (horz) {
Color uppercol = ColorUtil.lightenColor(col, -colFactor);
Color lowercol = ColorUtil.lightenColor(col, colFactor);
float h3 = h / 3;
float ym1 = y1;
afpDataStream.createLine(
pts2units(x1),
pts2units(ym1),
pts2units(x2),
pts2units(ym1),
pts2units(h3),
uppercol
);
afpDataStream.createLine(
pts2units(x1),
pts2units(ym1 + h3),
pts2units(x2),
pts2units(ym1 + h3),
pts2units(h3),
col
);
afpDataStream.createLine(
pts2units(x1),
pts2units(ym1 + h3 + h3),
pts2units(x2),
pts2units(ym1 + h3 + h3),
pts2units(h3),
lowercol
);
} else {
Color leftcol = ColorUtil.lightenColor(col, -colFactor);
Color rightcol = ColorUtil.lightenColor(col, colFactor);
float w3 = w / 3;
float xm1 = x1 + (w3 / 2);
afpDataStream.createLine(
pts2units(xm1),
pts2units(y1),
pts2units(xm1),
pts2units(y2),
pts2units(w3),
leftcol
);
afpDataStream.createLine(
pts2units(xm1 + w3),
pts2units(y1),
pts2units(xm1 + w3),
pts2units(y2),
pts2units(w3),
col
);
afpDataStream.createLine(
pts2units(xm1 + w3 + w3),
pts2units(y1),
pts2units(xm1 + w3 + w3),
pts2units(y2),
pts2units(w3),
rightcol
);
}
break;
}
case Constants.EN_HIDDEN:
break;
case Constants.EN_INSET:
case Constants.EN_OUTSET:
default:
afpDataStream.createLine(
pts2units(x1),
pts2units(y1),
pts2units(horz ? x2 : x1),
pts2units(horz ? y1 : y2),
pts2units(Math.abs(horz ? (y2 - y1) : (x2 - x1))),
col
);
}
}
/**
* {@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_GRAYSCALE,
Boolean.valueOf(!this.colorImages));
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);
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 = null;
if (pageSegmentsMap != null) {
name = (String) pageSegmentsMap.get(uri);
}
if (name != null) {
afpDataStream.createIncludePageSegment(name, mpts2units(x), mpts2units(y));
} else {
ImageManager manager = getUserAgent().getFactory().getImageManager();
ImageInfo info = 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(ri, getResolution(),
posInt.x + currentIPPosition,
posInt.y + currentBPPosition,
posInt.width,
posInt.height);
} else if (img instanceof ImageRawCCITTFax) {
ImageRawCCITTFax ccitt = (ImageRawCCITTFax)img;
int afpx = mpts2units(posInt.x + currentIPPosition);
int afpy = mpts2units(posInt.y + currentBPPosition);
int afpw = mpts2units(posInt.getWidth());
int afph = mpts2units(posInt.getHeight());
int afpres = getResolution();
ImageObject io = afpDataStream.getImageObject(afpx, afpy, afpw, afph,
afpres, afpres);
io.setImageParameters(
(int) (ccitt.getSize().getDpiHorizontal() * 10),
(int) (ccitt.getSize().getDpiVertical() * 10),
ccitt.getSize().getWidthPx(),
ccitt.getSize().getHeightPx());
int compression = ccitt.getCompression();
switch (compression) {
case TIFFImage.COMP_FAX_G3_1D :
io.setImageEncoding((byte) 0x80);
break;
case TIFFImage.COMP_FAX_G3_2D :
io.setImageEncoding((byte) 0x81);
break;
case TIFFImage.COMP_FAX_G4_2D :
io.setImageEncoding((byte) 0x82);
break;
default:
throw new IllegalStateException(
"Invalid compression scheme: " + compression);
}
InputStream in = ccitt.createInputStream();
try {
byte[] buf = IOUtils.toByteArray(in);
io.setImageData(buf);
} finally {
IOUtils.closeQuietly(in);
}
} 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);
}
/*
ImageFactory fact = userAgent.getFactory().getImageFactory();
FopImage fopimage = fact.getImage(url, userAgent);
if (fopimage == null) {
return;
}
if (!fopimage.load(FopImage.DIMENSIONS)) {
return;
}
String mime = fopimage.getMimeType();
if ("text/xml".equals(mime) || MimeConstants.MIME_SVG.equals(mime)) {
if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
return;
}
Document doc = ((XMLImage) fopimage).getDocument();
String ns = ((XMLImage) fopimage).getNameSpace();
renderDocument(doc, ns, pos, foreignAttributes);
} else if (MimeConstants.MIME_EPS.equals(mime)) {
log.warn("EPS images are not supported by this renderer");
*/
/*
* } else if (MimeConstants.MIME_JPEG.equals(mime)) { if
* (!fopimage.load(FopImage.ORIGINAL_DATA)) { return; }
* fact.releaseImage(url, userAgent);
*
* int x = mpts2units(pos.getX() + currentIPPosition); int y =
* mpts2units(pos.getY() + currentBPPosition); int w =
* mpts2units(pos.getWidth()); int h =
* mpts2units(pos.getHeight()); ImageObject io =
* _afpDataStream.getImageObject(); io.setImageViewport(x, y, w,
* h); io.setImageParameters(
* (int)(fopimage.getHorizontalResolution() * 10),
* (int)(fopimage.getVerticalResolution() * 10),
* fopimage.getWidth(), fopimage.getHeight() );
* io.setImageIDESize((byte)fopimage.getBitsPerPixel());
* io.setImageEncoding((byte)0x83);
* io.setImageData(fopimage.getRessourceBytes());
*//*
} else if (MimeConstants.MIME_TIFF.equals(mime)
&& fopimage instanceof TIFFImage) {
TIFFImage tiffImage = (TIFFImage) fopimage;
int x = mpts2units(pos.getX() + currentIPPosition);
int y = mpts2units(pos.getY() + currentBPPosition);
int w = mpts2units(pos.getWidth());
int h = mpts2units(pos.getHeight());
ImageObject io = afpDataStream.getImageObject(x, y, w, h,
getResolution(), getResolution());
io.setImageParameters(
(int)(fopimage.getHorizontalResolution() * 10),
(int)(fopimage.getVerticalResolution() * 10),
fopimage.getWidth(),
fopimage.getHeight()
);
if (tiffImage.getStripCount() == 1) {
int comp = tiffImage.getCompression();
if (comp == 3) {
if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
return;
}
io.setImageEncoding((byte)0x81);
io.setImageData(fopimage.getRessourceBytes());
} else if (comp == 4) {
if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
return;
}
io.setImageEncoding((byte)0x82);
io.setImageData(fopimage.getRessourceBytes());
} else {
if (!fopimage.load(FopImage.BITMAP)) {
return;
}
convertToGrayScaleImage(io, fopimage.getBitmaps(),
fopimage.getWidth(), fopimage.getHeight());
}
} else {
if (!fopimage.load(FopImage.BITMAP)) {
return;
}
convertToGrayScaleImage(io, fopimage.getBitmaps(),
fopimage.getWidth(), fopimage.getHeight());
}
} else {
if (!fopimage.load(FopImage.BITMAP)) {
return;
}
fact.releaseImage(url, userAgent);
int x = mpts2units(pos.getX() + currentIPPosition);
int y = mpts2units(pos.getY() + currentBPPosition);
int w = mpts2units(pos.getWidth());
int h = mpts2units(pos.getHeight());
ImageObject io = afpDataStream.getImageObject(x, y, w, h,
getResolution(), getResolution());
io.setImageParameters(
(int)(fopimage.getHorizontalResolution() * 10),
(int)(fopimage.getVerticalResolution() * 10),
fopimage.getWidth(),
fopimage.getHeight()
);
if (colorImages) {
io.setImageIDESize((byte)24);
io.setImageData(fopimage.getBitmaps());
} else {
convertToGrayScaleImage(io, fopimage.getBitmaps(),
fopimage.getWidth(), fopimage.getHeight());
}
}*/
}
}
/**
* 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.
*/
public static void writeImage(RenderedImage image, OutputStream out)
throws IOException {
ImageEncodingHelper.encodeRenderedImageAsRGB(image, out);
}
/**
* Draws a BufferedImage to AFP.
*
* @param image
* the RenderedImage
* @param imageResolution
* the resolution of the BufferedImage
* @param x
* the x coordinate (in mpt)
* @param y
* the y coordinate (in mpt)
* @param w
* the width of the viewport (in mpt)
* @param h
* the height of the viewport (in mpt)
*/
public void drawBufferedImage(RenderedImage image, int imageResolution, int x,
int y, int w, int h) {
int afpx = mpts2units(x);
int afpy = mpts2units(y);
int afpw = mpts2units(w);
int afph = mpts2units(h);
int afpres = getResolution();
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)
writeImage(image, baout);
byte[] buf = baout.toByteArray();
// Generate image
ImageObject io = afpDataStream.getImageObject(afpx, afpy, afpw,
afph, afpres, afpres);
io.setImageParameters(imageResolution, imageResolution,
image.getWidth(), image.getHeight());
if (colorImages) {
io.setImageIDESize((byte)24);
io.setImageData(buf);
} else {
// TODO Teach it how to handle grayscale BufferedImages directly
// because this is pretty inefficient
convertToGrayScaleImage(io, buf,
image.getWidth(), image.getHeight(), this.bitsPerPixel);
}
} catch (IOException ioe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageWritingError(this, ioe);
}
}
/**
* Establishes a new foreground or fill color.
* {@inheritDoc}
*/
public void updateColor(Color col, boolean fill) {
if (fill) {
currentColor = col;
}
}
/** {@inheritDoc} */
public List breakOutOfStateStack() {
log.debug("Block.FIXED --> break out");
List breakOutList = new java.util.ArrayList();
//Don't pop the last ViewPortPos (created by renderPage())
while (this.viewPortPositions.size() > 1) {
breakOutList.add(0, popViewPortPos());
}
return breakOutList;
}
/** {@inheritDoc} */
public void restoreStateStackAfterBreakOut(List breakOutList) {
log.debug("Block.FIXED --> restoring context after break-out");
for (int i = 0, c = breakOutList.size(); i < c; i++) {
ViewPortPos vps = (ViewPortPos)breakOutList.get(i);
pushViewPortPos(vps);
}
}
/** Saves the graphics state of the rendering engine. */
public void saveGraphicsState() {
}
/** Restores the last graphics state of the rendering engine. */
public void restoreGraphicsState() {
}
/** Indicates the beginning of a text object. */
public void beginTextObject() {
}
/** Indicates the end of a text object. */
public void endTextObject() {
}
/**
* {@inheritDoc}
*/
public void renderImage(Image image, Rectangle2D pos) {
String url = image.getURL();
drawImage(url, pos);
}
/**
* {@inheritDoc}
*/
public void renderText(TextArea text) {
renderInlineAreaBackAndBorders(text);
String name = getInternalFontNameForArea(text);
currentFontSize = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue();
AFPFont tf = (AFPFont) fontInfo.getFonts().get(name);
Color col = (Color) text.getTrait(Trait.COLOR);
int vsci = mpts2units(tf.getWidth(' ', currentFontSize) / 1000
+ text.getTextWordSpaceAdjust()
+ text.getTextLetterSpaceAdjust());
// 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
int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
int bl = currentBPPosition + text.getOffset() + text.getBaselineOffset();
// Set letterSpacing
//float ls = fs.getLetterSpacing() / this.currentFontSize;
String worddata = text.getText();
// Create an AFPFontAttributes object from the current font details
AFPFontAttributes afpFontAttributes = new AFPFontAttributes(name, tf, currentFontSize);
if (!currentPageFonts.containsKey(afpFontAttributes.getFontKey())) {
// Font not found on current page, so add the new one
pageFontCounter++;
afpFontAttributes.setFontReference(pageFontCounter);
currentPageFonts.put(
afpFontAttributes.getFontKey(),
afpFontAttributes);
} else {
// Use the previously stored font attributes
afpFontAttributes = (AFPFontAttributes) currentPageFonts.get(
afpFontAttributes.getFontKey());
}
// Try and get the encoding to use for the font
String encoding = null;
try {
encoding = tf.getCharacterSet(currentFontSize).getEncoding();
} catch (Throwable ex) {
encoding = AFPConstants.EBCIDIC_ENCODING;
log.warn(
"renderText():: Error getting encoding for font '"
+ tf.getFullName()
+ "' - using default encoding "
+ encoding);
}
try {
afpDataStream.createText(
afpFontAttributes.getFontReference(),
mpts2units(rx),
mpts2units(bl),
col,
vsci,
mpts2units(text.getTextLetterSpaceAdjust()),
worddata.getBytes(encoding));
} catch (UnsupportedEncodingException usee) {
log.error(
"renderText:: Font "
+ afpFontAttributes.getFontKey()
+ " caused UnsupportedEncodingException");
}
super.renderText(text);
renderTextDecoration(tf, currentFontSize, text, bl, rx);
}
/**
* {@inheritDoc}
*/
public void renderWord(WordArea word) {
// UNUSED
// String name = getInternalFontNameForArea(word.getParentArea());
// int size = ((Integer)
// word.getParentArea().getTrait(Trait.FONT_SIZE)).intValue();
// AFPFont tf = (AFPFont) fontInfo.getFonts().get(name);
//
// String s = word.getWord();
//
// FontMetrics metrics = fontInfo.getMetricsFor(name);
super.renderWord(word);
}
/**
* {@inheritDoc}
*/
public void renderSpace(SpaceArea space) {
// UNUSED
// String name = getInternalFontNameForArea(space.getParentArea());
// int size = ((Integer)
// space.getParentArea().getTrait(Trait.FONT_SIZE)).intValue();
// AFPFont tf = (AFPFont) fontInfo.getFonts().get(name);
//
// String s = space.getSpace();
//
// FontMetrics metrics = fontInfo.getMetricsFor(name);
super.renderSpace(space);
}
/**
* 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 AFPRenderer options
* @param options the <code>Map</code> containing the options
*/
// UNUSED
// public void setOptions(Map options) {
//
// this.afpOptions = options;
//
// }
/**
* Determines the orientation from the string representation, this method
* guarantees to return a value of either 0, 90, 180 or 270.
*
* @return the orientation
*/
// UNUSED
// private int getOrientation(String orientationString) {
//
// int orientation = 0;
// if (orientationString != null && orientationString.length() > 0) {
// try {
// orientation = Integer.parseInt(orientationString);
// } catch (NumberFormatException nfe) {
// log.error("Cannot use orientation of " + orientation
// + " defaulting to zero.");
// orientation = 0;
// }
// } else {
// orientation = 0;
// }
// switch (orientation) {
// case 0:
// break;
// case 90:
// break;
// case 180:
// break;
// case 270:
// break;
// default:
// log.error("Cannot use orientation of " + orientation
// + " defaulting to zero.");
// orientation = 0;
// break;
// }
//
// return orientation;
//
// }
/**
* 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) {
if (rotation == 0
|| rotation == 90
|| rotation == 180
|| rotation == 270) {
portraitRotation = rotation;
} else {
throw new IllegalArgumentException("The portrait rotation must be one"
+ " of the values 0, 90, 180, 270");
}
}
/**
* 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) {
if (rotation == 0
|| rotation == 90
|| rotation == 180
|| rotation == 270) {
landscapeRotation = rotation;
} else {
throw new IllegalArgumentException("The landscape rotation must be one"
+ " of the values 0, 90, 180, 270");
}
}
/**
* Get the MIME type of the renderer.
*
* @return The MIME type of the renderer
*/
public String getMimeType() {
return MimeConstants.MIME_AFP;
}
/**
* Method to render the page extension.
* <p>
*
* @param pageViewport the page object
*/
private void renderPageObjectExtensions(PageViewport pageViewport) {
pageSegmentsMap = null;
if (pageViewport.getExtensionAttachments() != null
&& pageViewport.getExtensionAttachments().size() > 0) {
// Extract all AFPPageSetup instances from the attachment list on
// the s-p-m
Iterator i = pageViewport.getExtensionAttachments().iterator();
while (i.hasNext()) {
ExtensionAttachment attachment = (ExtensionAttachment)i.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) {
afpDataStream.createIncludePageOverlay(overlay);
}
} else if (AFPElementMapping.INCLUDE_PAGE_SEGMENT
.equals(element)) {
String name = aps.getName();
String source = aps.getValue();
if (pageSegmentsMap == null) {
pageSegmentsMap = new HashMap();
}
pageSegmentsMap.put(source, name);
} else if (AFPElementMapping.TAG_LOGICAL_ELEMENT
.equals(element)) {
String name = aps.getName();
String value = aps.getValue();
if (pageSegmentsMap == null) {
pageSegmentsMap = new HashMap();
}
afpDataStream.createTagLogicalElement(name, value);
} else if (AFPElementMapping.NO_OPERATION.equals(element)) {
String content = aps.getContent();
if (content != null) {
afpDataStream.createNoOperation(content);
}
}
}
}
}
}
/**
* Converts FOP mpt measurement to afp measurement units
* @param mpt the millipoints value
*/
private int mpts2units(int mpt) {
return mpts2units((double) mpt);
}
/**
* Converts FOP pt measurement to afp measurement units
* @param mpt the millipoints value
*/
private int pts2units(float mpt) {
return mpts2units(mpt * 1000d);
}
/**
* Converts FOP mpt measurement to afp measurement units
*
* @param mpt
* the millipoints value
* @return afp measurement unit value
*/
private int mpts2units(double mpt) {
return (int)Math.round(mpt / (DPI_CONVERSION_FACTOR / getResolution()));
}
/**
* Converts a byte array containing 24 bit RGB image data to a grayscale
* image.
*
* @param io
* the target image object
* @param raw
* the buffer containing the RGB image data
* @param width
* the width of the image in pixels
* @param height
* the height of the image in pixels
* @param bitsPerPixel
* the number of bits to use per pixel
*/
protected static void convertToGrayScaleImage(ImageObject io, byte[] raw, int width,
int height, int bitsPerPixel) {
int pixelsPerByte = 8 / bitsPerPixel;
int bytewidth = (width / pixelsPerByte);
if ((width % pixelsPerByte) != 0) {
bytewidth++;
}
byte[] bw = new byte[height * bytewidth];
byte ib;
for (int y = 0; y < height; y++) {
ib = 0;
int i = 3 * y * width;
for (int x = 0; x < width; x++, i += 3) {
// see http://www.jguru.com/faq/view.jsp?EID=221919
double greyVal = 0.212671d * ((int) raw[i] & 0xff) + 0.715160d
* ((int) raw[i + 1] & 0xff) + 0.072169d
* ((int) raw[i + 2] & 0xff);
switch (bitsPerPixel) {
case 1:
if (greyVal < 128) {
ib |= (byte) (1 << (7 - (x % 8)));
}
break;
case 4:
greyVal /= 16;
ib |= (byte) ((byte) greyVal << ((1 - (x % 2)) * 4));
break;
case 8:
ib = (byte) greyVal;
break;
default:
throw new UnsupportedOperationException(
"Unsupported bits per pixel: " + bitsPerPixel);
}
if ((x % pixelsPerByte) == (pixelsPerByte - 1)
|| ((x + 1) == width)) {
bw[(y * bytewidth) + (x / pixelsPerByte)] = ib;
ib = 0;
}
}
}
io.setImageIDESize((byte) bitsPerPixel);
io.setImageData(bw);
}
private final class ViewPortPos {
private int x = 0;
private int y = 0;
private int rot = 0;
private ViewPortPos() {
}
private ViewPortPos(Rectangle2D view, CTM ctm) {
ViewPortPos currentVP = (ViewPortPos) viewPortPositions
.get(viewPortPositions.size() - 1);
int xOrigin;
int yOrigin;
int width;
int height;
switch (currentVP.rot) {
case 90:
width = mpts2units(view.getHeight());
height = mpts2units(view.getWidth());
xOrigin = pageWidth - width - mpts2units(view.getY())
- currentVP.y;
yOrigin = mpts2units(view.getX()) + currentVP.x;
break;
case 180:
width = mpts2units(view.getWidth());
height = mpts2units(view.getHeight());
xOrigin = pageWidth - width - mpts2units(view.getX())
- currentVP.x;
yOrigin = pageHeight - height - mpts2units(view.getY())
- currentVP.y;
break;
case 270:
width = mpts2units(view.getHeight());
height = mpts2units(view.getWidth());
xOrigin = mpts2units(view.getY()) + currentVP.y;
yOrigin = pageHeight - height - mpts2units(view.getX())
- currentVP.x;
break;
default:
xOrigin = mpts2units(view.getX()) + currentVP.x;
yOrigin = mpts2units(view.getY()) + currentVP.y;
width = mpts2units(view.getWidth());
height = mpts2units(view.getHeight());
break;
}
this.rot = currentVP.rot;
double[] ctmf = ctm.toArray();
if (ctmf[0] == 0.0d && ctmf[1] == -1.0d && ctmf[2] == 1.0d
&& ctmf[3] == 0.d) {
this.rot += 270;
} else if (ctmf[0] == -1.0d && ctmf[1] == 0.0d && ctmf[2] == 0.0d
&& ctmf[3] == -1.0d) {
this.rot += 180;
} else if (ctmf[0] == 0.0d && ctmf[1] == 1.0d && ctmf[2] == -1.0d
&& ctmf[3] == 0.0d) {
this.rot += 90;
}
this.rot %= 360;
switch (this.rot) {
/*
* case 0: this.x = mpts2units(view.getX()) + x; this.y =
* mpts2units(view.getY()) + y; break; case 90: this.x =
* mpts2units(view.getY()) + y; this.y = _pageWidth -
* mpts2units(view.getX() + view.getWidth()) - x; break; case 180:
* this.x = _pageWidth - mpts2units(view.getX() + view.getWidth()) -
* x; this.y = _pageHeight - mpts2units(view.getY() +
* view.getHeight()) - y; break; case 270: this.x = _pageHeight -
* mpts2units(view.getY() + view.getHeight()) - y; this.y =
* mpts2units(view.getX()) + x; break;
*/
case 0:
this.x = xOrigin;
this.y = yOrigin;
break;
case 90:
this.x = yOrigin;
this.y = pageWidth - width - xOrigin;
break;
case 180:
this.x = pageWidth - width - xOrigin;
this.y = pageHeight - height - yOrigin;
break;
case 270:
this.x = pageHeight - height - yOrigin;
this.y = xOrigin;
break;
default:
}
}
public String toString() {
return "x:" + x + " y:" + y + " rot:" + rot;
}
}
private List viewPortPositions = new ArrayList();
private void pushViewPortPos(ViewPortPos vpp) {
viewPortPositions.add(vpp);
afpDataStream.setOffsets(vpp.x, vpp.y, vpp.rot);
}
private ViewPortPos popViewPortPos() {
ViewPortPos current = (ViewPortPos)viewPortPositions.remove(viewPortPositions.size() - 1);
if (viewPortPositions.size() > 0) {
ViewPortPos vpp = (ViewPortPos)viewPortPositions.get(viewPortPositions.size() - 1);
afpDataStream.setOffsets(vpp.x, vpp.y, vpp.rot);
}
return current;
}
/**
* Sets the number of bits used per pixel
*
* @param bitsPerPixel
* number of bits per pixel
*/
public void setBitsPerPixel(int bitsPerPixel) {
this.bitsPerPixel = bitsPerPixel;
switch (bitsPerPixel) {
case 1:
case 4:
case 8:
break;
default:
log.warn("Invalid bits_per_pixel value, must be 1, 4 or 8.");
bitsPerPixel = 8;
break;
}
}
/**
* Sets whether images are color or not
*
* @param colorImages
* color image output
*/
public void setColorImages(boolean colorImages) {
this.colorImages = colorImages;
}
/**
* Sets the output/device resolution
*
* @param resolution
* the output resolution (dpi)
*/
public void setResolution(int resolution) {
if (log.isDebugEnabled()) {
log.debug("renderer-resolution set to: " + resolution + "dpi");
}
this.resolution = resolution;
}
/**
* Returns the output/device resolution.
* @return the resolution in dpi
*/
public int getResolution() {
return this.resolution;
}
}
|