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

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