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.

PDFDocumentGraphics2D.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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.svg;
  19. import java.awt.Color;
  20. import java.awt.Font;
  21. import java.awt.Graphics;
  22. import java.awt.Shape;
  23. import java.awt.font.FontRenderContext;
  24. import java.awt.font.GlyphVector;
  25. import java.awt.geom.AffineTransform;
  26. import java.io.IOException;
  27. import java.io.OutputStream;
  28. import java.io.StringWriter;
  29. import org.apache.xmlgraphics.image.GraphicsConstants;
  30. import org.apache.fop.Version;
  31. import org.apache.fop.fonts.FontInfo;
  32. import org.apache.fop.fonts.FontSetup;
  33. import org.apache.fop.pdf.PDFAnnotList;
  34. import org.apache.fop.pdf.PDFColorHandler;
  35. import org.apache.fop.pdf.PDFDocument;
  36. import org.apache.fop.pdf.PDFFilterList;
  37. import org.apache.fop.pdf.PDFNumber;
  38. import org.apache.fop.pdf.PDFPage;
  39. import org.apache.fop.pdf.PDFPaintingState;
  40. import org.apache.fop.pdf.PDFResources;
  41. import org.apache.fop.pdf.PDFStream;
  42. /**
  43. * This class is a wrapper for the {@link PDFGraphics2D} that
  44. * is used to create a full document around the PDF rendering from
  45. * {@link PDFGraphics2D}.
  46. *
  47. * @see org.apache.fop.svg.PDFGraphics2D
  48. */
  49. public class PDFDocumentGraphics2D extends PDFGraphics2D {
  50. private final PDFContext pdfContext;
  51. private int width;
  52. private int height;
  53. //for SVG scaling
  54. private float svgWidth;
  55. private float svgHeight;
  56. /** Normal PDF resolution (72dpi) */
  57. public static final int NORMAL_PDF_RESOLUTION = 72;
  58. /** Default device resolution (300dpi is a resonable quality for most purposes) */
  59. public static final int DEFAULT_NATIVE_DPI = GraphicsConstants.DEFAULT_SAMPLE_DPI;
  60. /**
  61. * The device resolution may be different from the normal target resolution. See
  62. * http://issues.apache.org/bugzilla/show_bug.cgi?id=37305
  63. */
  64. private float deviceDPI = DEFAULT_NATIVE_DPI;
  65. /** Initial clipping area, used to restore to original setting
  66. * when a new page is started. */
  67. protected Shape initialClip;
  68. /**
  69. * Initial transformation matrix, used to restore to original
  70. * setting when a new page is started.
  71. */
  72. protected AffineTransform initialTransform;
  73. /**
  74. * Create a new PDFDocumentGraphics2D.
  75. * This is used to create a new pdf document, the height,
  76. * width and output stream can be setup later.
  77. * For use by the transcoder which needs font information
  78. * for the bridge before the document size is known.
  79. * The resulting document is written to the stream after rendering.
  80. *
  81. * @param textAsShapes set this to true so that text will be rendered
  82. * using curves and not the font.
  83. */
  84. public PDFDocumentGraphics2D(boolean textAsShapes) {
  85. super(textAsShapes);
  86. this.pdfDoc = new PDFDocument("Apache FOP Version " + Version.getVersion()
  87. + ": PDFDocumentGraphics2D");
  88. this.pdfContext = new PDFContext();
  89. this.colorHandler = new PDFColorHandler(this.pdfDoc.getResources());
  90. }
  91. /**
  92. * Create a new PDFDocumentGraphics2D.
  93. * This is used to create a new pdf document of the given height
  94. * and width.
  95. * The resulting document is written to the stream after rendering.
  96. *
  97. * @param textAsShapes set this to true so that text will be rendered
  98. * using curves and not the font.
  99. * @param stream the stream that the final document should be written to.
  100. * @param width the width of the document
  101. * @param height the height of the document
  102. * @throws IOException an io exception if there is a problem
  103. * writing to the output stream
  104. */
  105. public PDFDocumentGraphics2D(boolean textAsShapes, OutputStream stream,
  106. int width, int height) throws IOException {
  107. this(textAsShapes);
  108. setupDocument(stream, width, height);
  109. }
  110. /**
  111. * Create a new PDFDocumentGraphics2D.
  112. * This is used to create a new pdf document.
  113. * For use by the transcoder which needs font information
  114. * for the bridge before the document size is known.
  115. * The resulting document is written to the stream after rendering.
  116. * This constructor is Avalon-style.
  117. */
  118. public PDFDocumentGraphics2D() {
  119. this(false);
  120. }
  121. /**
  122. * Setup the document.
  123. * @param stream the output stream to write the document
  124. * @param width the width of the page
  125. * @param height the height of the page
  126. * @throws IOException an io exception if there is a problem
  127. * writing to the output stream
  128. */
  129. public void setupDocument(OutputStream stream, int width, int height) throws IOException {
  130. this.width = width;
  131. this.height = height;
  132. pdfDoc.outputHeader(stream);
  133. setOutputStream(stream);
  134. }
  135. /**
  136. * Setup a default FontInfo instance if none has been setup before.
  137. */
  138. public void setupDefaultFontInfo() {
  139. if (fontInfo == null) {
  140. //Default minimal fonts
  141. FontInfo fontInfo = new FontInfo();
  142. FontSetup.setup(fontInfo);
  143. setFontInfo(fontInfo);
  144. }
  145. }
  146. /**
  147. * Set the device resolution for rendering. Will take effect at the
  148. * start of the next page.
  149. * @param deviceDPI the device resolution (in dpi)
  150. */
  151. public void setDeviceDPI(float deviceDPI) {
  152. this.deviceDPI = deviceDPI;
  153. }
  154. /**
  155. * @return the device resolution (in dpi) for rendering.
  156. */
  157. public float getDeviceDPI() {
  158. return deviceDPI;
  159. }
  160. /**
  161. * Sets the font info for this PDF document.
  162. * @param fontInfo the font info object with all the fonts
  163. */
  164. public void setFontInfo(FontInfo fontInfo) {
  165. this.fontInfo = fontInfo;
  166. }
  167. /**
  168. * Get the font info for this pdf document.
  169. * @return the font information
  170. */
  171. public FontInfo getFontInfo() {
  172. return fontInfo;
  173. }
  174. /**
  175. * Get the pdf document created by this class.
  176. * @return the pdf document
  177. */
  178. public PDFDocument getPDFDocument() {
  179. return this.pdfDoc;
  180. }
  181. /**
  182. * Return the PDFContext for this instance.
  183. * @return the PDFContext
  184. */
  185. public PDFContext getPDFContext() {
  186. return this.pdfContext;
  187. }
  188. /**
  189. * Set the dimensions of the svg document that will be drawn.
  190. * This is useful if the dimensions of the svg document are different
  191. * from the pdf document that is to be created.
  192. * The result is scaled so that the svg fits correctly inside the
  193. * pdf document.
  194. * @param w the width of the page
  195. * @param h the height of the page
  196. */
  197. public void setSVGDimension(float w, float h) {
  198. this.svgWidth = w;
  199. this.svgHeight = h;
  200. }
  201. /**
  202. * Set the background of the pdf document.
  203. * This is used to set the background for the pdf document
  204. * Rather than leaving it as the default white.
  205. * @param col the background colour to fill
  206. */
  207. public void setBackgroundColor(Color col) {
  208. StringBuffer sb = new StringBuffer();
  209. sb.append("q\n");
  210. this.colorHandler.establishColor(sb, col, true);
  211. sb.append("0 0 ").append(width).append(" ").append(height).append(" re\n");
  212. sb.append("f\n");
  213. sb.append("Q\n");
  214. currentStream.write(sb.toString());
  215. }
  216. /**
  217. * Is called to prepare the PDFDocumentGraphics2D for the next page to be painted. Basically,
  218. * this closes the current page. A new page is prepared as soon as painting starts.
  219. */
  220. public void nextPage() {
  221. closePage();
  222. }
  223. /**
  224. * Closes the current page and adds it to the PDF file.
  225. */
  226. protected void closePage() {
  227. if (!pdfContext.isPagePending()) {
  228. return; //ignore
  229. }
  230. currentStream.write("Q\n");
  231. //Finish page
  232. PDFStream pdfStream = this.pdfDoc.getFactory().makeStream(
  233. PDFFilterList.CONTENT_FILTER, false);
  234. pdfStream.add(getString());
  235. currentStream = null;
  236. this.pdfDoc.registerObject(pdfStream);
  237. pdfContext.getCurrentPage().setContents(pdfStream);
  238. PDFAnnotList annots = pdfContext.getCurrentPage().getAnnotations();
  239. if (annots != null) {
  240. this.pdfDoc.addObject(annots);
  241. }
  242. this.pdfDoc.addObject(pdfContext.getCurrentPage());
  243. pdfContext.clearCurrentPage();
  244. }
  245. /** {@inheritDoc} */
  246. @Override
  247. protected void preparePainting() {
  248. if (pdfContext.isPagePending()) {
  249. return;
  250. }
  251. //Setup default font info if no more font configuration has been done by the user.
  252. if (!this.textAsShapes && getFontInfo() == null) {
  253. setupDefaultFontInfo();
  254. }
  255. try {
  256. startPage();
  257. } catch (IOException ioe) {
  258. handleIOException(ioe);
  259. }
  260. }
  261. /**
  262. * Called to prepare a new page
  263. * @throws IOException if starting the new page fails due to I/O errors.
  264. */
  265. protected void startPage() throws IOException {
  266. if (pdfContext.isPagePending()) {
  267. throw new IllegalStateException("Close page first before starting another");
  268. }
  269. //Start page
  270. paintingState = new PDFPaintingState();
  271. if (this.initialTransform == null) {
  272. //Save initial transformation matrix
  273. this.initialTransform = getTransform();
  274. this.initialClip = getClip();
  275. } else {
  276. //Reset transformation matrix
  277. setTransform(this.initialTransform);
  278. setClip(this.initialClip);
  279. }
  280. currentFontName = "";
  281. currentFontSize = 0;
  282. if (currentStream == null) {
  283. currentStream = new StringWriter();
  284. }
  285. PDFResources pdfResources = this.pdfDoc.getResources();
  286. PDFPage page = this.pdfDoc.getFactory().makePage(pdfResources,
  287. width, height);
  288. resourceContext = page;
  289. pdfContext.setCurrentPage(page);
  290. pageRef = page.referencePDF();
  291. currentStream.write("q\n");
  292. AffineTransform at = new AffineTransform(1.0, 0.0, 0.0, -1.0,
  293. 0.0, height);
  294. currentStream.write("1 0 0 -1 0 " + height + " cm\n");
  295. if (svgWidth != 0) {
  296. double scaleX = width / svgWidth;
  297. double scaleY = height / svgHeight;
  298. at.scale(scaleX, scaleY);
  299. currentStream.write("" + PDFNumber.doubleOut(scaleX) + " 0 0 "
  300. + PDFNumber.doubleOut(scaleY) + " 0 0 cm\n");
  301. }
  302. if (deviceDPI != NORMAL_PDF_RESOLUTION) {
  303. double s = NORMAL_PDF_RESOLUTION / deviceDPI;
  304. at.scale(s, s);
  305. currentStream.write("" + PDFNumber.doubleOut(s) + " 0 0 "
  306. + PDFNumber.doubleOut(s) + " 0 0 cm\n");
  307. scale(1 / s, 1 / s);
  308. }
  309. // Remember the transform we installed.
  310. paintingState.concatenate(at);
  311. pdfContext.increasePageCount();
  312. }
  313. /**
  314. * The rendering process has finished.
  315. * This should be called after the rendering has completed as there is
  316. * no other indication it is complete.
  317. * This will then write the results to the output stream.
  318. * @throws IOException an io exception if there is a problem
  319. * writing to the output stream
  320. */
  321. public void finish() throws IOException {
  322. // restorePDFState();
  323. closePage();
  324. if (fontInfo != null) {
  325. pdfDoc.getResources().addFonts(pdfDoc, fontInfo);
  326. }
  327. this.pdfDoc.output(outputStream);
  328. pdfDoc.outputTrailer(outputStream);
  329. outputStream.flush();
  330. }
  331. /**
  332. * This constructor supports the create method
  333. * @param g the pdf document graphics to make a copy of
  334. */
  335. public PDFDocumentGraphics2D(PDFDocumentGraphics2D g) {
  336. super(g);
  337. this.pdfContext = g.pdfContext;
  338. this.width = g.width;
  339. this.height = g.height;
  340. this.svgWidth = g.svgWidth;
  341. this.svgHeight = g.svgHeight;
  342. }
  343. /**
  344. * Creates a new <code>Graphics</code> object that is
  345. * a copy of this <code>Graphics</code> object.
  346. * @return a new graphics context that is a copy of
  347. * this graphics context.
  348. */
  349. @Override
  350. public Graphics create() {
  351. preparePainting();
  352. return new PDFDocumentGraphics2D(this);
  353. }
  354. /**
  355. * Draw a string to the pdf document.
  356. * This either draws the string directly or if drawing text as
  357. * shapes it converts the string into shapes and draws that.
  358. * @param s the string to draw
  359. * @param x the x position
  360. * @param y the y position
  361. */
  362. @Override
  363. public void drawString(String s, float x, float y) {
  364. if (super.textAsShapes) {
  365. Font font = super.getFont();
  366. FontRenderContext frc = super.getFontRenderContext();
  367. GlyphVector gv = font.createGlyphVector(frc, s);
  368. Shape glyphOutline = gv.getOutline(x, y);
  369. super.fill(glyphOutline);
  370. } else {
  371. super.drawString(s, x, y);
  372. }
  373. }
  374. }