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.

AbstractPDFStream.java 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. import java.io.IOException;
  20. import java.io.OutputStream;
  21. import org.apache.commons.io.output.CountingOutputStream;
  22. import org.apache.fop.util.CloseBlockerOutputStream;
  23. /**
  24. * This is an abstract base class for PDF streams.
  25. */
  26. public abstract class AbstractPDFStream extends PDFObject {
  27. private final PDFDictionary dictionary;
  28. /** The filters that should be applied */
  29. private PDFFilterList filters;
  30. private final boolean encodeOnTheFly;
  31. protected AbstractPDFStream() {
  32. this(true);
  33. }
  34. protected AbstractPDFStream(PDFDictionary dictionary) {
  35. this(dictionary, true);
  36. }
  37. protected AbstractPDFStream(boolean encodeOnTheFly) {
  38. this(new PDFDictionary(), encodeOnTheFly);
  39. }
  40. protected AbstractPDFStream(PDFDictionary dictionary, boolean encodeOnTheFly) {
  41. this.dictionary = dictionary;
  42. this.encodeOnTheFly = encodeOnTheFly;
  43. }
  44. protected final PDFDictionary getDictionary() {
  45. return dictionary;
  46. }
  47. protected Object get(String key) {
  48. return dictionary.get(key);
  49. }
  50. /**
  51. * Puts the given object in the dictionary associated to this stream.
  52. *
  53. * @param key the key in the dictionary
  54. * @param value the value to store
  55. */
  56. public void put(String key, Object value) {
  57. dictionary.put(key, value);
  58. }
  59. /**
  60. * Sets up the default filters for this stream if they haven't been set
  61. * from outside.
  62. */
  63. protected void setupFilterList() {
  64. if (multipleFiltersAllowed() && !getFilterList().isInitialized()) {
  65. getFilterList().addDefaultFilters(
  66. getDocumentSafely().getFilterMap(),
  67. getDefaultFilterName());
  68. }
  69. prepareImplicitFilters();
  70. getDocument().applyEncryption(this);
  71. }
  72. /**
  73. * Returns the name of a suitable filter for this PDF object.
  74. *
  75. * @return the default filter
  76. * @see PDFFilterList
  77. */
  78. protected String getDefaultFilterName() {
  79. return PDFFilterList.DEFAULT_FILTER;
  80. }
  81. /**
  82. * Returns the associated filter list.
  83. * @return the filter list
  84. */
  85. public PDFFilterList getFilterList() {
  86. if (this.filters == null) {
  87. if (getDocument() == null) {
  88. this.filters = new PDFFilterList();
  89. } else {
  90. this.filters = new PDFFilterList(getDocument().isEncryptionActive());
  91. }
  92. boolean hasFilterEntries = (get("Filter") != null);
  93. if (hasFilterEntries) {
  94. this.filters.setDisableAllFilters(true);
  95. }
  96. }
  97. return this.filters;
  98. }
  99. /**
  100. * Returns a value that hints at the size of the encoded stream. This is
  101. * used to optimize buffer allocation so fewer buffer reallocations are
  102. * necessary.
  103. * @return an estimated size (0 if no hint can be given)
  104. * @throws IOException in case of an I/O problem
  105. */
  106. protected abstract int getSizeHint() throws IOException;
  107. /**
  108. * Sends the raw stream data to the target OutputStream.
  109. * @param out OutputStream to write to
  110. * @throws IOException In case of an I/O problem
  111. */
  112. protected abstract void outputRawStreamData(OutputStream out)
  113. throws IOException;
  114. /**
  115. * Output just the stream data enclosed by stream/endstream markers
  116. * @param encodedStream already encoded/filtered stream to write
  117. * @param out OutputStream to write to
  118. * @return int number of bytes written
  119. * @throws IOException in case of an I/O problem
  120. */
  121. protected int outputStreamData(StreamCache encodedStream, OutputStream out) throws IOException {
  122. int length = 0;
  123. byte[] p = encode("stream\n");
  124. out.write(p);
  125. length += p.length;
  126. encodedStream.outputContents(out);
  127. length += encodedStream.getSize();
  128. p = encode("\nendstream");
  129. out.write(p);
  130. length += p.length;
  131. return length;
  132. }
  133. /**
  134. * Encodes the raw data stream for output to a PDF file.
  135. * @return the encoded stream
  136. * @throws IOException in case of an I/O problem
  137. */
  138. protected StreamCache encodeStream() throws IOException {
  139. //Allocate a temporary buffer to find out the size of the encoded stream
  140. final StreamCache encodedStream = StreamCacheFactory.getInstance()
  141. .createStreamCache(getSizeHint());
  142. OutputStream filteredOutput
  143. = getFilterList().applyFilters(encodedStream.getOutputStream());
  144. outputRawStreamData(filteredOutput);
  145. filteredOutput.flush();
  146. filteredOutput.close();
  147. return encodedStream;
  148. }
  149. /**
  150. * Encodes and writes a stream directly to an OutputStream. The length of
  151. * the stream, in this case, is set on a PDFNumber object that has to be
  152. * prepared beforehand.
  153. * @param out OutputStream to write to
  154. * @param refLength PDFNumber object to receive the stream length
  155. * @return number of bytes written (header and trailer included)
  156. * @throws IOException in case of an I/O problem
  157. */
  158. protected int encodeAndWriteStream(OutputStream out, PDFNumber refLength)
  159. throws IOException {
  160. int bytesWritten = 0;
  161. //Stream header
  162. byte[] buf = encode("stream\n");
  163. out.write(buf);
  164. bytesWritten += buf.length;
  165. //Stream contents
  166. CloseBlockerOutputStream cbout = new CloseBlockerOutputStream(out);
  167. CountingOutputStream cout = new CountingOutputStream(cbout);
  168. OutputStream filteredOutput = getFilterList().applyFilters(cout);
  169. outputRawStreamData(filteredOutput);
  170. filteredOutput.close();
  171. refLength.setNumber(Integer.valueOf(cout.getCount()));
  172. bytesWritten += cout.getCount();
  173. //Stream trailer
  174. buf = encode("\nendstream");
  175. out.write(buf);
  176. bytesWritten += buf.length;
  177. return bytesWritten;
  178. }
  179. /**
  180. * Overload the base object method so we don't have to copy
  181. * byte arrays around so much
  182. * {@inheritDoc}
  183. */
  184. @Override
  185. public int output(OutputStream stream) throws IOException {
  186. setupFilterList();
  187. CountingOutputStream cout = new CountingOutputStream(stream);
  188. StringBuilder textBuffer = new StringBuilder(64);
  189. StreamCache encodedStream = null;
  190. PDFNumber refLength = null;
  191. final Object lengthEntry;
  192. if (encodeOnTheFly) {
  193. refLength = new PDFNumber();
  194. getDocumentSafely().registerObject(refLength);
  195. lengthEntry = refLength;
  196. } else {
  197. encodedStream = encodeStream();
  198. lengthEntry = Integer.valueOf(encodedStream.getSize() + 1);
  199. }
  200. populateStreamDict(lengthEntry);
  201. dictionary.writeDictionary(cout, textBuffer);
  202. //Send encoded stream to target OutputStream
  203. PDFDocument.flushTextBuffer(textBuffer, cout);
  204. if (encodedStream == null) {
  205. encodeAndWriteStream(cout, refLength);
  206. } else {
  207. outputStreamData(encodedStream, cout);
  208. encodedStream.clear(); //Encoded stream can now be discarded
  209. }
  210. PDFDocument.flushTextBuffer(textBuffer, cout);
  211. return cout.getCount();
  212. }
  213. @Override
  214. public void setDocument(PDFDocument doc) {
  215. dictionary.setDocument(doc);
  216. super.setDocument(doc);
  217. }
  218. /**
  219. * Populates the dictionary with all necessary entries for the stream.
  220. * Override this method if you need additional entries.
  221. * @param lengthEntry value for the /Length entry
  222. */
  223. protected void populateStreamDict(Object lengthEntry) {
  224. put("Length", lengthEntry);
  225. if (!getFilterList().isDisableAllFilters()) {
  226. getFilterList().putFilterDictEntries(dictionary);
  227. }
  228. }
  229. /**
  230. * Prepares implicit filters (such as the DCTFilter for JPEG images). You
  231. * must make sure that the appropriate filters are in the filter list at
  232. * the right places.
  233. */
  234. protected void prepareImplicitFilters() {
  235. //nop: No default implicit filters
  236. }
  237. /**
  238. * Whether multiple filters can be applied.
  239. * @return true if multiple filters allowed
  240. */
  241. protected boolean multipleFiltersAllowed() {
  242. return true;
  243. }
  244. }