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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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.PDFColor;
  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. }
  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. Color c = col;
  208. PDFColor currentColour = new PDFColor(c.getRed(), c.getGreen(), c.getBlue());
  209. currentStream.write("q\n");
  210. currentStream.write(currentColour.getColorSpaceOut(true));
  211. currentStream.write("0 0 " + width + " " + height + " re\n");
  212. currentStream.write("f\n");
  213. currentStream.write("Q\n");
  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. currentStream.write("Q\n");
  230. //Finish page
  231. PDFStream pdfStream = this.pdfDoc.getFactory().makeStream(
  232. PDFFilterList.CONTENT_FILTER, false);
  233. pdfStream.add(getString());
  234. currentStream = null;
  235. this.pdfDoc.registerObject(pdfStream);
  236. pdfContext.getCurrentPage().setContents(pdfStream);
  237. PDFAnnotList annots = pdfContext.getCurrentPage().getAnnotations();
  238. if (annots != null) {
  239. this.pdfDoc.addObject(annots);
  240. }
  241. this.pdfDoc.addObject(pdfContext.getCurrentPage());
  242. pdfContext.clearCurrentPage();
  243. }
  244. /** {@inheritDoc} */
  245. protected void preparePainting() {
  246. if (pdfContext.isPagePending()) {
  247. return;
  248. }
  249. //Setup default font info if no more font configuration has been done by the user.
  250. if (!this.textAsShapes && getFontInfo() == null) {
  251. setupDefaultFontInfo();
  252. }
  253. try {
  254. startPage();
  255. } catch (IOException ioe) {
  256. handleIOException(ioe);
  257. }
  258. }
  259. /**
  260. * Called to prepare a new page
  261. * @throws IOException if starting the new page fails due to I/O errors.
  262. */
  263. protected void startPage() throws IOException {
  264. if (pdfContext.isPagePending()) {
  265. throw new IllegalStateException("Close page first before starting another");
  266. }
  267. //Start page
  268. paintingState = new PDFPaintingState();
  269. if (this.initialTransform == null) {
  270. //Save initial transformation matrix
  271. this.initialTransform = getTransform();
  272. this.initialClip = getClip();
  273. } else {
  274. //Reset transformation matrix
  275. setTransform(this.initialTransform);
  276. setClip(this.initialClip);
  277. }
  278. currentFontName = "";
  279. currentFontSize = 0;
  280. if (currentStream == null) {
  281. currentStream = new StringWriter();
  282. }
  283. PDFResources pdfResources = this.pdfDoc.getResources();
  284. PDFPage page = this.pdfDoc.getFactory().makePage(pdfResources,
  285. width, height);
  286. resourceContext = page;
  287. pdfContext.setCurrentPage(page);
  288. pageRef = page.referencePDF();
  289. currentStream.write("q\n");
  290. AffineTransform at = new AffineTransform(1.0, 0.0, 0.0, -1.0,
  291. 0.0, height);
  292. currentStream.write("1 0 0 -1 0 " + height + " cm\n");
  293. if (svgWidth != 0) {
  294. double scaleX = width / svgWidth;
  295. double scaleY = height / svgHeight;
  296. at.scale(scaleX, scaleY);
  297. currentStream.write("" + PDFNumber.doubleOut(scaleX) + " 0 0 "
  298. + PDFNumber.doubleOut(scaleY) + " 0 0 cm\n");
  299. }
  300. if (deviceDPI != NORMAL_PDF_RESOLUTION) {
  301. double s = NORMAL_PDF_RESOLUTION / deviceDPI;
  302. at.scale(s, s);
  303. currentStream.write("" + PDFNumber.doubleOut(s) + " 0 0 "
  304. + PDFNumber.doubleOut(s) + " 0 0 cm\n");
  305. scale(1 / s, 1 / s);
  306. }
  307. // Remember the transform we installed.
  308. paintingState.concatenate(at);
  309. pdfContext.increasePageCount();
  310. }
  311. /**
  312. * The rendering process has finished.
  313. * This should be called after the rendering has completed as there is
  314. * no other indication it is complete.
  315. * This will then write the results to the output stream.
  316. * @throws IOException an io exception if there is a problem
  317. * writing to the output stream
  318. */
  319. public void finish() throws IOException {
  320. // restorePDFState();
  321. closePage();
  322. if (fontInfo != null) {
  323. pdfDoc.getResources().addFonts(pdfDoc, fontInfo);
  324. }
  325. this.pdfDoc.output(outputStream);
  326. pdfDoc.outputTrailer(outputStream);
  327. outputStream.flush();
  328. }
  329. /**
  330. * This constructor supports the create method
  331. * @param g the pdf document graphics to make a copy of
  332. */
  333. public PDFDocumentGraphics2D(PDFDocumentGraphics2D g) {
  334. super(g);
  335. this.pdfContext = g.pdfContext;
  336. this.width = g.width;
  337. this.height = g.height;
  338. this.svgWidth = g.svgWidth;
  339. this.svgHeight = g.svgHeight;
  340. }
  341. /**
  342. * Creates a new <code>Graphics</code> object that is
  343. * a copy of this <code>Graphics</code> object.
  344. * @return a new graphics context that is a copy of
  345. * this graphics context.
  346. */
  347. public Graphics create() {
  348. return new PDFDocumentGraphics2D(this);
  349. }
  350. /**
  351. * Draw a string to the pdf document.
  352. * This either draws the string directly or if drawing text as
  353. * shapes it converts the string into shapes and draws that.
  354. * @param s the string to draw
  355. * @param x the x position
  356. * @param y the y position
  357. */
  358. public void drawString(String s, float x, float y) {
  359. if (super.textAsShapes) {
  360. Font font = super.getFont();
  361. FontRenderContext frc = super.getFontRenderContext();
  362. GlyphVector gv = font.createGlyphVector(frc, s);
  363. Shape glyphOutline = gv.getOutline(x, y);
  364. super.fill(glyphOutline);
  365. } else {
  366. super.drawString(s, x, y);
  367. }
  368. }
  369. }