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.

PDFObject.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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.util.Set;
  23. import org.apache.commons.logging.Log;
  24. import org.apache.commons.logging.LogFactory;
  25. /**
  26. * generic PDF object.
  27. *
  28. * A PDF Document is essentially a collection of these objects. A PDF
  29. * Object has a number and a generation (although the generation will always
  30. * be 0 in new documents).
  31. */
  32. public abstract class PDFObject implements PDFWritable {
  33. /** logger for all PDFObjects (and descendants) */
  34. protected static final Log log = LogFactory.getLog(PDFObject.class.getName());
  35. /**
  36. * the object's number
  37. */
  38. private boolean hasObjNum;
  39. private PDFObjectNumber objNum = new PDFObjectNumber();
  40. /**
  41. * the object's generation (0 in new documents)
  42. */
  43. private int generation;
  44. /**
  45. * the parent PDFDocument
  46. */
  47. private PDFDocument document;
  48. /** the parent PDFObject (may be null and may not always be set, needed for encryption) */
  49. private PDFObject parent;
  50. /**
  51. * Returns the object's number.
  52. * @return the PDF Object number
  53. */
  54. public PDFObjectNumber getObjectNumber() {
  55. if (!hasObjNum) {
  56. throw new IllegalStateException("Object has no number assigned: " + this.toString());
  57. }
  58. return objNum;
  59. }
  60. /**
  61. * Default constructor.
  62. */
  63. public PDFObject() {
  64. //nop
  65. }
  66. /**
  67. * Constructor for direct objects.
  68. * @param parent the containing PDFObject instance
  69. */
  70. public PDFObject(PDFObject parent) {
  71. setParent(parent);
  72. }
  73. /**
  74. * Indicates whether this PDFObject has already been assigned an
  75. * object number.
  76. * @return True if it has an object number
  77. */
  78. public boolean hasObjectNumber() {
  79. return hasObjNum;
  80. }
  81. /**
  82. * Sets the object number
  83. */
  84. public void setObjectNumber(PDFDocument document) {
  85. objNum.setDocument(document);
  86. hasObjNum = true;
  87. PDFDocument doc = getDocument();
  88. setParent(null);
  89. setDocument(doc); //Restore reference to PDFDocument after setting parent to null
  90. if (log.isTraceEnabled()) {
  91. log.trace("Assigning " + this + " object number " + objNum);
  92. }
  93. }
  94. public void setObjectNumber(PDFObjectNumber objectNumber) {
  95. objNum = objectNumber;
  96. hasObjNum = true;
  97. }
  98. public void setObjectNumber(int objectNumber) {
  99. objNum = new PDFObjectNumber(objectNumber);
  100. hasObjNum = true;
  101. }
  102. /**
  103. * Returns this object's generation.
  104. * @return the PDF Object generation
  105. */
  106. public int getGeneration() {
  107. return this.generation;
  108. }
  109. /**
  110. * Returns the parent PDFDocument if assigned.
  111. * @return the parent PDFDocument (May be null if the parent PDFDocument
  112. * has not been assigned)
  113. */
  114. public final PDFDocument getDocument() {
  115. if (this.document != null) {
  116. return this.document;
  117. } else if (getParent() != null) {
  118. return getParent().getDocument();
  119. } else {
  120. return null;
  121. }
  122. }
  123. /**
  124. * Returns the parent PDFDocument, but unlike <code>getDocument()</code>
  125. * it throws an informative Exception if the parent document is unavailable
  126. * instead of having a NullPointerException somewhere without a message.
  127. * @return the parent PDFDocument
  128. */
  129. public final PDFDocument getDocumentSafely() {
  130. final PDFDocument doc = getDocument();
  131. if (doc == null) {
  132. throw new IllegalStateException("Parent PDFDocument is unavailable on "
  133. + getClass().getName());
  134. }
  135. return doc;
  136. }
  137. /**
  138. * Sets the parent PDFDocument.
  139. * @param doc the PDFDocument.
  140. */
  141. public void setDocument(PDFDocument doc) {
  142. this.document = doc;
  143. }
  144. /**
  145. * Returns this objects's parent. The parent is null if it is a "direct object".
  146. * @return the parent or null if there's no parent (or it hasn't been set)
  147. */
  148. public PDFObject getParent() {
  149. return this.parent;
  150. }
  151. /**
  152. * Sets the direct parent object.
  153. * @param parent the direct parent
  154. */
  155. public void setParent(PDFObject parent) {
  156. this.parent = parent;
  157. }
  158. /**
  159. * Returns the PDF representation of the Object ID.
  160. * @return the Object ID
  161. */
  162. public String getObjectID() {
  163. return getObjectNumber() + " " + getGeneration() + " obj\n";
  164. }
  165. /**
  166. * Returns the PDF representation of a reference to this object.
  167. * @return the reference string
  168. */
  169. public String referencePDF() {
  170. if (!hasObjectNumber()) {
  171. throw new IllegalArgumentException(
  172. "Cannot reference this object. It doesn't have an object number");
  173. }
  174. return makeReference().toString();
  175. }
  176. /**
  177. * Creates and returns a reference to this object.
  178. * @return the object reference
  179. */
  180. public PDFReference makeReference() {
  181. return new PDFReference(this);
  182. }
  183. /**
  184. * Write the PDF represention of this object
  185. *
  186. * @param stream the stream to write the PDF to
  187. * @throws IOException if there is an error writing to the stream
  188. * @return the number of bytes written
  189. */
  190. public int output(OutputStream stream) throws IOException {
  191. byte[] pdf = this.toPDF();
  192. stream.write(pdf);
  193. return pdf.length;
  194. }
  195. /** {@inheritDoc} */
  196. public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException {
  197. if (hasObjectNumber()) {
  198. textBuffer.append(referencePDF());
  199. } else {
  200. PDFDocument.flushTextBuffer(textBuffer, out);
  201. output(out);
  202. }
  203. }
  204. /**
  205. * Encodes the object as a byte array for output to a PDF file.
  206. *
  207. * @return PDF string
  208. */
  209. protected byte[] toPDF() {
  210. return encode(toPDFString());
  211. }
  212. /**
  213. * This method returns a String representation of the PDF object. The result
  214. * is normally converted/encoded to a byte array by toPDF(). Only use
  215. * this method to implement the serialization if the object can be fully
  216. * represented as text. If the PDF representation of the object contains
  217. * binary content use toPDF() or output(OutputStream) instead. This applies
  218. * to any object potentially containing a string object because string object
  219. * are encrypted and therefore need to be binary.
  220. * @return String the String representation
  221. */
  222. protected String toPDFString() {
  223. throw new UnsupportedOperationException("Not implemented. "
  224. + "Use output(OutputStream) instead.");
  225. }
  226. /**
  227. * Converts text to a byte array for writing to a PDF file.
  228. * @param text text to convert/encode
  229. * @return byte[] the resulting byte array
  230. */
  231. public static final byte[] encode(String text) {
  232. return PDFDocument.encode(text);
  233. }
  234. /**
  235. * Encodes a Text String (3.8.1 in PDF 1.4 specs)
  236. * @param text the text to encode
  237. * @return byte[] the encoded text
  238. */
  239. protected byte[] encodeText(String text) {
  240. if (getDocumentSafely().isEncryptionActive()) {
  241. final byte[] buf = PDFText.toUTF16(text);
  242. return PDFText.escapeByteArray(
  243. getDocument().getEncryption().encrypt(buf, this));
  244. } else {
  245. return encode(PDFText.escapeText(text, false));
  246. }
  247. }
  248. /**
  249. * Encodes a String (3.2.3 in PDF 1.4 specs)
  250. * @param string the string to encode
  251. * @return byte[] the encoded string
  252. */
  253. protected byte[] encodeString(String string) {
  254. return encodeText(string);
  255. }
  256. /**
  257. * Encodes binary data as hexadecimal string object.
  258. * @param data the binary data
  259. * @param out the OutputStream to write the encoded object to
  260. * @throws IOException if an I/O error occurs
  261. */
  262. protected void encodeBinaryToHexString(byte[] data, OutputStream out) throws IOException {
  263. out.write('<');
  264. if (getDocumentSafely().isEncryptionActive()) {
  265. data = getDocument().getEncryption().encrypt(data, this);
  266. }
  267. String hex = PDFText.toHex(data, false);
  268. byte[] encoded = hex.getBytes("US-ASCII");
  269. out.write(encoded);
  270. out.write('>');
  271. }
  272. /**
  273. * Formats an object for serialization to PDF.
  274. * <p>
  275. * IMPORTANT: If you need to write out binary output, call
  276. * {@link PDFDocument#flushTextBuffer(StringBuilder, OutputStream)} before writing any content
  277. * to the {@link OutputStream}!
  278. * @param obj the object
  279. * @param out the OutputStream to write to
  280. * @param textBuffer a text buffer for text output
  281. * @throws IOException If an I/O error occurs
  282. */
  283. protected void formatObject(Object obj, OutputStream out, StringBuilder textBuffer)
  284. throws IOException {
  285. if (obj == null) {
  286. textBuffer.append("null");
  287. } else if (obj instanceof PDFWritable) {
  288. ((PDFWritable)obj).outputInline(out, textBuffer);
  289. } else if (obj instanceof Number) {
  290. if (obj instanceof Double || obj instanceof Float) {
  291. textBuffer.append(PDFNumber.doubleOut(((Number)obj).doubleValue()));
  292. } else {
  293. textBuffer.append(obj.toString());
  294. }
  295. } else if (obj instanceof Boolean) {
  296. textBuffer.append(obj.toString());
  297. } else if (obj instanceof byte[]) {
  298. PDFDocument.flushTextBuffer(textBuffer, out);
  299. encodeBinaryToHexString((byte[])obj, out);
  300. } else {
  301. PDFDocument.flushTextBuffer(textBuffer, out);
  302. out.write(encodeText(obj.toString()));
  303. }
  304. }
  305. /**
  306. * Check if the other PDFObject has the same content as the current object.
  307. * <p>
  308. * Note: This function has a contract which is less binding than
  309. * {@link #equals(Object)}. Whereas equals would require all values to be
  310. * identical, this method is not required to check everything. In the case
  311. * of PDFObjects, this means that the overriding function does not have to
  312. * check for {@link #getObjectID()}.
  313. *
  314. * @param o
  315. * object to compare to.
  316. * @return true if the other object has the same content.
  317. */
  318. protected boolean contentEquals(PDFObject o) {
  319. return this.equals(o);
  320. }
  321. public void getChildren(Set<PDFObject> children) {
  322. }
  323. }