You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AFPDocumentHandler.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.render.afp;
  19. import java.awt.Color;
  20. import java.awt.Dimension;
  21. import java.awt.geom.AffineTransform;
  22. import java.io.IOException;
  23. import java.net.URI;
  24. import java.util.HashMap;
  25. import java.util.Iterator;
  26. import java.util.List;
  27. import java.util.Map;
  28. import org.apache.fop.afp.AFPDitheredRectanglePainter;
  29. import org.apache.fop.afp.AFPPaintingState;
  30. import org.apache.fop.afp.AFPRectanglePainter;
  31. import org.apache.fop.afp.AFPResourceLevelDefaults;
  32. import org.apache.fop.afp.AFPResourceManager;
  33. import org.apache.fop.afp.AFPUnitConverter;
  34. import org.apache.fop.afp.AbstractAFPPainter;
  35. import org.apache.fop.afp.DataStream;
  36. import org.apache.fop.afp.fonts.AFPFontCollection;
  37. import org.apache.fop.afp.fonts.AFPPageFonts;
  38. import org.apache.fop.afp.modca.ResourceObject;
  39. import org.apache.fop.afp.util.AFPResourceAccessor;
  40. import org.apache.fop.apps.MimeConstants;
  41. import org.apache.fop.fonts.FontCollection;
  42. import org.apache.fop.fonts.FontEventAdapter;
  43. import org.apache.fop.fonts.FontInfo;
  44. import org.apache.fop.fonts.FontManager;
  45. import org.apache.fop.render.afp.AFPRendererConfig.AFPRendererConfigParser;
  46. import org.apache.fop.render.afp.extensions.AFPElementMapping;
  47. import org.apache.fop.render.afp.extensions.AFPIncludeFormMap;
  48. import org.apache.fop.render.afp.extensions.AFPInvokeMediumMap;
  49. import org.apache.fop.render.afp.extensions.AFPPageOverlay;
  50. import org.apache.fop.render.afp.extensions.AFPPageSegmentElement;
  51. import org.apache.fop.render.afp.extensions.AFPPageSetup;
  52. import org.apache.fop.render.afp.extensions.ExtensionPlacement;
  53. import org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler;
  54. import org.apache.fop.render.intermediate.IFContext;
  55. import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator;
  56. import org.apache.fop.render.intermediate.IFException;
  57. import org.apache.fop.render.intermediate.IFPainter;
  58. /**
  59. * {@link org.apache.fop.render.intermediate.IFDocumentHandler} implementation that produces AFP
  60. * (MO:DCA).
  61. */
  62. public class AFPDocumentHandler extends AbstractBinaryWritingIFDocumentHandler
  63. implements AFPCustomizable {
  64. //** logging instance */
  65. //private static Log log = LogFactory.getLog(AFPDocumentHandler.class);
  66. /** the resource manager */
  67. private AFPResourceManager resourceManager;
  68. /** the painting state */
  69. private final AFPPaintingState paintingState;
  70. /** unit converter */
  71. private final AFPUnitConverter unitConv;
  72. /** the AFP datastream */
  73. private DataStream dataStream;
  74. /** the map of page segments */
  75. private Map<String, PageSegmentDescriptor> pageSegmentMap
  76. = new java.util.HashMap<String, PageSegmentDescriptor>();
  77. // Rounded corners are cached at the document level
  78. private Map<String, String> roundedCornerNameCache
  79. = new HashMap<String, String>();
  80. private int roundedCornerCount = 0;
  81. /** Medium Map referenced on previous page **/
  82. private String lastMediumMap;
  83. private static enum Location {
  84. ELSEWHERE, IN_DOCUMENT_HEADER, FOLLOWING_PAGE_SEQUENCE, IN_PAGE_HEADER
  85. }
  86. private Location location = Location.ELSEWHERE;
  87. /** temporary holds extensions that have to be deferred until the end of the page-sequence */
  88. private List<AFPPageSetup> deferredPageSequenceExtensions
  89. = new java.util.LinkedList<AFPPageSetup>();
  90. /** the shading mode for filled rectangles */
  91. private AFPShadingMode shadingMode = AFPShadingMode.COLOR;
  92. /**
  93. * Default constructor.
  94. */
  95. public AFPDocumentHandler(IFContext context) {
  96. super(context);
  97. this.resourceManager = new AFPResourceManager(context.getUserAgent().getResourceResolver());
  98. this.paintingState = new AFPPaintingState();
  99. this.unitConv = paintingState.getUnitConverter();
  100. }
  101. /** {@inheritDoc} */
  102. public boolean supportsPagesOutOfOrder() {
  103. return false;
  104. }
  105. /** {@inheritDoc} */
  106. public String getMimeType() {
  107. return MimeConstants.MIME_AFP;
  108. }
  109. /** {@inheritDoc} */
  110. public IFDocumentHandlerConfigurator getConfigurator() {
  111. return new AFPRendererConfigurator(getUserAgent(), new AFPRendererConfigParser());
  112. }
  113. /** {@inheritDoc} */
  114. @Override
  115. public void setDefaultFontInfo(FontInfo fontInfo) {
  116. FontManager fontManager = getUserAgent().getFontManager();
  117. FontCollection[] fontCollections = new FontCollection[] {
  118. new AFPFontCollection(getUserAgent().getEventBroadcaster(), null)
  119. };
  120. FontInfo fi = (fontInfo != null ? fontInfo : new FontInfo());
  121. fi.setEventListener(new FontEventAdapter(getUserAgent().getEventBroadcaster()));
  122. fontManager.setup(fi, fontCollections);
  123. setFontInfo(fi);
  124. }
  125. AFPPaintingState getPaintingState() {
  126. return this.paintingState;
  127. }
  128. DataStream getDataStream() {
  129. return this.dataStream;
  130. }
  131. AFPResourceManager getResourceManager() {
  132. return this.resourceManager;
  133. }
  134. AbstractAFPPainter createRectanglePainter() {
  135. if (AFPShadingMode.DITHERED.equals(this.shadingMode)) {
  136. return new AFPDitheredRectanglePainter(
  137. getPaintingState(), getDataStream(), getResourceManager());
  138. } else {
  139. return new AFPRectanglePainter(
  140. getPaintingState(), getDataStream());
  141. }
  142. }
  143. /** {@inheritDoc} */
  144. @Override
  145. public void startDocument() throws IFException {
  146. super.startDocument();
  147. try {
  148. paintingState.setColor(Color.WHITE);
  149. this.dataStream = resourceManager.createDataStream(paintingState, outputStream);
  150. this.dataStream.startDocument();
  151. } catch (IOException e) {
  152. throw new IFException("I/O error in startDocument()", e);
  153. }
  154. }
  155. /** {@inheritDoc} */
  156. @Override
  157. public void startDocumentHeader() throws IFException {
  158. super.startDocumentHeader();
  159. this.location = Location.IN_DOCUMENT_HEADER;
  160. }
  161. /** {@inheritDoc} */
  162. @Override
  163. public void endDocumentHeader() throws IFException {
  164. super.endDocumentHeader();
  165. this.location = Location.ELSEWHERE;
  166. }
  167. /** {@inheritDoc} */
  168. @Override
  169. public void endDocument() throws IFException {
  170. try {
  171. this.dataStream.endDocument();
  172. this.dataStream = null;
  173. this.resourceManager.writeToStream();
  174. this.resourceManager = null;
  175. } catch (IOException ioe) {
  176. throw new IFException("I/O error in endDocument()", ioe);
  177. }
  178. super.endDocument();
  179. }
  180. /** {@inheritDoc} */
  181. public void startPageSequence(String id) throws IFException {
  182. try {
  183. dataStream.startPageGroup();
  184. } catch (IOException ioe) {
  185. throw new IFException("I/O error in startPageSequence()", ioe);
  186. }
  187. this.location = Location.FOLLOWING_PAGE_SEQUENCE;
  188. }
  189. /** {@inheritDoc} */
  190. public void endPageSequence() throws IFException {
  191. try {
  192. //Process deferred page-sequence-level extensions
  193. Iterator<AFPPageSetup> iter = this.deferredPageSequenceExtensions.iterator();
  194. while (iter.hasNext()) {
  195. AFPPageSetup aps = iter.next();
  196. iter.remove();
  197. if (AFPElementMapping.NO_OPERATION.equals(aps.getElementName())) {
  198. handleNOP(aps);
  199. } else {
  200. throw new UnsupportedOperationException("Don't know how to handle " + aps);
  201. }
  202. }
  203. //End page sequence
  204. dataStream.endPageGroup();
  205. } catch (IOException ioe) {
  206. throw new IFException("I/O error in endPageSequence()", ioe);
  207. }
  208. this.location = Location.ELSEWHERE;
  209. }
  210. /**
  211. * Returns the base AFP transform
  212. *
  213. * @return the base AFP transform
  214. */
  215. private AffineTransform getBaseTransform() {
  216. AffineTransform baseTransform = new AffineTransform();
  217. double scale = unitConv.mpt2units(1);
  218. baseTransform.scale(scale, scale);
  219. return baseTransform;
  220. }
  221. /** {@inheritDoc} */
  222. public void startPage(int index, String name, String pageMasterName, Dimension size)
  223. throws IFException {
  224. this.location = Location.ELSEWHERE;
  225. paintingState.clear();
  226. AffineTransform baseTransform = getBaseTransform();
  227. paintingState.concatenate(baseTransform);
  228. int pageWidth = Math.round(unitConv.mpt2units(size.width));
  229. paintingState.setPageWidth(pageWidth);
  230. int pageHeight = Math.round(unitConv.mpt2units(size.height));
  231. paintingState.setPageHeight(pageHeight);
  232. int pageRotation = paintingState.getPageRotation();
  233. int resolution = paintingState.getResolution();
  234. dataStream.startPage(pageWidth, pageHeight, pageRotation,
  235. resolution, resolution);
  236. }
  237. /** {@inheritDoc} */
  238. @Override
  239. public void startPageHeader() throws IFException {
  240. super.startPageHeader();
  241. this.location = Location.IN_PAGE_HEADER;
  242. }
  243. /** {@inheritDoc} */
  244. @Override
  245. public void endPageHeader() throws IFException {
  246. this.location = Location.ELSEWHERE;
  247. super.endPageHeader();
  248. }
  249. /** {@inheritDoc} */
  250. public IFPainter startPageContent() throws IFException {
  251. return new AFPPainter(this);
  252. }
  253. /** {@inheritDoc} */
  254. public void endPageContent() throws IFException {
  255. }
  256. /** {@inheritDoc} */
  257. public void endPage() throws IFException {
  258. try {
  259. AFPPageFonts pageFonts = paintingState.getPageFonts();
  260. if (pageFonts != null && !pageFonts.isEmpty()) {
  261. dataStream.addFontsToCurrentPage(pageFonts);
  262. }
  263. dataStream.endPage();
  264. } catch (IOException ioe) {
  265. throw new IFException("I/O error in endPage()", ioe);
  266. }
  267. }
  268. /** {@inheritDoc} */
  269. public void handleExtensionObject(Object extension) throws IFException {
  270. if (extension instanceof AFPPageSetup) {
  271. AFPPageSetup aps = (AFPPageSetup)extension;
  272. String element = aps.getElementName();
  273. if (AFPElementMapping.TAG_LOGICAL_ELEMENT.equals(element)) {
  274. switch (this.location) {
  275. case FOLLOWING_PAGE_SEQUENCE:
  276. case IN_PAGE_HEADER:
  277. String name = aps.getName();
  278. String value = aps.getValue();
  279. int encoding = aps.getEncoding();
  280. dataStream.createTagLogicalElement(name, value, encoding);
  281. break;
  282. default:
  283. throw new IFException(
  284. "TLE extension must be in the page header or between page-sequence"
  285. + " and the first page: " + aps, null);
  286. }
  287. } else if (AFPElementMapping.NO_OPERATION.equals(element)) {
  288. switch (this.location) {
  289. case FOLLOWING_PAGE_SEQUENCE:
  290. if (aps.getPlacement() == ExtensionPlacement.BEFORE_END) {
  291. this.deferredPageSequenceExtensions.add(aps);
  292. break;
  293. }
  294. case IN_DOCUMENT_HEADER:
  295. case IN_PAGE_HEADER:
  296. handleNOP(aps);
  297. break;
  298. default:
  299. throw new IFException(
  300. "NOP extension must be in the document header, the page header"
  301. + " or between page-sequence"
  302. + " and the first page: " + aps, null);
  303. }
  304. } else {
  305. if (this.location != Location.IN_PAGE_HEADER) {
  306. throw new IFException(
  307. "AFP page setup extension encountered outside the page header: " + aps,
  308. null);
  309. }
  310. if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(element)) {
  311. AFPPageSegmentElement.AFPPageSegmentSetup apse
  312. = (AFPPageSegmentElement.AFPPageSegmentSetup)aps;
  313. String name = apse.getName();
  314. String source = apse.getValue();
  315. String uri = apse.getResourceSrc();
  316. pageSegmentMap.put(source, new PageSegmentDescriptor(name, uri));
  317. }
  318. }
  319. } else if (extension instanceof AFPPageOverlay) {
  320. AFPPageOverlay ipo = (AFPPageOverlay)extension;
  321. if (this.location != Location.IN_PAGE_HEADER) {
  322. throw new IFException(
  323. "AFP page overlay extension encountered outside the page header: " + ipo,
  324. null);
  325. }
  326. String overlay = ipo.getName();
  327. if (overlay != null) {
  328. dataStream.createIncludePageOverlay(overlay, ipo.getX(), ipo.getY());
  329. }
  330. } else if (extension instanceof AFPInvokeMediumMap) {
  331. if (this.location != Location.FOLLOWING_PAGE_SEQUENCE
  332. && this.location != Location.IN_PAGE_HEADER) {
  333. throw new IFException(
  334. "AFP IMM extension must be between page-sequence"
  335. + " and the first page or child of page-header: "
  336. + extension, null);
  337. }
  338. AFPInvokeMediumMap imm = (AFPInvokeMediumMap)extension;
  339. String mediumMap = imm.getName();
  340. if (mediumMap != null) {
  341. dataStream.createInvokeMediumMap(mediumMap);
  342. }
  343. } else if (extension instanceof AFPIncludeFormMap) {
  344. AFPIncludeFormMap formMap = (AFPIncludeFormMap)extension;
  345. AFPResourceAccessor accessor = new AFPResourceAccessor(
  346. getUserAgent().getResourceResolver());
  347. try {
  348. getResourceManager().createIncludedResource(formMap.getName(),
  349. formMap.getSrc(), accessor,
  350. ResourceObject.TYPE_FORMDEF);
  351. } catch (IOException ioe) {
  352. throw new IFException(
  353. "I/O error while embedding form map resource: " + formMap.getName(), ioe);
  354. }
  355. }
  356. }
  357. /**
  358. * Corner images can be reused by storing at the document level in the AFP
  359. * The cache is used to map cahced images to caller generated descriptions of the corner
  360. * @param cornerKey caller's identifier for the corner
  361. * @return document id of the corner image
  362. */
  363. public String cacheRoundedCorner(String cornerKey) {
  364. // Make a unique id
  365. StringBuffer idBuilder = new StringBuffer("RC");
  366. String tmp = Integer.toHexString(roundedCornerCount).toUpperCase();
  367. if (tmp.length() > 6) {
  368. //Will never happen
  369. //log.error("Rounded corners cache capacity exceeded");
  370. //We should get a visual clue
  371. roundedCornerCount = 0;
  372. tmp = "000000";
  373. } else if (tmp.length() < 6) {
  374. for (int i = 0; i < 6 - tmp.length(); i++) {
  375. idBuilder.append("0");
  376. }
  377. idBuilder.append(tmp);
  378. }
  379. roundedCornerCount++;
  380. String id = idBuilder.toString();
  381. //cache the corner id
  382. roundedCornerNameCache.put(cornerKey, id);
  383. return id;
  384. }
  385. /**
  386. * This method returns the an id that identifies a cached corner or null if non existent
  387. * @param cornerKey caller's identifier for the corner
  388. * @return document id of the corner image
  389. */
  390. public String getCachedRoundedCorner(String cornerKey) {
  391. return (String)roundedCornerNameCache.get(cornerKey);
  392. }
  393. private void handleNOP(AFPPageSetup nop) {
  394. String content = nop.getContent();
  395. if (content != null) {
  396. dataStream.createNoOperation(content);
  397. }
  398. }
  399. // ---=== AFPCustomizable ===---
  400. /** {@inheritDoc} */
  401. public void setBitsPerPixel(int bitsPerPixel) {
  402. paintingState.setBitsPerPixel(bitsPerPixel);
  403. }
  404. /** {@inheritDoc} */
  405. public void setColorImages(boolean colorImages) {
  406. paintingState.setColorImages(colorImages);
  407. }
  408. /** {@inheritDoc} */
  409. public void setNativeImagesSupported(boolean nativeImages) {
  410. paintingState.setNativeImagesSupported(nativeImages);
  411. }
  412. /** {@inheritDoc} */
  413. public void setCMYKImagesSupported(boolean value) {
  414. paintingState.setCMYKImagesSupported(value);
  415. }
  416. /** {@inheritDoc} */
  417. public void setDitheringQuality(float quality) {
  418. this.paintingState.setDitheringQuality(quality);
  419. }
  420. /** {@inheritDoc} */
  421. public void setBitmapEncodingQuality(float quality) {
  422. this.paintingState.setBitmapEncodingQuality(quality);
  423. }
  424. /** {@inheritDoc} */
  425. public void setShadingMode(AFPShadingMode shadingMode) {
  426. this.shadingMode = shadingMode;
  427. }
  428. /** {@inheritDoc} */
  429. public void setResolution(int resolution) {
  430. paintingState.setResolution(resolution);
  431. }
  432. /** {@inheritDoc} */
  433. public void setLineWidthCorrection(float correction) {
  434. paintingState.setLineWidthCorrection(correction);
  435. }
  436. /** {@inheritDoc} */
  437. public int getResolution() {
  438. return paintingState.getResolution();
  439. }
  440. /** {@inheritDoc} */
  441. public void setGOCAEnabled(boolean enabled) {
  442. this.paintingState.setGOCAEnabled(enabled);
  443. }
  444. /** {@inheritDoc} */
  445. public boolean isGOCAEnabled() {
  446. return this.paintingState.isGOCAEnabled();
  447. }
  448. /** {@inheritDoc} */
  449. public void setStrokeGOCAText(boolean stroke) {
  450. this.paintingState.setStrokeGOCAText(stroke);
  451. }
  452. /** {@inheritDoc} */
  453. public boolean isStrokeGOCAText() {
  454. return this.paintingState.isStrokeGOCAText();
  455. }
  456. /** {@inheritDoc} */
  457. public void setWrapPSeg(boolean pSeg) {
  458. paintingState.setWrapPSeg(pSeg);
  459. }
  460. /** {@inheritDoc} */
  461. public void setFS45(boolean fs45) {
  462. paintingState.setFS45(fs45);
  463. }
  464. /** {@inheritDoc} */
  465. public boolean getWrapPSeg() {
  466. return paintingState.getWrapPSeg();
  467. }
  468. /** {@inheritDoc} */
  469. public boolean getFS45() {
  470. return paintingState.getFS45();
  471. }
  472. public void setDefaultResourceGroupUri(URI uri) {
  473. resourceManager.setDefaultResourceGroupUri(uri);
  474. }
  475. /** {@inheritDoc} */
  476. public void setResourceLevelDefaults(AFPResourceLevelDefaults defaults) {
  477. resourceManager.setResourceLevelDefaults(defaults);
  478. }
  479. /**
  480. * Returns the page segment descriptor for a given URI if it actually represents a page segment.
  481. * Otherwise, it just returns null.
  482. * @param uri the URI that identifies the page segment
  483. * @return the page segment descriptor or null if there's no page segment for the given URI
  484. */
  485. PageSegmentDescriptor getPageSegmentNameFor(String uri) {
  486. return pageSegmentMap.get(uri);
  487. }
  488. /** {@inheritDoc} */
  489. public void canEmbedJpeg(boolean canEmbed) {
  490. paintingState.setCanEmbedJpeg(canEmbed);
  491. }
  492. }