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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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.awt.geom.Rectangle2D.Double;
  25. import java.io.IOException;
  26. import java.util.Map;
  27. import org.w3c.dom.NodeList;
  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.apps.MimeConstants;
  32. import org.apache.fop.fo.extensions.xmp.XMPMetadata;
  33. import org.apache.fop.pdf.PDFAnnotList;
  34. import org.apache.fop.pdf.PDFDocument;
  35. import org.apache.fop.pdf.PDFPage;
  36. import org.apache.fop.pdf.PDFReference;
  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.IFDocumentHandler;
  44. import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator;
  45. import org.apache.fop.render.intermediate.IFDocumentNavigationHandler;
  46. import org.apache.fop.render.intermediate.IFException;
  47. import org.apache.fop.render.intermediate.IFPainter;
  48. import org.apache.fop.util.XMLUtil;
  49. /**
  50. * {@link IFDocumentHandler} implementation that produces PDF.
  51. */
  52. public class PDFDocumentHandler extends AbstractBinaryWritingIFDocumentHandler {
  53. /** logging instance */
  54. private static Log log = LogFactory.getLog(PDFDocumentHandler.class);
  55. private int pageSequenceIndex;
  56. private boolean accessEnabled;
  57. private PDFLogicalStructureHandler logicalStructureHandler;
  58. /** the PDF Document being created */
  59. protected PDFDocument pdfDoc;
  60. /**
  61. * Utility class which enables all sorts of features that are not directly connected to the
  62. * normal rendering process.
  63. */
  64. protected PDFRenderingUtil pdfUtil;
  65. /** the /Resources object of the PDF document being created */
  66. protected PDFResources pdfResources;
  67. /** The current content generator */
  68. protected PDFContentGenerator generator;
  69. /** the current annotation list to add annotations to */
  70. protected PDFResourceContext currentContext;
  71. /** the current page to add annotations to */
  72. protected PDFPage currentPage;
  73. /** the current page's PDF reference */
  74. protected PageReference currentPageRef;
  75. /** Used for bookmarks/outlines. */
  76. protected Map pageReferences = new java.util.HashMap();
  77. private final PDFDocumentNavigationHandler documentNavigationHandler
  78. = new PDFDocumentNavigationHandler(this);
  79. /**
  80. * Default constructor.
  81. */
  82. public PDFDocumentHandler() {
  83. }
  84. /** {@inheritDoc} */
  85. public boolean supportsPagesOutOfOrder() {
  86. return !accessEnabled;
  87. }
  88. /** {@inheritDoc} */
  89. public String getMimeType() {
  90. return MimeConstants.MIME_PDF;
  91. }
  92. /** {@inheritDoc} */
  93. public void setContext(IFContext context) {
  94. super.setContext(context);
  95. this.pdfUtil = new PDFRenderingUtil(context.getUserAgent());
  96. }
  97. /** {@inheritDoc} */
  98. public IFDocumentHandlerConfigurator getConfigurator() {
  99. return new PDFRendererConfigurator(getUserAgent());
  100. }
  101. /** {@inheritDoc} */
  102. public IFDocumentNavigationHandler getDocumentNavigationHandler() {
  103. return this.documentNavigationHandler;
  104. }
  105. PDFRenderingUtil getPDFUtil() {
  106. return this.pdfUtil;
  107. }
  108. PDFLogicalStructureHandler getLogicalStructureHandler() {
  109. return logicalStructureHandler;
  110. }
  111. /** {@inheritDoc} */
  112. public void startDocument() throws IFException {
  113. super.startDocument();
  114. try {
  115. this.pdfDoc = pdfUtil.setupPDFDocument(this.outputStream);
  116. this.accessEnabled = getUserAgent().isAccessibilityEnabled();
  117. if (accessEnabled) {
  118. pdfDoc.getRoot().makeTagged();
  119. logicalStructureHandler = new PDFLogicalStructureHandler(pdfDoc);
  120. }
  121. } catch (IOException e) {
  122. throw new IFException("I/O error in startDocument()", e);
  123. }
  124. }
  125. /** {@inheritDoc} */
  126. public void endDocumentHeader() throws IFException {
  127. pdfUtil.generateDefaultXMPMetadata();
  128. }
  129. /** {@inheritDoc} */
  130. public void endDocument() throws IFException {
  131. try {
  132. pdfDoc.getResources().addFonts(pdfDoc, fontInfo);
  133. pdfDoc.outputTrailer(this.outputStream);
  134. this.pdfDoc = null;
  135. pdfResources = null;
  136. this.generator = null;
  137. currentContext = null;
  138. currentPage = null;
  139. } catch (IOException ioe) {
  140. throw new IFException("I/O error in endDocument()", ioe);
  141. }
  142. super.endDocument();
  143. }
  144. /** {@inheritDoc} */
  145. public void startPageSequence(String id) throws IFException {
  146. //TODO page sequence title
  147. if (this.pdfDoc.getRoot().getLanguage() == null
  148. && getContext().getLanguage() != null) {
  149. //No document-level language set, so we use the first page-sequence's language
  150. this.pdfDoc.getRoot().setLanguage(XMLUtil.toRFC3066(getContext().getLanguage()));
  151. }
  152. if (accessEnabled) {
  153. NodeList nodes = getUserAgent().getStructureTree().getPageSequence(pageSequenceIndex++);
  154. logicalStructureHandler.processStructureTree(nodes, getContext().getLanguage());
  155. }
  156. }
  157. /** {@inheritDoc} */
  158. public void endPageSequence() throws IFException {
  159. //nop
  160. }
  161. /** {@inheritDoc} */
  162. public void startPage(int index, String name, String pageMasterName, Dimension size)
  163. throws IFException {
  164. this.pdfResources = this.pdfDoc.getResources();
  165. PageBoundaries boundaries = new PageBoundaries(size, getContext().getForeignAttributes());
  166. Rectangle trimBox = boundaries.getTrimBox();
  167. Rectangle bleedBox = boundaries.getBleedBox();
  168. Rectangle mediaBox = boundaries.getMediaBox();
  169. Rectangle cropBox = boundaries.getCropBox();
  170. // set scale attributes
  171. double scaleX = 1;
  172. double scaleY = 1;
  173. String scale = (String) getContext().getForeignAttribute(
  174. PageScale.EXT_PAGE_SCALE);
  175. Point2D scales = PageScale.getScale(scale);
  176. if (scales != null) {
  177. scaleX = scales.getX();
  178. scaleY = scales.getY();
  179. }
  180. this.currentPage = this.pdfDoc.getFactory().makePage(
  181. this.pdfResources,
  182. index,
  183. toPointAndScale(mediaBox, scaleX, scaleY),
  184. toPointAndScale(cropBox, scaleX, scaleY),
  185. toPointAndScale(bleedBox, scaleX, scaleY),
  186. toPointAndScale(trimBox, scaleX, scaleY));
  187. if (accessEnabled) {
  188. logicalStructureHandler.startPage(currentPage);
  189. }
  190. pdfUtil.generatePageLabel(index, name);
  191. currentPageRef = new PageReference(currentPage, size);
  192. this.pageReferences.put(new Integer(index), currentPageRef);
  193. this.generator = new PDFContentGenerator(this.pdfDoc, this.outputStream,
  194. this.currentPage);
  195. // Transform the PDF's default coordinate system (0,0 at lower left) to the PDFPainter's
  196. AffineTransform basicPageTransform = new AffineTransform(1, 0, 0, -1, 0,
  197. (scaleY * size.height) / 1000f);
  198. basicPageTransform.scale(scaleX, scaleY);
  199. generator.concatenate(basicPageTransform);
  200. }
  201. private Double toPointAndScale(Rectangle box, double scaleX, double scaleY) {
  202. return new Rectangle2D.Double(box.getX() * scaleX / 1000,
  203. box.getY() * scaleY / 1000,
  204. box.getWidth() * scaleX / 1000,
  205. box.getHeight() * scaleY / 1000);
  206. }
  207. /** {@inheritDoc} */
  208. public IFPainter startPageContent() throws IFException {
  209. return new PDFPainter(this, logicalStructureHandler);
  210. }
  211. /** {@inheritDoc} */
  212. public void endPageContent() throws IFException {
  213. //nop
  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 {
  243. log.debug("Don't know how to handle extension object. Ignoring: "
  244. + extension + " (" + extension.getClass().getName() + ")");
  245. }
  246. }
  247. PageReference getPageReference(int pageIndex) {
  248. return (PageReference)this.pageReferences.get(
  249. new Integer(pageIndex));
  250. }
  251. static final class PageReference {
  252. private final PDFReference pageRef;
  253. private final Dimension pageDimension;
  254. private PageReference(PDFPage page, Dimension dim) {
  255. this.pageRef = page.makeReference();
  256. this.pageDimension = new Dimension(dim);
  257. }
  258. public PDFReference getPageRef() {
  259. return this.pageRef;
  260. }
  261. public Dimension getPageDimension() {
  262. return this.pageDimension;
  263. }
  264. }
  265. }