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.

PDFDocumentHandler.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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.pdf;
  19. import java.awt.Dimension;
  20. import java.awt.Rectangle;
  21. import java.awt.geom.AffineTransform;
  22. import java.awt.geom.Point2D;
  23. import java.awt.geom.Rectangle2D;
  24. import java.io.IOException;
  25. import java.util.HashMap;
  26. import java.util.Locale;
  27. import java.util.Map;
  28. import org.apache.commons.logging.Log;
  29. import org.apache.commons.logging.LogFactory;
  30. import org.apache.xmlgraphics.xmp.Metadata;
  31. import org.apache.fop.accessibility.StructureTreeEventHandler;
  32. import org.apache.fop.apps.MimeConstants;
  33. import org.apache.fop.fo.extensions.xmp.XMPMetadata;
  34. import org.apache.fop.pdf.PDFAnnotList;
  35. import org.apache.fop.pdf.PDFArray;
  36. import org.apache.fop.pdf.PDFDocument;
  37. import org.apache.fop.pdf.PDFPage;
  38. import org.apache.fop.pdf.PDFResources;
  39. import org.apache.fop.render.extensions.prepress.PageBoundaries;
  40. import org.apache.fop.render.extensions.prepress.PageScale;
  41. import org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler;
  42. import org.apache.fop.render.intermediate.IFContext;
  43. import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator;
  44. import org.apache.fop.render.intermediate.IFDocumentNavigationHandler;
  45. import org.apache.fop.render.intermediate.IFException;
  46. import org.apache.fop.render.intermediate.IFPainter;
  47. import org.apache.fop.render.pdf.PDFRendererConfig.PDFRendererConfigParser;
  48. import org.apache.fop.render.pdf.extensions.PDFDictionaryAttachment;
  49. import org.apache.fop.render.pdf.extensions.PDFEmbeddedFileAttachment;
  50. /**
  51. * {@link org.apache.fop.render.intermediate.IFDocumentHandler} implementation that produces PDF.
  52. */
  53. public class PDFDocumentHandler extends AbstractBinaryWritingIFDocumentHandler {
  54. /** logging instance */
  55. private static Log log = LogFactory.getLog(PDFDocumentHandler.class);
  56. private boolean accessEnabled;
  57. private PDFLogicalStructureHandler logicalStructureHandler;
  58. private PDFStructureTreeBuilder structureTreeBuilder;
  59. /** the PDF Document being created */
  60. private PDFDocument pdfDoc;
  61. /**
  62. * Utility class which enables all sorts of features that are not directly connected to the
  63. * normal rendering process.
  64. */
  65. private final PDFRenderingUtil pdfUtil;
  66. /** the /Resources object of the PDF document being created */
  67. private PDFResources pdfResources;
  68. /** The current content generator */
  69. private PDFContentGenerator generator;
  70. /** the current page to add annotations to */
  71. private PDFPage currentPage;
  72. /** the current page's PDF reference */
  73. private PageReference currentPageRef;
  74. /** Used for bookmarks/outlines. */
  75. private Map<Integer, PageReference> pageReferences = new HashMap<Integer, PageReference>();
  76. private final PDFDocumentNavigationHandler documentNavigationHandler
  77. = new PDFDocumentNavigationHandler(this);
  78. private Map<Integer, PDFArray> pageNumbers = new HashMap<Integer, PDFArray>();
  79. /**
  80. * Default constructor.
  81. */
  82. public PDFDocumentHandler(IFContext context) {
  83. super(context);
  84. this.pdfUtil = new PDFRenderingUtil(context.getUserAgent());
  85. }
  86. /** {@inheritDoc} */
  87. public boolean supportsPagesOutOfOrder() {
  88. return !accessEnabled;
  89. }
  90. /** {@inheritDoc} */
  91. public String getMimeType() {
  92. return MimeConstants.MIME_PDF;
  93. }
  94. /** {@inheritDoc} */
  95. public IFDocumentHandlerConfigurator getConfigurator() {
  96. return new PDFRendererConfigurator(getUserAgent(), new PDFRendererConfigParser());
  97. }
  98. /** {@inheritDoc} */
  99. public IFDocumentNavigationHandler getDocumentNavigationHandler() {
  100. return this.documentNavigationHandler;
  101. }
  102. void mergeRendererOptionsConfig(PDFRendererOptionsConfig config) {
  103. pdfUtil.mergeRendererOptionsConfig(config);
  104. }
  105. PDFLogicalStructureHandler getLogicalStructureHandler() {
  106. return logicalStructureHandler;
  107. }
  108. PDFDocument getPDFDocument() {
  109. return pdfDoc;
  110. }
  111. PDFPage getCurrentPage() {
  112. return currentPage;
  113. }
  114. PageReference getCurrentPageRef() {
  115. return currentPageRef;
  116. }
  117. PDFContentGenerator getGenerator() {
  118. return generator;
  119. }
  120. /** {@inheritDoc} */
  121. public void startDocument() throws IFException {
  122. super.startDocument();
  123. try {
  124. this.pdfDoc = pdfUtil.setupPDFDocument(this.outputStream);
  125. this.accessEnabled = getUserAgent().isAccessibilityEnabled();
  126. if (accessEnabled) {
  127. setupAccessibility();
  128. }
  129. } catch (IOException e) {
  130. throw new IFException("I/O error in startDocument()", e);
  131. }
  132. }
  133. private void setupAccessibility() {
  134. pdfDoc.getRoot().makeTagged();
  135. logicalStructureHandler = new PDFLogicalStructureHandler(pdfDoc);
  136. // TODO this is ugly. All the necessary information should be available
  137. // at creation time in order to enforce immutability
  138. structureTreeBuilder.setPdfFactory(pdfDoc.getFactory());
  139. structureTreeBuilder.setLogicalStructureHandler(logicalStructureHandler);
  140. structureTreeBuilder.setEventBroadcaster(getUserAgent().getEventBroadcaster());
  141. }
  142. /** {@inheritDoc} */
  143. public void endDocumentHeader() throws IFException {
  144. pdfUtil.generateDefaultXMPMetadata();
  145. }
  146. /** {@inheritDoc} */
  147. public void endDocument() throws IFException {
  148. try {
  149. pdfDoc.getResources().addFonts(pdfDoc, fontInfo);
  150. pdfDoc.outputTrailer(this.outputStream);
  151. this.pdfDoc = null;
  152. pdfResources = null;
  153. this.generator = null;
  154. currentPage = null;
  155. } catch (IOException ioe) {
  156. throw new IFException("I/O error in endDocument()", ioe);
  157. }
  158. super.endDocument();
  159. }
  160. /** {@inheritDoc} */
  161. public void startPageSequence(String id) throws IFException {
  162. //nop
  163. }
  164. /** {@inheritDoc} */
  165. public void endPageSequence() throws IFException {
  166. //nop
  167. }
  168. /** {@inheritDoc} */
  169. public void startPage(int index, String name, String pageMasterName, Dimension size)
  170. throws IFException {
  171. this.pdfResources = this.pdfDoc.getResources();
  172. PageBoundaries boundaries = new PageBoundaries(size, getContext().getForeignAttributes());
  173. Rectangle trimBox = boundaries.getTrimBox();
  174. Rectangle bleedBox = boundaries.getBleedBox();
  175. Rectangle mediaBox = boundaries.getMediaBox();
  176. Rectangle cropBox = boundaries.getCropBox();
  177. // set scale attributes
  178. double scaleX = 1;
  179. double scaleY = 1;
  180. String scale = (String) getContext().getForeignAttribute(
  181. PageScale.EXT_PAGE_SCALE);
  182. Point2D scales = PageScale.getScale(scale);
  183. if (scales != null) {
  184. scaleX = scales.getX();
  185. scaleY = scales.getY();
  186. }
  187. //PDF uses the lower left as origin, need to transform from FOP's internal coord system
  188. AffineTransform boxTransform = new AffineTransform(
  189. scaleX / 1000, 0, 0, -scaleY / 1000, 0, scaleY * size.getHeight() / 1000);
  190. this.currentPage = this.pdfDoc.getFactory().makePage(
  191. this.pdfResources,
  192. index,
  193. toPDFCoordSystem(mediaBox, boxTransform),
  194. toPDFCoordSystem(cropBox, boxTransform),
  195. toPDFCoordSystem(bleedBox, boxTransform),
  196. toPDFCoordSystem(trimBox, boxTransform));
  197. if (accessEnabled) {
  198. logicalStructureHandler.startPage(currentPage);
  199. }
  200. pdfUtil.generatePageLabel(index, name);
  201. currentPageRef = new PageReference(currentPage, size);
  202. this.pageReferences.put(Integer.valueOf(index), currentPageRef);
  203. this.generator = new PDFContentGenerator(this.pdfDoc, this.outputStream,
  204. this.currentPage);
  205. // Transform the PDF's default coordinate system (0,0 at lower left) to the PDFPainter's
  206. AffineTransform basicPageTransform = new AffineTransform(1, 0, 0, -1, 0,
  207. (scaleY * size.height) / 1000f);
  208. basicPageTransform.scale(scaleX, scaleY);
  209. generator.saveGraphicsState();
  210. generator.concatenate(basicPageTransform);
  211. }
  212. private Rectangle2D toPDFCoordSystem(Rectangle box, AffineTransform transform) {
  213. return transform.createTransformedShape(box).getBounds2D();
  214. }
  215. /** {@inheritDoc} */
  216. public IFPainter startPageContent() throws IFException {
  217. return new PDFPainter(this, logicalStructureHandler);
  218. }
  219. /** {@inheritDoc} */
  220. public void endPageContent() throws IFException {
  221. generator.restoreGraphicsState();
  222. //for top-level transform to change the default coordinate system
  223. }
  224. /** {@inheritDoc} */
  225. public void endPage() throws IFException {
  226. if (accessEnabled) {
  227. logicalStructureHandler.endPage();
  228. }
  229. try {
  230. this.documentNavigationHandler.commit();
  231. this.pdfDoc.registerObject(generator.getStream());
  232. currentPage.setContents(generator.getStream());
  233. PDFAnnotList annots = currentPage.getAnnotations();
  234. if (annots != null) {
  235. this.pdfDoc.addObject(annots);
  236. }
  237. this.pdfDoc.addObject(currentPage);
  238. this.generator.flushPDFDoc();
  239. this.generator = null;
  240. } catch (IOException ioe) {
  241. throw new IFException("I/O error in endPage()", ioe);
  242. }
  243. }
  244. /** {@inheritDoc} */
  245. public void handleExtensionObject(Object extension) throws IFException {
  246. if (extension instanceof XMPMetadata) {
  247. pdfUtil.renderXMPMetadata((XMPMetadata) extension);
  248. } else if (extension instanceof Metadata) {
  249. XMPMetadata wrapper = new XMPMetadata(((Metadata) extension));
  250. pdfUtil.renderXMPMetadata(wrapper);
  251. } else if (extension instanceof PDFEmbeddedFileAttachment) {
  252. PDFEmbeddedFileAttachment embeddedFile
  253. = (PDFEmbeddedFileAttachment)extension;
  254. try {
  255. pdfUtil.addEmbeddedFile(embeddedFile);
  256. } catch (IOException ioe) {
  257. throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe);
  258. }
  259. } else if (extension instanceof PDFDictionaryAttachment) {
  260. pdfUtil.renderDictionaryExtension((PDFDictionaryAttachment) extension, currentPage);
  261. } else if (extension != null) {
  262. log.debug("Don't know how to handle extension object. Ignoring: "
  263. + extension + " (" + extension.getClass().getName() + ")");
  264. } else {
  265. log.debug("Ignoring null extension object.");
  266. }
  267. }
  268. /** {@inheritDoc} */
  269. public void setDocumentLocale(Locale locale) {
  270. pdfDoc.getRoot().setLanguage(locale);
  271. }
  272. PageReference getPageReference(int pageIndex) {
  273. return this.pageReferences.get(Integer.valueOf(pageIndex));
  274. }
  275. static final class PageReference {
  276. private final String pageRef;
  277. private final Dimension pageDimension;
  278. private PageReference(PDFPage page, Dimension dim) {
  279. // Avoid keeping references to PDFPage as memory usage is
  280. // considerably increased when handling thousands of pages.
  281. this.pageRef = page.makeReference().toString();
  282. this.pageDimension = new Dimension(dim);
  283. }
  284. public String getPageRef() {
  285. return this.pageRef;
  286. }
  287. public Dimension getPageDimension() {
  288. return this.pageDimension;
  289. }
  290. }
  291. @Override
  292. public StructureTreeEventHandler getStructureTreeEventHandler() {
  293. if (structureTreeBuilder == null) {
  294. structureTreeBuilder = new PDFStructureTreeBuilder();
  295. }
  296. return structureTreeBuilder;
  297. }
  298. public Map<Integer, PDFArray> getPageNumbers() {
  299. return pageNumbers;
  300. }
  301. }