Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

PDFDocumentGraphics2D.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. * @author <a href="mailto:keiron@aftexsw.com">Keiron Liddle</a>
  47. * @version $Id$
  48. * @see org.apache.fop.svg.PDFGraphics2D
  49. */
  50. public class PDFDocumentGraphics2D extends PDFGraphics2D {
  51. private PDFContext pdfContext;
  52. private int width;
  53. private int height;
  54. //for SVG scaling
  55. private float svgWidth;
  56. private float svgHeight;
  57. /** Normal PDF resolution (72dpi) */
  58. public static final int NORMAL_PDF_RESOLUTION = 72;
  59. /** Default device resolution (300dpi is a resonable quality for most purposes) */
  60. public static final int DEFAULT_NATIVE_DPI = 300;
  61. /**
  62. * The device resolution may be different from the normal target resolution. See
  63. * http://issues.apache.org/bugzilla/show_bug.cgi?id=37305
  64. */
  65. private float deviceDPI = DEFAULT_NATIVE_DPI;
  66. /** Initial clipping area, used to restore to original setting
  67. * when a new page is started. */
  68. protected Shape initialClip;
  69. /**
  70. * Initial transformation matrix, used to restore to original
  71. * setting when a new page is started.
  72. */
  73. protected AffineTransform initialTransform;
  74. /**
  75. * Create a new PDFDocumentGraphics2D.
  76. * This is used to create a new pdf document, the height,
  77. * width and output stream can be setup later.
  78. * For use by the transcoder which needs font information
  79. * for the bridge before the document size is known.
  80. * The resulting document is written to the stream after rendering.
  81. *
  82. * @param textAsShapes set this to true so that text will be rendered
  83. * using curves and not the font.
  84. */
  85. public PDFDocumentGraphics2D(boolean textAsShapes) {
  86. super(textAsShapes);
  87. this.pdfDoc = new PDFDocument("Apache FOP Version " + Version.getVersion()
  88. + ": PDFDocumentGraphics2D");
  89. this.pdfContext = new PDFContext();
  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, null, null);
  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. Color c = col;
  209. PDFColor currentColour = new PDFColor(c.getRed(), c.getGreen(), c.getBlue());
  210. currentStream.write("q\n");
  211. currentStream.write(currentColour.getColorSpaceOut(true));
  212. currentStream.write("0 0 " + width + " " + height + " re\n");
  213. currentStream.write("f\n");
  214. currentStream.write("Q\n");
  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. //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. graphicsState = new PDFState();
  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. AffineTransform at = new AffineTransform(1.0, 0.0, 0.0, -1.0,
  290. 0.0, (double)height);
  291. currentStream.write("1 0 0 -1 0 " + height + " cm\n");
  292. if (svgWidth != 0) {
  293. double scaleX = width / svgWidth;
  294. double scaleY = height / svgHeight;
  295. at.scale(scaleX, scaleY);
  296. currentStream.write("" + PDFNumber.doubleOut(scaleX) + " 0 0 "
  297. + PDFNumber.doubleOut(scaleY) + " 0 0 cm\n");
  298. }
  299. if (deviceDPI != NORMAL_PDF_RESOLUTION) {
  300. double s = NORMAL_PDF_RESOLUTION / deviceDPI;
  301. at.scale(s, s);
  302. currentStream.write("" + PDFNumber.doubleOut(s) + " 0 0 "
  303. + PDFNumber.doubleOut(s) + " 0 0 cm\n");
  304. scale(1 / s, 1 / s);
  305. }
  306. // Remember the transform we installed.
  307. graphicsState.concatenate(at);
  308. pdfContext.increasePageCount();
  309. }
  310. /**
  311. * The rendering process has finished.
  312. * This should be called after the rendering has completed as there is
  313. * no other indication it is complete.
  314. * This will then write the results to the output stream.
  315. * @throws IOException an io exception if there is a problem
  316. * writing to the output stream
  317. */
  318. public void finish() throws IOException {
  319. // restorePDFState();
  320. closePage();
  321. if (fontInfo != null) {
  322. pdfDoc.getResources().addFonts(pdfDoc, fontInfo);
  323. }
  324. this.pdfDoc.output(outputStream);
  325. pdfDoc.outputTrailer(outputStream);
  326. outputStream.flush();
  327. }
  328. /**
  329. * This constructor supports the create method
  330. * @param g the pdf document graphics to make a copy of
  331. */
  332. public PDFDocumentGraphics2D(PDFDocumentGraphics2D g) {
  333. super(g);
  334. this.pdfContext = g.pdfContext;
  335. this.width = g.width;
  336. this.height = g.height;
  337. this.svgWidth = g.svgWidth;
  338. this.svgHeight = g.svgHeight;
  339. }
  340. /**
  341. * Creates a new <code>Graphics</code> object that is
  342. * a copy of this <code>Graphics</code> object.
  343. * @return a new graphics context that is a copy of
  344. * this graphics context.
  345. */
  346. public Graphics create() {
  347. return new PDFDocumentGraphics2D(this);
  348. }
  349. /**
  350. * Draw a string to the pdf document.
  351. * This either draws the string directly or if drawing text as
  352. * shapes it converts the string into shapes and draws that.
  353. * @param s the string to draw
  354. * @param x the x position
  355. * @param y the y position
  356. */
  357. public void drawString(String s, float x, float y) {
  358. if (super.textAsShapes) {
  359. Font font = super.getFont();
  360. FontRenderContext frc = super.getFontRenderContext();
  361. GlyphVector gv = font.createGlyphVector(frc, s);
  362. Shape glyphOutline = gv.getOutline(x, y);
  363. super.fill(glyphOutline);
  364. } else {
  365. super.drawString(s, x, y);
  366. }
  367. }
  368. }