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 12KB

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