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

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