Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

PDFDocumentHandler.java 15KB

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