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

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