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 13KB

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