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.

PDFDocument.java 41KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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.pdf;
  19. // Java
  20. import java.io.IOException;
  21. import java.io.OutputStream;
  22. import java.io.UnsupportedEncodingException;
  23. import java.security.MessageDigest;
  24. import java.security.NoSuchAlgorithmException;
  25. import java.util.ArrayList;
  26. import java.util.Collection;
  27. import java.util.Collections;
  28. import java.util.Date;
  29. import java.util.HashMap;
  30. import java.util.LinkedList;
  31. import java.util.List;
  32. import java.util.Map;
  33. import org.apache.commons.logging.Log;
  34. import org.apache.commons.logging.LogFactory;
  35. import org.apache.xmlgraphics.image.loader.util.SoftMapCache;
  36. import org.apache.fop.pdf.StandardStructureAttributes.Table.Scope;
  37. import org.apache.fop.pdf.xref.CrossReferenceStream;
  38. import org.apache.fop.pdf.xref.CrossReferenceTable;
  39. import org.apache.fop.pdf.xref.TrailerDictionary;
  40. /* image support modified from work of BoBoGi */
  41. /* font support based on work by Takayuki Takeuchi */
  42. /**
  43. * Class representing a PDF document.
  44. *
  45. * The document is built up by calling various methods and then finally
  46. * output to given filehandle using output method.
  47. *
  48. * A PDF document consists of a series of numbered objects preceded by a
  49. * header and followed by an xref table and trailer. The xref table
  50. * allows for quick access to objects by listing their character
  51. * positions within the document. For this reason the PDF document must
  52. * keep track of the character position of each object. The document
  53. * also keeps direct track of the /Root, /Info and /Resources objects.
  54. *
  55. * Modified by Mark Lillywhite, mark-fop@inomial.com. The changes
  56. * involve: ability to output pages one-at-a-time in a streaming
  57. * fashion (rather than storing them all for output at the end);
  58. * ability to write the /Pages object after writing the rest
  59. * of the document; ability to write to a stream and flush
  60. * the object list; enhanced trailer output; cleanups.
  61. *
  62. */
  63. public class PDFDocument {
  64. /** the encoding to use when converting strings to PDF commands */
  65. public static final String ENCODING = "ISO-8859-1";
  66. /** the counter for object numbering */
  67. protected int objectcount;
  68. /** the logger instance */
  69. private Log log = LogFactory.getLog("org.apache.fop.pdf");
  70. /** the current character position */
  71. protected long position;
  72. /** the character position of each object */
  73. protected List<Long> indirectObjectOffsets = new ArrayList<Long>();
  74. protected List<PDFStructElem> structureTreeElements;
  75. /** List of objects to write in the trailer */
  76. protected List<PDFObject> trailerObjects = new ArrayList<PDFObject>();
  77. /** the objects themselves */
  78. protected List<PDFObject> objects = new LinkedList<PDFObject>();
  79. /** Controls the PDF version of this document */
  80. private VersionController versionController;
  81. /** Indicates which PDF profiles are active (PDF/A, PDF/X etc.) */
  82. private PDFProfile pdfProfile = new PDFProfile(this);
  83. /** the /Root object */
  84. private PDFRoot root;
  85. /** The root outline object */
  86. private PDFOutline outlineRoot;
  87. /** The /Pages object (mark-fop@inomial.com) */
  88. private PDFPages pages;
  89. /** the /Info object */
  90. private PDFInfo info;
  91. /** the /Resources object */
  92. private PDFResources resources;
  93. /** the document's encryption, if it exists */
  94. private PDFEncryption encryption;
  95. /** the colorspace (0=RGB, 1=CMYK) */
  96. private PDFDeviceColorSpace colorspace
  97. = new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_RGB);
  98. /** the counter for Pattern name numbering (e.g. 'Pattern1') */
  99. private int patternCount;
  100. /** the counter for Shading name numbering */
  101. private int shadingCount;
  102. /** the counter for XObject numbering */
  103. private int xObjectCount;
  104. protected int gStateObjectCount;
  105. /* TODO: Should be modified (works only for image subtype) */
  106. private Map<String, PDFXObject> xObjectsMap = new HashMap<String, PDFXObject>();
  107. private SoftMapCache xObjectsMapFast = new SoftMapCache(false);
  108. private Map<String, PDFFont> fontMap = new HashMap<String, PDFFont>();
  109. private Map<String, List<String>> filterMap = new HashMap<String, List<String>>();
  110. private List<PDFGState> gstates = new ArrayList<PDFGState>();
  111. private List<PDFFunction> functions = new ArrayList<PDFFunction>();
  112. private List<PDFShading> shadings = new ArrayList<PDFShading>();
  113. private List<PDFPattern> patterns = new ArrayList<PDFPattern>();
  114. private List<PDFLink> links = new ArrayList<PDFLink>();
  115. private List<PDFDestination> destinations;
  116. private List<PDFFileSpec> filespecs = new ArrayList<PDFFileSpec>();
  117. private List<PDFGoToRemote> gotoremotes = new ArrayList<PDFGoToRemote>();
  118. private List<PDFGoTo> gotos = new ArrayList<PDFGoTo>();
  119. private List<PDFLaunch> launches = new ArrayList<PDFLaunch>();
  120. protected List<PDFPage> pageObjs = new ArrayList<PDFPage>();
  121. private List<PDFLayer> layers;
  122. private List<PDFNavigator> navigators;
  123. private List<PDFNavigatorAction> navigatorActions;
  124. private PDFFactory factory;
  125. private FileIDGenerator fileIDGenerator;
  126. private boolean accessibilityEnabled;
  127. private boolean mergeFontsEnabled;
  128. private boolean linearizationEnabled;
  129. private boolean formXObjectEnabled;
  130. protected boolean outputStarted;
  131. /**
  132. * Creates an empty PDF document.
  133. *
  134. * The constructor creates a /Root and /Pages object to
  135. * track the document but does not write these objects until
  136. * the trailer is written. Note that the object ID of the
  137. * pages object is determined now, and the xref table is
  138. * updated later. This allows Pages to refer to their
  139. * Parent before we write it out.
  140. *
  141. * @param prod the name of the producer of this pdf document
  142. */
  143. public PDFDocument(String prod) {
  144. this(prod, null);
  145. versionController = VersionController.getDynamicVersionController(Version.V1_4, this);
  146. }
  147. /**
  148. * Creates an empty PDF document.
  149. *
  150. * The constructor creates a /Root and /Pages object to
  151. * track the document but does not write these objects until
  152. * the trailer is written. Note that the object ID of the
  153. * pages object is determined now, and the xref table is
  154. * updated later. This allows Pages to refer to their
  155. * Parent before we write it out.
  156. *
  157. * @param prod the name of the producer of this pdf document
  158. * @param versionController the version controller of this PDF document
  159. */
  160. public PDFDocument(String prod, VersionController versionController) {
  161. this.factory = new PDFFactory(this);
  162. /* create the /Root, /Info and /Resources objects */
  163. this.pages = getFactory().makePages();
  164. // Create the Root object
  165. this.root = getFactory().makeRoot(this.pages);
  166. // Create the Resources object
  167. this.resources = getFactory().makeResources();
  168. // Make the /Info record
  169. this.info = getFactory().makeInfo(prod);
  170. this.versionController = versionController;
  171. }
  172. /**
  173. * Returns the current PDF version.
  174. *
  175. * @return returns the PDF version
  176. */
  177. public Version getPDFVersion() {
  178. return versionController.getPDFVersion();
  179. }
  180. /**
  181. * Sets the PDF version of this document.
  182. *
  183. * @param version the PDF version
  184. * @throws IllegalStateException if the version of this PDF is not allowed to change.
  185. */
  186. public void setPDFVersion(Version version) {
  187. versionController.setPDFVersion(version);
  188. }
  189. /** @return the String representing the current PDF version */
  190. public String getPDFVersionString() {
  191. return versionController.getPDFVersion().toString();
  192. }
  193. /** @return the PDF profile currently active. */
  194. public PDFProfile getProfile() {
  195. return this.pdfProfile;
  196. }
  197. /**
  198. * Returns the factory for PDF objects.
  199. *
  200. * @return the {@link PDFFactory} object
  201. */
  202. public PDFFactory getFactory() {
  203. return this.factory;
  204. }
  205. /**
  206. * Converts text to a byte array for writing to a PDF file.
  207. *
  208. * @param text text to convert/encode
  209. * @return the resulting <code>byte</code> array
  210. */
  211. public static byte[] encode(String text) {
  212. try {
  213. return text.getBytes(ENCODING);
  214. } catch (UnsupportedEncodingException uee) {
  215. return text.getBytes();
  216. }
  217. }
  218. /**
  219. * Flushes the given text buffer to an output stream with the right encoding and resets
  220. * the text buffer. This is used to efficiently switch between outputting text and binary
  221. * content.
  222. * @param textBuffer the text buffer
  223. * @param out the output stream to flush the text content to
  224. * @throws IOException if an I/O error occurs while writing to the output stream
  225. */
  226. public static void flushTextBuffer(StringBuilder textBuffer, OutputStream out)
  227. throws IOException {
  228. out.write(encode(textBuffer.toString()));
  229. textBuffer.setLength(0);
  230. }
  231. /**
  232. * Sets the producer of the document.
  233. *
  234. * @param producer string indicating application producing the PDF
  235. */
  236. public void setProducer(String producer) {
  237. this.info.setProducer(producer);
  238. }
  239. /**
  240. * Sets the creation date of the document.
  241. *
  242. * @param date Date to be stored as creation date in the PDF.
  243. */
  244. public void setCreationDate(Date date) {
  245. this.info.setCreationDate(date);
  246. }
  247. /**
  248. * Sets the creator of the document.
  249. *
  250. * @param creator string indicating application creating the document
  251. */
  252. public void setCreator(String creator) {
  253. this.info.setCreator(creator);
  254. }
  255. /**
  256. * Sets the filter map to use for filters in this document.
  257. *
  258. * @param map the map of filter lists for each stream type
  259. */
  260. public void setFilterMap(Map<String, List<String>> map) {
  261. this.filterMap = map;
  262. }
  263. /**
  264. * Returns the {@link PDFFilter}s map used for filters in this document.
  265. *
  266. * @return the map of filters being used
  267. */
  268. public Map<String, List<String>> getFilterMap() {
  269. return this.filterMap;
  270. }
  271. /**
  272. * Returns the {@link PDFPages} object associated with the root object.
  273. *
  274. * @return the {@link PDFPages} object
  275. */
  276. public PDFPages getPages() {
  277. return this.pages;
  278. }
  279. /**
  280. * Get the {@link PDFRoot} object for this document.
  281. *
  282. * @return the {@link PDFRoot} object
  283. */
  284. public PDFRoot getRoot() {
  285. return this.root;
  286. }
  287. /**
  288. * Get the Structural Tree Collection for this document
  289. * @return
  290. */
  291. public List<PDFStructElem> getStructureTreeElements() {
  292. return structureTreeElements;
  293. }
  294. /**
  295. * Creates and returns a StructTreeRoot object.
  296. *
  297. * @param parentTree the value of the ParenTree entry
  298. * @return the structure tree root
  299. */
  300. public PDFStructTreeRoot makeStructTreeRoot(PDFParentTree parentTree) {
  301. PDFStructTreeRoot structTreeRoot = new PDFStructTreeRoot(parentTree);
  302. assignObjectNumber(structTreeRoot);
  303. addTrailerObject(structTreeRoot);
  304. root.setStructTreeRoot(structTreeRoot);
  305. structureTreeElements = new ArrayList<PDFStructElem>();
  306. return structTreeRoot;
  307. }
  308. /**
  309. * Adds the given element to the structure tree.
  310. */
  311. public void registerStructureElement(PDFStructElem structElem) {
  312. assignObjectNumber(structElem);
  313. structureTreeElements.add(structElem);
  314. }
  315. /**
  316. * Assigns the given scope to the given element and adds it to the structure tree. The
  317. * scope may not be added if it's not compatible with this document's PDF version.
  318. */
  319. public void registerStructureElement(PDFStructElem structElem, Scope scope) {
  320. registerStructureElement(structElem);
  321. versionController.addTableHeaderScopeAttribute(structElem, scope);
  322. }
  323. /**
  324. * Get the {@link PDFInfo} object for this document.
  325. *
  326. * @return the {@link PDFInfo} object
  327. */
  328. public PDFInfo getInfo() {
  329. return this.info;
  330. }
  331. /**
  332. * Registers a {@link PDFObject} in this PDF document.
  333. * The object is assigned a new object number.
  334. *
  335. * @param obj {@link PDFObject} to add
  336. * @return the added {@link PDFObject} added (with its object number set)
  337. */
  338. public PDFObject registerObject(PDFObject obj) {
  339. assignObjectNumber(obj);
  340. addObject(obj);
  341. if (obj instanceof AbstractPDFStream) {
  342. ((AbstractPDFStream) obj).registerChildren();
  343. }
  344. return obj;
  345. }
  346. /**
  347. * Registers a {@link PDFObject} in this PDF document at end.
  348. * The object is assigned a new object number.
  349. *
  350. * @param obj {@link PDFObject} to add
  351. * @return the added {@link PDFObject} added (with its object number set)
  352. */
  353. <T extends PDFObject> T registerTrailerObject(T obj) {
  354. assignObjectNumber(obj);
  355. addTrailerObject(obj);
  356. return obj;
  357. }
  358. /**
  359. * Assigns the {@link PDFObject} an object number,
  360. * and sets the parent of the {@link PDFObject} to this document.
  361. *
  362. * @param obj {@link PDFObject} to assign a number to
  363. */
  364. public void assignObjectNumber(PDFObject obj) {
  365. if (outputStarted && isLinearizationEnabled()) {
  366. throw new IllegalStateException("Can't assign number after start of output");
  367. }
  368. if (obj == null) {
  369. throw new NullPointerException("obj must not be null");
  370. }
  371. if (obj.hasObjectNumber()) {
  372. throw new IllegalStateException(
  373. "Error registering a PDFObject: "
  374. + "PDFObject already has an object number");
  375. }
  376. PDFDocument currentParent = obj.getDocument();
  377. if (currentParent != null && currentParent != this) {
  378. throw new IllegalStateException(
  379. "Error registering a PDFObject: "
  380. + "PDFObject already has a parent PDFDocument");
  381. }
  382. obj.setObjectNumber(this);
  383. if (currentParent == null) {
  384. obj.setDocument(this);
  385. }
  386. }
  387. /**
  388. * Adds a {@link PDFObject} to this document.
  389. * The object <em>MUST</em> have an object number assigned.
  390. *
  391. * @param obj {@link PDFObject} to add
  392. */
  393. public void addObject(PDFObject obj) {
  394. if (obj == null) {
  395. throw new NullPointerException("obj must not be null");
  396. }
  397. if (!obj.hasObjectNumber()) {
  398. throw new IllegalStateException(
  399. "Error adding a PDFObject: "
  400. + "PDFObject doesn't have an object number");
  401. }
  402. //Add object to list
  403. this.objects.add(obj);
  404. //Add object to special lists where necessary
  405. if (obj instanceof PDFFunction) {
  406. this.functions.add((PDFFunction) obj);
  407. }
  408. if (obj instanceof PDFShading) {
  409. final String shadingName = "Sh" + (++this.shadingCount);
  410. ((PDFShading)obj).setName(shadingName);
  411. this.shadings.add((PDFShading) obj);
  412. }
  413. if (obj instanceof PDFPattern) {
  414. final String patternName = "Pa" + (++this.patternCount);
  415. ((PDFPattern)obj).setName(patternName);
  416. this.patterns.add((PDFPattern) obj);
  417. }
  418. if (obj instanceof PDFFont) {
  419. final PDFFont font = (PDFFont)obj;
  420. this.fontMap.put(font.getName(), font);
  421. }
  422. if (obj instanceof PDFGState) {
  423. this.gstates.add((PDFGState) obj);
  424. }
  425. if (obj instanceof PDFPage) {
  426. this.pages.notifyKidRegistered((PDFPage)obj);
  427. pageObjs.add((PDFPage) obj);
  428. }
  429. if (obj instanceof PDFLaunch) {
  430. this.launches.add((PDFLaunch) obj);
  431. }
  432. if (obj instanceof PDFLink) {
  433. this.links.add((PDFLink) obj);
  434. }
  435. if (obj instanceof PDFFileSpec) {
  436. this.filespecs.add((PDFFileSpec) obj);
  437. }
  438. if (obj instanceof PDFGoToRemote) {
  439. this.gotoremotes.add((PDFGoToRemote) obj);
  440. }
  441. if (obj instanceof PDFLayer) {
  442. if (this.layers == null) {
  443. this.layers = new ArrayList<PDFLayer>();
  444. }
  445. this.layers.add((PDFLayer) obj);
  446. }
  447. if (obj instanceof PDFNavigator) {
  448. if (this.navigators == null) {
  449. this.navigators = new ArrayList<PDFNavigator>();
  450. }
  451. this.navigators.add((PDFNavigator) obj);
  452. }
  453. if (obj instanceof PDFNavigatorAction) {
  454. if (this.navigatorActions == null) {
  455. this.navigatorActions = new ArrayList<PDFNavigatorAction>();
  456. }
  457. this.navigatorActions.add((PDFNavigatorAction) obj);
  458. }
  459. }
  460. /**
  461. * Add trailer object.
  462. * Adds an object to the list of trailer objects.
  463. *
  464. * @param obj the PDF object to add
  465. */
  466. public void addTrailerObject(PDFObject obj) {
  467. this.trailerObjects.add(obj);
  468. if (obj instanceof PDFGoTo) {
  469. this.gotos.add((PDFGoTo) obj);
  470. }
  471. }
  472. /**
  473. * Apply the encryption filter to a PDFStream if encryption is enabled.
  474. *
  475. * @param stream PDFStream to encrypt
  476. */
  477. public void applyEncryption(AbstractPDFStream stream) {
  478. if (isEncryptionActive()) {
  479. this.encryption.applyFilter(stream);
  480. }
  481. }
  482. /**
  483. * Enables PDF encryption.
  484. *
  485. * @param params The encryption parameters for the pdf file
  486. */
  487. public void setEncryption(PDFEncryptionParams params) {
  488. getProfile().verifyEncryptionAllowed();
  489. fileIDGenerator = FileIDGenerator.getRandomFileIDGenerator();
  490. this.encryption = PDFEncryptionManager.newInstance(params, this);
  491. if (this.encryption != null) {
  492. PDFObject pdfObject = (PDFObject)this.encryption;
  493. addTrailerObject(pdfObject);
  494. try {
  495. if (encryption.getPDFVersion().compareTo(versionController.getPDFVersion()) > 0) {
  496. versionController.setPDFVersion(encryption.getPDFVersion());
  497. }
  498. } catch (IllegalStateException ise) {
  499. log.warn("Configured encryption requires PDF version " + encryption.getPDFVersion()
  500. + " but version has been set to " + versionController.getPDFVersion() + ".");
  501. throw ise;
  502. }
  503. } else {
  504. log.warn("PDF encryption is unavailable. PDF will be generated without encryption.");
  505. if (params.getEncryptionLengthInBits() == 256) {
  506. log.warn("Make sure the JCE Unlimited Strength Jurisdiction Policy files are available."
  507. + "AES 256 encryption cannot be performed without them.");
  508. }
  509. }
  510. }
  511. /**
  512. * Indicates whether encryption is active for this PDF or not.
  513. *
  514. * @return boolean True if encryption is active
  515. */
  516. public boolean isEncryptionActive() {
  517. return this.encryption != null;
  518. }
  519. /**
  520. * Returns the active Encryption object.
  521. *
  522. * @return the Encryption object
  523. */
  524. public PDFEncryption getEncryption() {
  525. return this.encryption;
  526. }
  527. private Object findPDFObject(List<? extends PDFObject> list, PDFObject compare) {
  528. for (PDFObject obj : list) {
  529. if (compare.contentEquals(obj)) {
  530. return obj;
  531. }
  532. }
  533. return null;
  534. }
  535. /**
  536. * Looks through the registered functions to see if one that is equal to
  537. * a reference object exists
  538. *
  539. * @param compare reference object
  540. * @return the function if it was found, null otherwise
  541. */
  542. protected PDFFunction findFunction(PDFFunction compare) {
  543. return (PDFFunction)findPDFObject(this.functions, compare);
  544. }
  545. /**
  546. * Looks through the registered shadings to see if one that is equal to
  547. * a reference object exists
  548. *
  549. * @param compare reference object
  550. * @return the shading if it was found, null otherwise
  551. */
  552. protected PDFShading findShading(PDFShading compare) {
  553. return (PDFShading)findPDFObject(this.shadings, compare);
  554. }
  555. /**
  556. * Find a previous pattern.
  557. * The problem with this is for tiling patterns the pattern
  558. * data stream is stored and may use up memory, usually this
  559. * would only be a small amount of data.
  560. *
  561. * @param compare reference object
  562. * @return the shading if it was found, null otherwise
  563. */
  564. protected PDFPattern findPattern(PDFPattern compare) {
  565. return (PDFPattern)findPDFObject(this.patterns, compare);
  566. }
  567. /**
  568. * Finds a font.
  569. *
  570. * @param fontname name of the font
  571. * @return PDFFont the requested font, null if it wasn't found
  572. */
  573. protected PDFFont findFont(String fontname) {
  574. return this.fontMap.get(fontname);
  575. }
  576. /**
  577. * Finds a named destination.
  578. *
  579. * @param compare reference object to use as search template
  580. * @return the link if found, null otherwise
  581. */
  582. protected PDFDestination findDestination(PDFDestination compare) {
  583. int index = getDestinationList().indexOf(compare);
  584. if (index >= 0) {
  585. return getDestinationList().get(index);
  586. } else {
  587. return null;
  588. }
  589. }
  590. /**
  591. * Finds a link.
  592. *
  593. * @param compare reference object to use as search template
  594. * @return the link if found, null otherwise
  595. */
  596. protected PDFLink findLink(PDFLink compare) {
  597. return (PDFLink)findPDFObject(this.links, compare);
  598. }
  599. /**
  600. * Finds a file spec.
  601. *
  602. * @param compare reference object to use as search template
  603. * @return the file spec if found, null otherwise
  604. */
  605. protected PDFFileSpec findFileSpec(PDFFileSpec compare) {
  606. return (PDFFileSpec)findPDFObject(this.filespecs, compare);
  607. }
  608. /**
  609. * Finds a goto remote.
  610. *
  611. * @param compare reference object to use as search template
  612. * @return the goto remote if found, null otherwise
  613. */
  614. protected PDFGoToRemote findGoToRemote(PDFGoToRemote compare) {
  615. return (PDFGoToRemote)findPDFObject(this.gotoremotes, compare);
  616. }
  617. /**
  618. * Finds a goto.
  619. *
  620. * @param compare reference object to use as search template
  621. * @return the goto if found, null otherwise
  622. */
  623. protected PDFGoTo findGoTo(PDFGoTo compare) {
  624. return (PDFGoTo)findPDFObject(this.gotos, compare);
  625. }
  626. /**
  627. * Finds a launch.
  628. *
  629. * @param compare reference object to use as search template
  630. * @return the launch if found, null otherwise
  631. */
  632. protected PDFLaunch findLaunch(PDFLaunch compare) {
  633. return (PDFLaunch) findPDFObject(this.launches, compare);
  634. }
  635. /**
  636. * Looks for an existing GState to use
  637. *
  638. * @param wanted requested features
  639. * @param current currently active features
  640. * @return the GState if found, null otherwise
  641. */
  642. protected PDFGState findGState(PDFGState wanted, PDFGState current) {
  643. PDFGState poss;
  644. for (PDFGState avail : this.gstates) {
  645. poss = new PDFGState();
  646. poss.addValues(current);
  647. poss.addValues(avail);
  648. if (poss.equals(wanted)) {
  649. return avail;
  650. }
  651. }
  652. return null;
  653. }
  654. /**
  655. * Returns the PDF color space object.
  656. *
  657. * @return the color space
  658. */
  659. public PDFDeviceColorSpace getPDFColorSpace() {
  660. return this.colorspace;
  661. }
  662. /**
  663. * Returns the color space.
  664. *
  665. * @return the color space
  666. */
  667. public int getColorSpace() {
  668. return getPDFColorSpace().getColorSpace();
  669. }
  670. /**
  671. * Set the color space.
  672. * This is used when creating gradients.
  673. *
  674. * @param theColorspace the new color space
  675. */
  676. public void setColorSpace(int theColorspace) {
  677. this.colorspace.setColorSpace(theColorspace);
  678. }
  679. /**
  680. * Returns the font map for this document.
  681. *
  682. * @return the map of fonts used in this document
  683. */
  684. public Map<String, PDFFont> getFontMap() {
  685. return this.fontMap;
  686. }
  687. /**
  688. * Get an image from the image map.
  689. *
  690. * @param key the image key to look for
  691. * @return the image or PDFXObject for the key if found
  692. * @deprecated Use getXObject instead (so forms are treated in the same way)
  693. */
  694. @Deprecated
  695. public PDFImageXObject getImage(String key) {
  696. return (PDFImageXObject)getXObject(key);
  697. }
  698. /**
  699. * Get an XObject from the image map.
  700. *
  701. * @param key the XObject key to look for
  702. * @return the PDFXObject for the key if found
  703. */
  704. public PDFXObject getXObject(String key) {
  705. Object xObj = xObjectsMapFast.get(key);
  706. if (xObj != null) {
  707. return (PDFXObject) xObj;
  708. }
  709. return xObjectsMap.get(toHashCode(key));
  710. }
  711. private void putXObject(String key, PDFXObject pdfxObject) {
  712. xObjectsMapFast.clear();
  713. xObjectsMapFast.put(key, pdfxObject);
  714. xObjectsMap.put(toHashCode(key), pdfxObject);
  715. }
  716. private String toHashCode(String key) {
  717. if (key.length() < 1024) {
  718. return key;
  719. }
  720. try {
  721. MessageDigest md = MessageDigest.getInstance("MD5");
  722. byte[] thedigest = md.digest(key.getBytes("UTF-8"));
  723. StringBuilder hex = new StringBuilder();
  724. for (byte b : thedigest) {
  725. hex.append(String.format("%02x", b));
  726. }
  727. return hex.toString();
  728. } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
  729. throw new RuntimeException(e);
  730. }
  731. }
  732. /**
  733. * Adds a destination to the document.
  734. * @param destination the destination object
  735. */
  736. public void addDestination(PDFDestination destination) {
  737. if (this.destinations == null) {
  738. this.destinations = new ArrayList<PDFDestination>();
  739. }
  740. this.destinations.add(destination);
  741. }
  742. /**
  743. * Gets the list of named destinations.
  744. *
  745. * @return the list of named destinations.
  746. */
  747. public List<PDFDestination> getDestinationList() {
  748. if (hasDestinations()) {
  749. return this.destinations;
  750. } else {
  751. return Collections.emptyList();
  752. }
  753. }
  754. /**
  755. * Gets whether the document has named destinations.
  756. *
  757. * @return whether the document has named destinations.
  758. */
  759. public boolean hasDestinations() {
  760. return this.destinations != null && !this.destinations.isEmpty();
  761. }
  762. /**
  763. * Add an image to the PDF document.
  764. * This adds an image to the PDF objects.
  765. * If an image with the same key already exists it will return the
  766. * old {@link PDFXObject}.
  767. *
  768. * @param res the PDF resource context to add to, may be null
  769. * @param img the PDF image to add
  770. * @return the PDF XObject that references the PDF image data
  771. */
  772. public PDFImageXObject addImage(PDFResourceContext res, PDFImage img) {
  773. // check if already created
  774. String key = img.getKey();
  775. PDFImageXObject xObject = (PDFImageXObject)getXObject(key);
  776. if (xObject != null) {
  777. if (res != null) {
  778. res.addXObject(xObject);
  779. }
  780. return xObject;
  781. }
  782. // setup image
  783. img.setup(this);
  784. // create a new XObject
  785. xObject = new PDFImageXObject(++this.xObjectCount, img);
  786. registerObject(xObject);
  787. this.resources.addXObject(xObject);
  788. if (res != null) {
  789. res.addXObject(xObject);
  790. }
  791. putXObject(key, xObject);
  792. return xObject;
  793. }
  794. /**
  795. * Add a form XObject to the PDF document.
  796. * This adds a Form XObject to the PDF objects.
  797. * If a Form XObject with the same key already exists it will return the
  798. * old {@link PDFFormXObject}.
  799. *
  800. * @param res the PDF resource context to add to, may be null
  801. * @param cont the PDF Stream contents of the Form XObject
  802. * @param formres a reference to the PDF Resources for the Form XObject data
  803. * @param key the key for the object
  804. * @return the PDF Form XObject that references the PDF data
  805. */
  806. public PDFFormXObject addFormXObject(
  807. PDFResourceContext res,
  808. PDFStream cont,
  809. PDFReference formres,
  810. String key) {
  811. // check if already created
  812. PDFFormXObject xObject = (PDFFormXObject)getXObject(key);
  813. if (xObject != null) {
  814. if (res != null) {
  815. res.addXObject(xObject);
  816. }
  817. return xObject;
  818. }
  819. xObject = new PDFFormXObject(
  820. ++this.xObjectCount,
  821. cont,
  822. formres);
  823. registerObject(xObject);
  824. this.resources.addXObject(xObject);
  825. if (res != null) {
  826. res.addXObject(xObject);
  827. }
  828. putXObject(key, xObject);
  829. return xObject;
  830. }
  831. /**
  832. * Get the root Outlines object. This method does not write
  833. * the outline to the PDF document, it simply creates a
  834. * reference for later.
  835. *
  836. * @return the PDF Outline root object
  837. */
  838. public PDFOutline getOutlineRoot() {
  839. if (this.outlineRoot != null) {
  840. return this.outlineRoot;
  841. }
  842. this.outlineRoot = new PDFOutline(null, null, true);
  843. assignObjectNumber(this.outlineRoot);
  844. addTrailerObject(this.outlineRoot);
  845. this.root.setRootOutline(this.outlineRoot);
  846. return this.outlineRoot;
  847. }
  848. /**
  849. * Get the /Resources object for the document
  850. *
  851. * @return the /Resources object
  852. */
  853. public PDFResources getResources() {
  854. return this.resources;
  855. }
  856. public void enableAccessibility(boolean enableAccessibility) {
  857. this.accessibilityEnabled = enableAccessibility;
  858. }
  859. /**
  860. *
  861. */
  862. public PDFReference resolveExtensionReference(String id) {
  863. if (layers != null) {
  864. for (PDFLayer layer : layers) {
  865. if (layer.hasId(id)) {
  866. return layer.makeReference();
  867. }
  868. }
  869. }
  870. if (navigators != null) {
  871. for (PDFNavigator navigator : navigators) {
  872. if (navigator.hasId(id)) {
  873. return navigator.makeReference();
  874. }
  875. }
  876. }
  877. if (navigatorActions != null) {
  878. for (PDFNavigatorAction action : navigatorActions) {
  879. if (action.hasId(id)) {
  880. return action.makeReference();
  881. }
  882. }
  883. }
  884. return null;
  885. }
  886. /**
  887. * Writes out the entire document
  888. *
  889. * @param stream the OutputStream to output the document to
  890. * @throws IOException if there is an exception writing to the output stream
  891. */
  892. public void output(OutputStream stream) throws IOException {
  893. outputStarted = true;
  894. //Write out objects until the list is empty. This approach (used with a
  895. //LinkedList) allows for output() methods to create and register objects
  896. //on the fly even during serialization.
  897. while (this.objects.size() > 0) {
  898. PDFObject object = this.objects.remove(0);
  899. streamIndirectObject(object, stream);
  900. }
  901. }
  902. protected void writeTrailer(OutputStream stream, int first, int last, int size, long mainOffset, long startxref)
  903. throws IOException {
  904. TrailerOutputHelper trailerOutputHelper = mayCompressStructureTreeElements()
  905. ? new CompressedTrailerOutputHelper()
  906. : new UncompressedTrailerOutputHelper();
  907. if (structureTreeElements != null) {
  908. trailerOutputHelper.outputStructureTreeElements(stream);
  909. }
  910. TrailerDictionary trailerDictionary = createTrailerDictionary(mainOffset != 0);
  911. if (mainOffset != 0) {
  912. trailerDictionary.getDictionary().put("Prev", mainOffset);
  913. }
  914. trailerOutputHelper.outputCrossReferenceObject(stream, trailerDictionary, first, last, size);
  915. String trailer = "\nstartxref\n" + startxref + "\n%%EOF\n";
  916. stream.write(encode(trailer));
  917. }
  918. protected int streamIndirectObject(PDFObject o, OutputStream stream) throws IOException {
  919. outputStarted = true;
  920. recordObjectOffset(o);
  921. int len = outputIndirectObject(o, stream);
  922. this.position += len;
  923. return len;
  924. }
  925. private void streamIndirectObjects(Collection<? extends PDFObject> objects, OutputStream stream)
  926. throws IOException {
  927. for (PDFObject o : objects) {
  928. streamIndirectObject(o, stream);
  929. }
  930. }
  931. private void recordObjectOffset(PDFObject object) {
  932. int index = object.getObjectNumber().getNumber() - 1;
  933. while (indirectObjectOffsets.size() <= index) {
  934. indirectObjectOffsets.add(null);
  935. }
  936. indirectObjectOffsets.set(index, position);
  937. }
  938. /**
  939. * Outputs the given object, wrapped by obj/endobj, to the given stream.
  940. *
  941. * @param object an indirect object, as described in Section 3.2.9 of the PDF 1.5
  942. * Reference.
  943. * @param stream the stream to which the object must be output
  944. * @throws IllegalArgumentException if the object is not an indirect object
  945. */
  946. public static int outputIndirectObject(PDFObject object, OutputStream stream)
  947. throws IOException {
  948. if (!object.hasObjectNumber()) {
  949. throw new IllegalArgumentException("Not an indirect object");
  950. }
  951. byte[] obj = encode(object.getObjectID());
  952. stream.write(obj);
  953. int length = object.output(stream);
  954. byte[] endobj = encode("\nendobj\n");
  955. stream.write(endobj);
  956. return obj.length + length + endobj.length;
  957. }
  958. /**
  959. * Write the PDF header.
  960. *
  961. * This method must be called prior to formatting
  962. * and outputting AreaTrees.
  963. *
  964. * @param stream the OutputStream to write the header to
  965. * @throws IOException if there is an exception writing to the output stream
  966. */
  967. public void outputHeader(OutputStream stream) throws IOException {
  968. this.position = 0;
  969. getProfile().verifyPDFVersion();
  970. byte[] pdf = encode("%PDF-" + getPDFVersionString() + "\n");
  971. stream.write(pdf);
  972. this.position += pdf.length;
  973. // output a binary comment as recommended by the PDF spec (3.4.1)
  974. byte[] bin = {
  975. (byte)'%',
  976. (byte)0xAA,
  977. (byte)0xAB,
  978. (byte)0xAC,
  979. (byte)0xAD,
  980. (byte)'\n' };
  981. stream.write(bin);
  982. this.position += bin.length;
  983. }
  984. /**
  985. * Write the trailer
  986. *
  987. * @param stream the OutputStream to write the trailer to
  988. * @throws IOException if there is an exception writing to the output stream
  989. */
  990. public void outputTrailer(OutputStream stream) throws IOException {
  991. createDestinations();
  992. output(stream);
  993. outputTrailerObjectsAndXref(stream);
  994. }
  995. private void createDestinations() {
  996. if (hasDestinations()) {
  997. Collections.sort(this.destinations, new DestinationComparator());
  998. PDFDests dests = getFactory().makeDests(this.destinations);
  999. if (this.root.getNames() == null) {
  1000. this.root.setNames(getFactory().makeNames());
  1001. }
  1002. this.root.getNames().setDests(dests);
  1003. }
  1004. }
  1005. private void outputTrailerObjectsAndXref(OutputStream stream) throws IOException {
  1006. TrailerOutputHelper trailerOutputHelper = mayCompressStructureTreeElements()
  1007. ? new CompressedTrailerOutputHelper()
  1008. : new UncompressedTrailerOutputHelper();
  1009. if (structureTreeElements != null) {
  1010. trailerOutputHelper.outputStructureTreeElements(stream);
  1011. }
  1012. streamIndirectObjects(trailerObjects, stream);
  1013. TrailerDictionary trailerDictionary = createTrailerDictionary(true);
  1014. long startxref = trailerOutputHelper.outputCrossReferenceObject(stream, trailerDictionary, 0,
  1015. indirectObjectOffsets.size(), indirectObjectOffsets.size());
  1016. String trailer = "\nstartxref\n" + startxref + "\n%%EOF\n";
  1017. stream.write(encode(trailer));
  1018. }
  1019. private boolean mayCompressStructureTreeElements() {
  1020. return accessibilityEnabled
  1021. && versionController.getPDFVersion().compareTo(Version.V1_5) >= 0
  1022. && !isLinearizationEnabled();
  1023. }
  1024. private TrailerDictionary createTrailerDictionary(boolean addRoot) {
  1025. FileIDGenerator gen = getFileIDGenerator();
  1026. TrailerDictionary trailerDictionary = new TrailerDictionary(this);
  1027. if (addRoot) {
  1028. trailerDictionary.setRoot(root).setInfo(info);
  1029. }
  1030. trailerDictionary.setFileID(gen.getOriginalFileID(), gen.getUpdatedFileID());
  1031. if (isEncryptionActive()) {
  1032. trailerDictionary.setEncryption(encryption);
  1033. }
  1034. return trailerDictionary;
  1035. }
  1036. public boolean isMergeFontsEnabled() {
  1037. return mergeFontsEnabled;
  1038. }
  1039. public void setMergeFontsEnabled(boolean mergeFontsEnabled) {
  1040. this.mergeFontsEnabled = mergeFontsEnabled;
  1041. if (mergeFontsEnabled) {
  1042. getResources().createFontsAsObj();
  1043. }
  1044. }
  1045. private interface TrailerOutputHelper {
  1046. void outputStructureTreeElements(OutputStream stream) throws IOException;
  1047. /**
  1048. * @return the offset of the cross-reference object (the value of startxref)
  1049. */
  1050. long outputCrossReferenceObject(OutputStream stream, TrailerDictionary trailerDictionary,
  1051. int first, int last, int size)
  1052. throws IOException;
  1053. }
  1054. private class UncompressedTrailerOutputHelper implements TrailerOutputHelper {
  1055. public void outputStructureTreeElements(OutputStream stream)
  1056. throws IOException {
  1057. streamIndirectObjects(structureTreeElements, stream);
  1058. }
  1059. public long outputCrossReferenceObject(OutputStream stream,
  1060. TrailerDictionary trailerDictionary, int first, int last, int size) throws IOException {
  1061. new CrossReferenceTable(trailerDictionary, position,
  1062. indirectObjectOffsets, first, last, size).output(stream);
  1063. return position;
  1064. }
  1065. }
  1066. private class CompressedTrailerOutputHelper implements TrailerOutputHelper {
  1067. private ObjectStreamManager structureTreeObjectStreams;
  1068. public void outputStructureTreeElements(OutputStream stream)
  1069. throws IOException {
  1070. assert structureTreeElements.size() > 0;
  1071. structureTreeObjectStreams = new ObjectStreamManager(PDFDocument.this);
  1072. for (PDFStructElem structElem : structureTreeElements) {
  1073. structureTreeObjectStreams.add(structElem);
  1074. }
  1075. }
  1076. public long outputCrossReferenceObject(OutputStream stream,
  1077. TrailerDictionary trailerDictionary, int first, int last, int size) throws IOException {
  1078. // Outputting the object streams should not have created new indirect objects
  1079. assert objects.isEmpty();
  1080. new CrossReferenceStream(PDFDocument.this, ++objectcount, trailerDictionary, position,
  1081. indirectObjectOffsets,
  1082. structureTreeObjectStreams.getCompressedObjectReferences())
  1083. .output(stream);
  1084. return position;
  1085. }
  1086. }
  1087. long getCurrentFileSize() {
  1088. return position;
  1089. }
  1090. FileIDGenerator getFileIDGenerator() {
  1091. if (fileIDGenerator == null) {
  1092. try {
  1093. fileIDGenerator = FileIDGenerator.getDigestFileIDGenerator(this);
  1094. } catch (NoSuchAlgorithmException e) {
  1095. fileIDGenerator = FileIDGenerator.getRandomFileIDGenerator();
  1096. }
  1097. }
  1098. return fileIDGenerator;
  1099. }
  1100. public boolean isLinearizationEnabled() {
  1101. return linearizationEnabled;
  1102. }
  1103. public void setLinearizationEnabled(boolean b) {
  1104. linearizationEnabled = b;
  1105. }
  1106. public boolean isFormXObjectEnabled() {
  1107. return formXObjectEnabled;
  1108. }
  1109. public void setFormXObjectEnabled(boolean b) {
  1110. formXObjectEnabled = b;
  1111. }
  1112. }