Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

PDFRenderer.java 43KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304
  1. /*-- $Id$ --
  2. ============================================================================
  3. The Apache Software License, Version 1.1
  4. ============================================================================
  5. Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without modifica-
  7. tion, are permitted provided that the following conditions are met:
  8. 1. Redistributions of source code must retain the above copyright notice,
  9. this list of conditions and the following disclaimer.
  10. 2. Redistributions in binary form must reproduce the above copyright notice,
  11. this list of conditions and the following disclaimer in the documentation
  12. and/or other materials provided with the distribution.
  13. 3. The end-user documentation included with the redistribution, if any, must
  14. include the following acknowledgment: "This product includes software
  15. developed by the Apache Software Foundation (http://www.apache.org/)."
  16. Alternately, this acknowledgment may appear in the software itself, if
  17. and wherever such third-party acknowledgments normally appear.
  18. 4. The names "FOP" and "Apache Software Foundation" must not be used to
  19. endorse or promote products derived from this software without prior
  20. written permission. For written permission, please contact
  21. apache@apache.org.
  22. 5. Products derived from this software may not be called "Apache", nor may
  23. "Apache" appear in their name, without prior written permission of the
  24. Apache Software Foundation.
  25. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  26. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  27. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  29. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
  30. DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  31. OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  32. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  34. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35. This software consists of voluntary contributions made by many individuals
  36. on behalf of the Apache Software Foundation and was originally created by
  37. James Tauber <jtauber@jtauber.com>. For more information on the Apache
  38. Software Foundation, please see <http://www.apache.org/>.
  39. */
  40. package org.apache.fop.render.pdf;
  41. // FOP
  42. import org.apache.fop.render.Renderer;
  43. import org.apache.fop.messaging.MessageHandler;
  44. import org.apache.fop.image.ImageArea;
  45. import org.apache.fop.image.FopImage;
  46. import org.apache.fop.apps.FOPException;
  47. import org.apache.fop.fo.properties.*;
  48. import org.apache.fop.layout.*;
  49. import org.apache.fop.layout.inline.*;
  50. import org.apache.fop.datatypes.*;
  51. import org.apache.fop.svg.*;
  52. import org.apache.fop.pdf.*;
  53. import org.apache.fop.layout.*;
  54. import org.apache.fop.image.*;
  55. import org.apache.fop.configuration.Configuration;
  56. import org.apache.fop.extensions.*;
  57. import org.apache.fop.datatypes.IDReferences;
  58. import org.apache.batik.bridge.*;
  59. import org.apache.batik.swing.svg.*;
  60. import org.apache.batik.swing.gvt.*;
  61. import org.apache.batik.gvt.*;
  62. import org.apache.batik.gvt.renderer.*;
  63. import org.apache.batik.gvt.filter.*;
  64. import org.apache.batik.gvt.event.*;
  65. import org.w3c.dom.*;
  66. import org.w3c.dom.svg.*;
  67. import org.w3c.dom.css.*;
  68. import org.w3c.dom.svg.SVGLength;
  69. // Java
  70. import java.io.IOException;
  71. import java.io.OutputStream;
  72. import java.util.Enumeration;
  73. import java.awt.Rectangle;
  74. import java.util.Vector;
  75. import java.util.Hashtable;
  76. import java.awt.geom.AffineTransform;
  77. import java.awt.geom.Dimension2D;
  78. import java.awt.Point;
  79. import java.awt.RenderingHints;
  80. import java.awt.font.FontRenderContext;
  81. import java.awt.Dimension;
  82. /**
  83. * Renderer that renders areas to PDF
  84. */
  85. public class PDFRenderer implements Renderer {
  86. private static final boolean OPTIMIZE_TEXT = true;
  87. /** the PDF Document being created */
  88. protected PDFDocument pdfDoc;
  89. /** the /Resources object of the PDF document being created */
  90. protected PDFResources pdfResources;
  91. /** the IDReferences for this document */
  92. protected IDReferences idReferences;
  93. /** the current stream to add PDF commands to */
  94. PDFStream currentStream;
  95. /** the current annotation list to add annotations to */
  96. PDFAnnotList currentAnnotList;
  97. /** the current page to add annotations to */
  98. PDFPage currentPage;
  99. /** the current (internal) font name */
  100. protected String currentFontName;
  101. /** the current font size in millipoints */
  102. protected int currentFontSize;
  103. /** the current color/gradient for borders, letters, etc. */
  104. protected PDFPathPaint currentStroke = null;
  105. /** the current color/gradient to fill shapes with */
  106. protected PDFPathPaint currentFill = null;
  107. /** the current colour's red component */
  108. protected float currentRed = 0;
  109. /** the current colour's green component */
  110. protected float currentGreen = 0;
  111. /** the current colour's blue component */
  112. protected float currentBlue = 0;
  113. /** the current vertical position in millipoints from bottom */
  114. protected int currentYPosition = 0;
  115. /** the current horizontal position in millipoints from left */
  116. protected int currentXPosition = 0;
  117. /** the horizontal position of the current area container */
  118. private int currentAreaContainerXPosition = 0;
  119. /** the current colour for use in svg */
  120. private PDFColor currentColour = new PDFColor(0, 0, 0);
  121. private FontInfo fontInfo;
  122. // previous values used for text-decoration drawing
  123. int prevUnderlineXEndPos;
  124. int prevUnderlineYEndPos;
  125. int prevUnderlineSize;
  126. PDFColor prevUnderlineColor;
  127. int prevOverlineXEndPos;
  128. int prevOverlineYEndPos;
  129. int prevOverlineSize;
  130. PDFColor prevOverlineColor;
  131. int prevLineThroughXEndPos;
  132. int prevLineThroughYEndPos;
  133. int prevLineThroughSize;
  134. PDFColor prevLineThroughColor;
  135. /** true if a TJ command is left to be written */
  136. boolean textOpen = false;
  137. /** the previous Y coordinate of the last word written.
  138. Used to decide if we can draw the next word on the same line. */
  139. int prevWordY = 0;
  140. /** the previous X coordinate of the last word written.
  141. used to calculate how much space between two words */
  142. int prevWordX = 0;
  143. /** The width of the previous word. Used to calculate space between */
  144. int prevWordWidth = 0;
  145. private PDFOutline rootOutline;
  146. /**
  147. * create the PDF renderer
  148. */
  149. public PDFRenderer() {
  150. this.pdfDoc = new PDFDocument();
  151. }
  152. /**
  153. * set the PDF document's producer
  154. *
  155. * @param producer string indicating application producing PDF
  156. */
  157. public void setProducer(String producer) {
  158. this.pdfDoc.setProducer(producer);
  159. }
  160. /**
  161. * render the areas into PDF
  162. *
  163. * @param areaTree the laid-out area tree
  164. * @param stream the OutputStream to write the PDF to
  165. */
  166. public void render(AreaTree areaTree,
  167. OutputStream stream) throws IOException, FOPException {
  168. MessageHandler.logln("rendering areas to PDF");
  169. idReferences = areaTree.getIDReferences();
  170. this.pdfResources = this.pdfDoc.getResources();
  171. this.pdfDoc.setIDReferences(idReferences);
  172. Enumeration e = areaTree.getPages().elements();
  173. while (e.hasMoreElements()) {
  174. this.renderPage((Page) e.nextElement());
  175. }
  176. if (!idReferences.isEveryIdValid()) {
  177. // throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n");
  178. MessageHandler.errorln("WARNING: The following id's were referenced but not found: "+
  179. idReferences.getInvalidIds() + "\n");
  180. }
  181. renderRootExtensions(areaTree);
  182. FontSetup.addToResources(this.pdfDoc, fontInfo);
  183. MessageHandler.logln("writing out PDF");
  184. this.pdfDoc.output(stream);
  185. }
  186. /**
  187. * add a line to the current stream
  188. *
  189. * @param x1 the start x location in millipoints
  190. * @param y1 the start y location in millipoints
  191. * @param x2 the end x location in millipoints
  192. * @param y2 the end y location in millipoints
  193. * @param th the thickness in millipoints
  194. * @param r the red component
  195. * @param g the green component
  196. * @param b the blue component
  197. */
  198. protected void addLine(int x1, int y1, int x2, int y2, int th,
  199. PDFPathPaint stroke) {
  200. closeText();
  201. currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) +
  202. (x1 / 1000f) + " "+ (y1 / 1000f) + " m " +
  203. (x2 / 1000f) + " "+ (y2 / 1000f) + " l " +
  204. (th / 1000f) + " w S\n" + "Q\nBT\n");
  205. }
  206. /**
  207. * add a line to the current stream
  208. *
  209. * @param x1 the start x location in millipoints
  210. * @param y1 the start y location in millipoints
  211. * @param x2 the end x location in millipoints
  212. * @param y2 the end y location in millipoints
  213. * @param th the thickness in millipoints
  214. * @param rs the rule style as String containing dashArray + dashPhase
  215. * @param r the red component
  216. * @param g the green component
  217. * @param b the blue component
  218. */
  219. protected void addLine(int x1, int y1, int x2, int y2, int th,
  220. String rs, PDFPathPaint stroke) {
  221. closeText();
  222. currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) +
  223. rs + (x1 / 1000f) + " "+ (y1 / 1000f) + " m " +
  224. (x2 / 1000f) + " "+ (y2 / 1000f) + " l " +
  225. (th / 1000f) + " w S\n" + "Q\nBT\n");
  226. }
  227. /**
  228. * add a rectangle to the current stream
  229. *
  230. * @param x the x position of left edge in millipoints
  231. * @param y the y position of top edge in millipoints
  232. * @param w the width in millipoints
  233. * @param h the height in millipoints
  234. * @param stroke the stroke color/gradient
  235. */
  236. protected void addRect(int x, int y, int w, int h,
  237. PDFPathPaint stroke) {
  238. closeText();
  239. currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) +
  240. (x / 1000f) + " " + (y / 1000f) + " " + (w / 1000f) +
  241. " " + (h / 1000f) + " re s\n" + "Q\nBT\n");
  242. }
  243. /**
  244. * add a filled rectangle to the current stream
  245. *
  246. * @param x the x position of left edge in millipoints
  247. * @param y the y position of top edge in millipoints
  248. * @param w the width in millipoints
  249. * @param h the height in millipoints
  250. * @param fill the fill color/gradient
  251. * @param stroke the stroke color/gradient
  252. */
  253. protected void addRect(int x, int y, int w, int h,
  254. PDFPathPaint stroke, PDFPathPaint fill) {
  255. closeText();
  256. currentStream.add("ET\nq\n" + fill.getColorSpaceOut(true) +
  257. stroke.getColorSpaceOut(false) + (x / 1000f) + " " +
  258. (y / 1000f) + " " + (w / 1000f) + " " + (h / 1000f) +
  259. " re b\n" + "Q\nBT\n");
  260. }
  261. /**
  262. * render area container to PDF
  263. *
  264. * @param area the area container to render
  265. */
  266. public void renderAreaContainer(AreaContainer area) {
  267. int saveY = this.currentYPosition;
  268. int saveX = this.currentAreaContainerXPosition;
  269. if (area.getPosition() == Position.ABSOLUTE) {
  270. // Y position is computed assuming positive Y axis, adjust for negative postscript one
  271. this.currentYPosition =
  272. area.getYPosition() - 2 * area.getPaddingTop() -
  273. 2 * area.borderWidthTop;
  274. this.currentAreaContainerXPosition = area.getXPosition();
  275. } else if (area.getPosition() == Position.RELATIVE) {
  276. this.currentYPosition -= area.getYPosition();
  277. this.currentAreaContainerXPosition += area.getXPosition();
  278. } else if (area.getPosition() == Position.STATIC) {
  279. this.currentYPosition -=
  280. area.getPaddingTop() + area.borderWidthTop;
  281. this.currentAreaContainerXPosition +=
  282. area.getPaddingLeft() + area.borderWidthLeft;
  283. }
  284. this.currentXPosition = this.currentAreaContainerXPosition;
  285. doFrame(area);
  286. Enumeration e = area.getChildren().elements();
  287. while (e.hasMoreElements()) {
  288. Box b = (Box) e.nextElement();
  289. b.render(this);
  290. }
  291. if (area.getPosition() != Position.STATIC) {
  292. this.currentYPosition = saveY;
  293. this.currentAreaContainerXPosition = saveX;
  294. } else
  295. this.currentYPosition -= area.getHeight();
  296. }
  297. public void renderBodyAreaContainer(BodyAreaContainer area) {
  298. int saveY = this.currentYPosition;
  299. int saveX = this.currentAreaContainerXPosition;
  300. if (area.getPosition() == Position.ABSOLUTE) {
  301. // Y position is computed assuming positive Y axis, adjust for negative postscript one
  302. this.currentYPosition = area.getYPosition();
  303. this.currentAreaContainerXPosition = area.getXPosition();
  304. } else if (area.getPosition() == Position.RELATIVE) {
  305. this.currentYPosition -= area.getYPosition();
  306. this.currentAreaContainerXPosition += area.getXPosition();
  307. }
  308. this.currentXPosition = this.currentAreaContainerXPosition;
  309. int w, h;
  310. int rx = this.currentAreaContainerXPosition;
  311. w = area.getContentWidth();
  312. h = area.getContentHeight();
  313. int ry = this.currentYPosition;
  314. ColorType bg = area.getBackgroundColor();
  315. // I'm not sure I should have to check for bg being null
  316. // but I do
  317. if ((bg != null) && (bg.alpha() == 0)) {
  318. this.addRect(rx, ry, w, -h, new PDFColor(bg), new PDFColor(bg));
  319. }
  320. // floats & footnotes stuff
  321. renderAreaContainer(area.getBeforeFloatReferenceArea());
  322. renderAreaContainer(area.getFootnoteReferenceArea());
  323. // main reference area
  324. Enumeration e = area.getMainReferenceArea().getChildren().elements();
  325. while (e.hasMoreElements()) {
  326. Box b = (Box) e.nextElement();
  327. b.render(this); // span areas
  328. }
  329. if (area.getPosition() != Position.STATIC) {
  330. this.currentYPosition = saveY;
  331. this.currentAreaContainerXPosition = saveX;
  332. } else
  333. this.currentYPosition -= area.getHeight();
  334. }
  335. public void renderSpanArea(SpanArea area) {
  336. Enumeration e = area.getChildren().elements();
  337. while (e.hasMoreElements()) {
  338. Box b = (Box) e.nextElement();
  339. b.render(this); // column areas
  340. }
  341. }
  342. private void doFrame(Area area) {
  343. int w, h;
  344. int rx = this.currentAreaContainerXPosition;
  345. w = area.getContentWidth();
  346. if (area instanceof BlockArea)
  347. rx += ((BlockArea) area).getStartIndent();
  348. h = area.getContentHeight();
  349. int ry = this.currentYPosition;
  350. ColorType bg = area.getBackgroundColor();
  351. rx = rx - area.getPaddingLeft();
  352. ry = ry + area.getPaddingTop();
  353. w = w + area.getPaddingLeft() + area.getPaddingRight();
  354. h = h + area.getPaddingTop() + area.getPaddingBottom();
  355. // I'm not sure I should have to check for bg being null
  356. // but I do
  357. if ((bg != null) && (bg.alpha() == 0)) {
  358. this.addRect(rx, ry, w, -h, new PDFColor(bg), new PDFColor(bg));
  359. }
  360. rx = rx - area.borderWidthLeft;
  361. ry = ry + area.borderWidthTop;
  362. w = w + area.borderWidthLeft + area.borderWidthRight;
  363. h = h + area.borderWidthTop + area.borderWidthBottom;
  364. if (area.borderWidthTop != 0)
  365. addLine(rx, ry, rx + w, ry, area.borderWidthTop,
  366. new PDFColor(area.borderColorTop));
  367. if (area.borderWidthLeft != 0)
  368. addLine(rx, ry, rx, ry - h, area.borderWidthLeft,
  369. new PDFColor(area.borderColorLeft));
  370. if (area.borderWidthRight != 0)
  371. addLine(rx + w, ry, rx + w, ry - h, area.borderWidthRight,
  372. new PDFColor(area.borderColorRight));
  373. if (area.borderWidthBottom != 0)
  374. addLine(rx, ry - h, rx + w, ry - h, area.borderWidthBottom,
  375. new PDFColor(area.borderColorBottom));
  376. }
  377. /**
  378. * render block area to PDF
  379. *
  380. * @param area the block area to render
  381. */
  382. public void renderBlockArea(BlockArea area) {
  383. // KLease: Temporary test to fix block positioning
  384. // Offset ypos by padding and border widths
  385. // this.currentYPosition -= (area.getPaddingTop() + area.borderWidthTop);
  386. doFrame(area);
  387. Enumeration e = area.getChildren().elements();
  388. while (e.hasMoreElements()) {
  389. Box b = (Box) e.nextElement();
  390. b.render(this);
  391. }
  392. // this.currentYPosition -= (area.getPaddingBottom() + area.borderWidthBottom);
  393. }
  394. /**
  395. * render display space to PDF
  396. *
  397. * @param space the display space to render
  398. */
  399. public void renderDisplaySpace(DisplaySpace space) {
  400. int d = space.getSize();
  401. this.currentYPosition -= d;
  402. }
  403. /**
  404. * render image area to PDF
  405. *
  406. * @param area the image area to render
  407. */
  408. public void renderImageArea(ImageArea area) {
  409. // adapted from contribution by BoBoGi
  410. int x = this.currentAreaContainerXPosition + area.getXOffset();
  411. int y = this.currentYPosition;
  412. int w = area.getContentWidth();
  413. int h = area.getHeight();
  414. this.currentYPosition -= h;
  415. FopImage img = area.getImage();
  416. if (img instanceof SVGImage) {
  417. try {
  418. closeText();
  419. SVGSVGElement svg =
  420. ((SVGImage) img).getSVGDocument().getRootElement();
  421. currentStream.add("ET\nq\n" + (((float) w) / 1000f) +
  422. " 0 0 " + (((float) h) / 1000f) + " " +
  423. (((float) x) / 1000f) + " " +
  424. (((float)(y - h)) / 1000f) + " cm\n");
  425. // renderSVG(svg, (int) x, (int) y);
  426. currentStream.add("Q\nBT\n");
  427. } catch (FopImageException e) {
  428. }
  429. } else {
  430. int xObjectNum = this.pdfDoc.addImage(img);
  431. closeText();
  432. currentStream.add("ET\nq\n" + (((float) w) / 1000f) +
  433. " 0 0 " + (((float) h) / 1000f) + " " +
  434. (((float) x) / 1000f) + " " +
  435. (((float)(y - h)) / 1000f) + " cm\n" + "/Im" +
  436. xObjectNum + " Do\nQ\nBT\n");
  437. }
  438. }
  439. /** render a foreign object area */
  440. public void renderForeignObjectArea(ForeignObjectArea area) {
  441. // if necessary need to scale and align the content
  442. this.currentXPosition = this.currentXPosition + area.getXOffset();
  443. this.currentYPosition = this.currentYPosition;
  444. switch (area.getAlign()) {
  445. case TextAlign.START:
  446. break;
  447. case TextAlign.END:
  448. break;
  449. case TextAlign.CENTER:
  450. case TextAlign.JUSTIFY:
  451. break;
  452. }
  453. switch (area.getVerticalAlign()) {
  454. case VerticalAlign.BASELINE:
  455. break;
  456. case VerticalAlign.MIDDLE:
  457. break;
  458. case VerticalAlign.SUB:
  459. break;
  460. case VerticalAlign.SUPER:
  461. break;
  462. case VerticalAlign.TEXT_TOP:
  463. break;
  464. case VerticalAlign.TEXT_BOTTOM:
  465. break;
  466. case VerticalAlign.TOP:
  467. break;
  468. case VerticalAlign.BOTTOM:
  469. break;
  470. }
  471. closeText();
  472. // in general the content will not be text
  473. currentStream.add("ET\n");
  474. // align and scale
  475. currentStream.add("q\n");
  476. switch (area.scalingMethod()) {
  477. case Scaling.UNIFORM:
  478. break;
  479. case Scaling.NON_UNIFORM:
  480. break;
  481. }
  482. // if the overflow is auto (default), scroll or visible
  483. // then the contents should not be clipped, since this
  484. // is considered a printing medium.
  485. switch (area.getOverflow()) {
  486. case Overflow.VISIBLE:
  487. case Overflow.SCROLL:
  488. case Overflow.AUTO:
  489. break;
  490. case Overflow.HIDDEN:
  491. break;
  492. }
  493. area.getObject().render(this);
  494. currentStream.add("Q\n");
  495. currentStream.add("BT\n");
  496. this.currentXPosition += area.getEffectiveWidth();
  497. // this.currentYPosition -= area.getEffectiveHeight();
  498. }
  499. /**
  500. * render SVG area to PDF
  501. *
  502. * @param area the SVG area to render
  503. */
  504. public void renderSVGArea(SVGArea area) {
  505. // place at the current instream offset
  506. int x = this.currentXPosition;
  507. // Buggy: Method getXOffset() not found in class org.apache.fop.dom.svg.SVGArea
  508. //int x = this.currentAreaContainerXPosition + area.getXOffset();
  509. int y = this.currentYPosition;
  510. SVGSVGElement svg = area.getSVGDocument().getRootElement();
  511. int w = (int)(svg.getWidth().getBaseVal().getValue() * 1000);
  512. int h = (int)(svg.getHeight().getBaseVal().getValue() * 1000);
  513. float sx = 1, sy = -1;
  514. int xOffset = x, yOffset = y;
  515. /*
  516. * Clip to the svg area.
  517. * Note: To have the svg overlay (under) a text area then use
  518. * an fo:block-container
  519. */
  520. currentStream.add("q\n");
  521. if (w != 0 && h != 0) {
  522. currentStream.add(x / 1000f + " " + y / 1000f + " m\n");
  523. currentStream.add((x + w) / 1000f + " " + y / 1000f + " l\n");
  524. currentStream.add((x + w) / 1000f + " " + (y - h) / 1000f + " l\n");
  525. currentStream.add(x / 1000f + " " + (y - h) / 1000f + " l\n");
  526. currentStream.add("h\n");
  527. currentStream.add("W\n");
  528. currentStream.add("n\n");
  529. }
  530. // transform so that the coordinates (0,0) is from the top left
  531. // and positive is down and to the right. (0,0) is where the
  532. // viewBox puts it.
  533. currentStream.add(sx + " 0 0 " + sy + " " +
  534. xOffset / 1000f + " " + yOffset / 1000f + " cm\n");
  535. SVGDocument doc = area.getSVGDocument();
  536. UserAgent userAgent = new MUserAgent(new AffineTransform());
  537. GVTBuilder builder = new GVTBuilder();
  538. GraphicsNodeRenderContext rc = getRenderContext();
  539. BridgeContext ctx = new BridgeContext(userAgent, rc);
  540. GraphicsNode root;
  541. //System.out.println("creating PDFGraphics2D");
  542. PDFGraphics2D graphics = new PDFGraphics2D(true, area.getFontState(), pdfDoc,
  543. currentFontName, currentFontSize, currentXPosition,
  544. currentYPosition);
  545. graphics.setGraphicContext(new org.apache.batik.ext.awt.g2d.GraphicContext());
  546. graphics.setRenderingHints(rc.getRenderingHints());
  547. try {
  548. root = builder.build(ctx, doc);
  549. root.paint(graphics, rc);
  550. currentStream.add(graphics.getString());
  551. } catch(Exception e) {
  552. e.printStackTrace();
  553. }
  554. currentStream.add("Q\n");
  555. }
  556. public GraphicsNodeRenderContext getRenderContext() {
  557. GraphicsNodeRenderContext nodeRenderContext = null;
  558. if (nodeRenderContext == null) {
  559. RenderingHints hints = new RenderingHints(null);
  560. hints.put(RenderingHints.KEY_ANTIALIASING,
  561. RenderingHints.VALUE_ANTIALIAS_ON);
  562. hints.put(RenderingHints.KEY_INTERPOLATION,
  563. RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  564. FontRenderContext fontRenderContext =
  565. new FontRenderContext(new AffineTransform(), true, true);
  566. TextPainter textPainter = new StrokingTextPainter();
  567. GraphicsNodeRableFactory gnrFactory =
  568. new ConcreteGraphicsNodeRableFactory();
  569. nodeRenderContext =
  570. new GraphicsNodeRenderContext(new AffineTransform(),
  571. null,
  572. hints,
  573. fontRenderContext,
  574. textPainter,
  575. gnrFactory);
  576. nodeRenderContext.setTextPainter(textPainter);
  577. }
  578. return nodeRenderContext;
  579. }
  580. /**
  581. * render inline area to PDF
  582. *
  583. * @param area inline area to render
  584. */
  585. public void renderWordArea(WordArea area) {
  586. // char ch;
  587. StringBuffer pdf = new StringBuffer();
  588. Hashtable kerning = null;
  589. boolean kerningAvailable = false;
  590. kerning = area.getFontState().getKerning();
  591. if (kerning != null && !kerning.isEmpty()) {
  592. kerningAvailable = true;
  593. }
  594. String name = area.getFontState().getFontName();
  595. int size = area.getFontState().getFontSize();
  596. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  597. boolean useMultiByte = false;
  598. Font f = (Font)area.getFontState().getFontInfo().getFonts().get(name);
  599. if (f instanceof CIDFont)
  600. useMultiByte=true;
  601. //String startText = useMultiByte ? "<FEFF" : "(";
  602. String startText = useMultiByte ? "<" : "(";
  603. String endText = useMultiByte ? ">" : ")";
  604. PDFColor theAreaColor = new PDFColor((double) area.getRed(),
  605. (double) area.getGreen(),
  606. (double) area.getBlue());
  607. if ((!name.equals(this.currentFontName)) ||
  608. (size != this.currentFontSize)) {
  609. closeText();
  610. this.currentFontName = name;
  611. this.currentFontSize = size;
  612. pdf = pdf.append("/" + name + " " + (size / 1000) + " Tf\n");
  613. }
  614. if (!(theAreaColor.equals(this.currentFill))) {
  615. closeText();
  616. this.currentFill = theAreaColor;
  617. pdf.append(this.currentFill.getColorSpaceOut(true));
  618. }
  619. int rx = this.currentXPosition;
  620. int bl = this.currentYPosition;
  621. if (area.getUnderlined()) {
  622. int yPos = bl - size/10;
  623. addLine(rx, yPos, rx + area.getContentWidth(),
  624. yPos, size/14, theAreaColor);
  625. // save position for underlining a following InlineSpace
  626. prevUnderlineXEndPos = rx + area.getContentWidth();
  627. prevUnderlineYEndPos = yPos;
  628. prevUnderlineSize = size/14;
  629. prevUnderlineColor = theAreaColor;
  630. }
  631. if (area.getOverlined()) {
  632. int yPos = bl + area.getFontState().getAscender() + size/10;
  633. addLine(rx, yPos, rx + area.getContentWidth(),
  634. yPos, size/14, theAreaColor);
  635. prevOverlineXEndPos = rx + area.getContentWidth();
  636. prevOverlineYEndPos = yPos;
  637. prevOverlineSize = size/14;
  638. prevOverlineColor = theAreaColor;
  639. }
  640. if (area.getLineThrough()) {
  641. int yPos = bl + area.getFontState().getAscender() * 3/8;
  642. addLine(rx, yPos, rx + area.getContentWidth(),
  643. yPos, size/14, theAreaColor);
  644. prevLineThroughXEndPos = rx + area.getContentWidth();
  645. prevLineThroughYEndPos = yPos;
  646. prevLineThroughSize = size/14;
  647. prevLineThroughColor = theAreaColor;
  648. }
  649. if (OPTIMIZE_TEXT) {
  650. if (!textOpen || bl != prevWordY) {
  651. closeText();
  652. pdf.append("1 0 0 1 " +(rx / 1000f) + " " +
  653. (bl / 1000f) + " Tm [" + startText);
  654. prevWordY = bl;
  655. textOpen = true;
  656. }
  657. else {
  658. // express the space between words in thousandths of an em
  659. int space = prevWordX - rx + prevWordWidth;
  660. float emDiff = (float)space / (float)currentFontSize * 1000f;
  661. pdf.append(emDiff + " " + startText);
  662. }
  663. prevWordWidth = area.getContentWidth();
  664. prevWordX = rx;
  665. }
  666. else {
  667. // original text render code sets the text transformation matrix
  668. // for every word.
  669. pdf.append("1 0 0 1 " +(rx / 1000f) + " " + (bl / 1000f) + " Tm ");
  670. if (kerningAvailable) {
  671. pdf.append(" [" + startText);
  672. }
  673. else {
  674. pdf.append(" " + startText);
  675. }
  676. }
  677. String s;
  678. if (area.getPageNumberID() != null) { // this text is a page number, so resolve it
  679. s = idReferences.getPageNumber(area.getPageNumberID());
  680. if (s == null) {
  681. s = "";
  682. }
  683. } else {
  684. s = area.getText();
  685. }
  686. int l = s.length();
  687. for (int i = 0; i < l; i++) {
  688. char ch = s.charAt(i);
  689. String prepend = "";
  690. if (!useMultiByte) {
  691. if(ch > 127) {
  692. pdf.append("\\");
  693. pdf.append(Integer.toOctalString((int) ch));
  694. } else {
  695. switch (ch) {
  696. case '(':
  697. case ')':
  698. case '\\':
  699. prepend = "\\";
  700. break;
  701. }
  702. pdf.append(getUnicodeString(prepend+ch, useMultiByte));
  703. }
  704. } else {
  705. pdf.append(getUnicodeString(prepend+ch, useMultiByte));
  706. }
  707. if (kerningAvailable && (i+1) < l) {
  708. pdf.append(addKerning((new Integer((int)ch)),
  709. (new Integer((int)s.charAt(i+1))),
  710. kerning,
  711. startText, endText));
  712. }
  713. }
  714. pdf.append(endText + " ");
  715. if (!OPTIMIZE_TEXT) {
  716. if (kerningAvailable) {
  717. pdf.append("] TJ\n");
  718. }
  719. else {
  720. pdf.append("Tj\n");
  721. }
  722. }
  723. currentStream.add(pdf.toString());
  724. this.currentXPosition += area.getContentWidth();
  725. }
  726. /**
  727. * Convert a string to a unicode hex representation
  728. */
  729. private String getUnicodeString(StringBuffer str, boolean useMultiByte) {
  730. return getUnicodeString(str.toString(), useMultiByte);
  731. }
  732. /**
  733. * Convert a string to a multibyte hex representation
  734. */
  735. private String getUnicodeString(String str, boolean useMultiByte) {
  736. if (!useMultiByte) {
  737. return str;
  738. } else {
  739. StringBuffer buf = new StringBuffer(str.length()*4);
  740. byte[] uniBytes = null;
  741. try {
  742. uniBytes = str.getBytes("UnicodeBigUnmarked");
  743. } catch (Exception e) {
  744. // This should never fail
  745. }
  746. for (int i = 0; i < uniBytes.length; i++) {
  747. int b = (uniBytes[i] < 0) ? (int)(256+uniBytes[i])
  748. : (int)uniBytes[i];
  749. String hexString=Integer.toHexString(b);
  750. if (hexString.length()==1)
  751. buf=buf.append("0"+hexString);
  752. else
  753. buf=buf.append(hexString);
  754. }
  755. return buf.toString();
  756. }
  757. }
  758. /** Checks to see if we have some text rendering commands open
  759. * still and writes out the TJ command to the stream if we do
  760. */
  761. private void closeText()
  762. {
  763. if (OPTIMIZE_TEXT && textOpen) {
  764. currentStream.add("] TJ\n");
  765. textOpen = false;
  766. prevWordX = 0;
  767. prevWordY = 0;
  768. }
  769. }
  770. /**
  771. * render inline space to PDF
  772. *
  773. * @param space space to render
  774. */
  775. public void renderInlineSpace(InlineSpace space) {
  776. this.currentXPosition += space.getSize();
  777. if (space.getUnderlined()) {
  778. if (prevUnderlineColor != null) {
  779. addLine(prevUnderlineXEndPos, prevUnderlineYEndPos,
  780. prevUnderlineXEndPos + space.getSize(),
  781. prevUnderlineYEndPos, prevUnderlineSize, prevUnderlineColor);
  782. }
  783. }
  784. if (space.getOverlined()) {
  785. if (prevOverlineColor != null) {
  786. addLine(prevOverlineXEndPos, prevOverlineYEndPos,
  787. prevOverlineXEndPos + space.getSize(),
  788. prevOverlineYEndPos, prevOverlineSize, prevOverlineColor);
  789. }
  790. }
  791. if (space.getLineThrough()) {
  792. if (prevLineThroughColor != null) {
  793. addLine(prevLineThroughXEndPos, prevLineThroughYEndPos,
  794. prevLineThroughXEndPos + space.getSize(),
  795. prevLineThroughYEndPos, prevLineThroughSize, prevLineThroughColor);
  796. }
  797. }
  798. }
  799. /**
  800. * render line area to PDF
  801. *
  802. * @param area area to render
  803. */
  804. public void renderLineArea(LineArea area) {
  805. int rx = this.currentAreaContainerXPosition + area.getStartIndent();
  806. int ry = this.currentYPosition;
  807. int w = area.getContentWidth();
  808. int h = area.getHeight();
  809. this.currentYPosition -= area.getPlacementOffset();
  810. this.currentXPosition = rx;
  811. int bl = this.currentYPosition;
  812. Enumeration e = area.getChildren().elements();
  813. while (e.hasMoreElements()) {
  814. Box b = (Box) e.nextElement();
  815. if(b instanceof InlineArea) {
  816. InlineArea ia = (InlineArea)b;
  817. this.currentYPosition = ry - ia.getYOffset();
  818. } else {
  819. this.currentYPosition = ry - area.getPlacementOffset();
  820. }
  821. b.render(this);
  822. }
  823. this.currentYPosition = ry - h;
  824. this.currentXPosition = rx;
  825. }
  826. private StringBuffer addKerning(Integer ch1, Integer ch2,
  827. Hashtable kerning, String startText,
  828. String endText) {
  829. Hashtable h2=(Hashtable)kerning.get(ch1);
  830. int pwdt=0;
  831. StringBuffer buf=new StringBuffer("");
  832. if (h2!=null) {
  833. Integer wdt=(Integer)h2.get(ch2);
  834. if (wdt!=null) {
  835. pwdt=-wdt.intValue();
  836. buf=buf.append(endText + " " + pwdt + " " + startText);
  837. }
  838. }
  839. return buf;
  840. }
  841. /**
  842. * render page into PDF
  843. *
  844. * @param page page to render
  845. */
  846. public void renderPage(Page page) {
  847. BodyAreaContainer body;
  848. AreaContainer before, after;
  849. currentStream = this.pdfDoc.makeStream();
  850. body = page.getBody();
  851. before = page.getBefore();
  852. after = page.getAfter();
  853. this.currentFontName = "";
  854. this.currentFontSize = 0;
  855. currentStream.add("BT\n");
  856. renderBodyAreaContainer(body);
  857. if (before != null) {
  858. renderAreaContainer(before);
  859. }
  860. if (after != null) {
  861. renderAreaContainer(after);
  862. }
  863. closeText();
  864. currentStream.add("ET\n");
  865. currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream,
  866. page.getWidth() / 1000,
  867. page.getHeight() / 1000, page);
  868. if (page.hasLinks()) {
  869. currentAnnotList = this.pdfDoc.makeAnnotList();
  870. currentPage.setAnnotList(currentAnnotList);
  871. Enumeration e = page.getLinkSets().elements();
  872. while (e.hasMoreElements()) {
  873. LinkSet linkSet = (LinkSet) e.nextElement();
  874. linkSet.align();
  875. String dest = linkSet.getDest();
  876. int linkType = linkSet.getLinkType();
  877. Enumeration f = linkSet.getRects().elements();
  878. while (f.hasMoreElements()) {
  879. LinkedRectangle lrect =
  880. (LinkedRectangle) f.nextElement();
  881. currentAnnotList.addLink(
  882. this.pdfDoc.makeLink(lrect.getRectangle(),
  883. dest, linkType));
  884. }
  885. }
  886. } else {
  887. // just to be on the safe side
  888. currentAnnotList = null;
  889. }
  890. }
  891. /**
  892. * render leader area into PDF
  893. *
  894. * @param area area to render
  895. */
  896. public void renderLeaderArea(LeaderArea area) {
  897. int rx = this.currentXPosition;
  898. ;
  899. int ry = this.currentYPosition;
  900. int w = area.getContentWidth();
  901. int h = area.getHeight();
  902. int th = area.getRuleThickness();
  903. int st = area.getRuleStyle();
  904. String rs = setRuleStylePattern(st);
  905. //checks whether thickness is = 0, because of bug in pdf (or where?),
  906. //a line with thickness 0 is still displayed
  907. if (th != 0) {
  908. switch (st) {
  909. case org.apache.fop.fo.properties.RuleStyle.DOUBLE:
  910. addLine(rx, ry, rx + w, ry, th / 3, rs,
  911. new PDFColor(area.getRed(),
  912. area.getGreen(), area.getBlue()));
  913. addLine(rx, ry + (2 * th / 3), rx + w,
  914. ry + (2 * th / 3), th / 3, rs,
  915. new PDFColor(area.getRed(),
  916. area.getGreen(), area.getBlue()));
  917. break;
  918. case org.apache.fop.fo.properties.RuleStyle.GROOVE:
  919. addLine(rx, ry, rx + w, ry, th / 2, rs,
  920. new PDFColor(area.getRed(),
  921. area.getGreen(), area.getBlue()));
  922. addLine(rx, ry + (th / 2), rx + w, ry + (th / 2),
  923. th / 2, rs, new PDFColor(255, 255, 255));
  924. break;
  925. case org.apache.fop.fo.properties.RuleStyle.RIDGE:
  926. addLine(rx, ry, rx + w, ry, th / 2, rs,
  927. new PDFColor(255, 255, 255));
  928. addLine(rx, ry + (th / 2), rx + w, ry + (th / 2),
  929. th / 2, rs,
  930. new PDFColor(area.getRed(),
  931. area.getGreen(), area.getBlue()));
  932. break;
  933. default:
  934. addLine(rx, ry, rx + w, ry, th, rs,
  935. new PDFColor(area.getRed(),
  936. area.getGreen(), area.getBlue()));
  937. }
  938. this.currentXPosition += area.getContentWidth();
  939. this.currentYPosition += th;
  940. }
  941. }
  942. /**
  943. * set up the font info
  944. *
  945. * @param fontInfo font info to set up
  946. */
  947. public void setupFontInfo(FontInfo fontInfo) {
  948. this.fontInfo = fontInfo;
  949. FontSetup.setup(fontInfo);
  950. }
  951. /**
  952. * defines a string containing dashArray and dashPhase for the rule style
  953. */
  954. private String setRuleStylePattern (int style) {
  955. String rs = "";
  956. switch (style) {
  957. case org.apache.fop.fo.properties.RuleStyle.SOLID:
  958. rs = "[] 0 d ";
  959. break;
  960. case org.apache.fop.fo.properties.RuleStyle.DASHED:
  961. rs = "[3 3] 0 d ";
  962. break;
  963. case org.apache.fop.fo.properties.RuleStyle.DOTTED:
  964. rs = "[1 3] 0 d ";
  965. break;
  966. case org.apache.fop.fo.properties.RuleStyle.DOUBLE:
  967. rs = "[] 0 d ";
  968. break;
  969. default:
  970. rs = "[] 0 d ";
  971. }
  972. return rs;
  973. }
  974. protected void renderRootExtensions(AreaTree areaTree)
  975. {
  976. Vector v = areaTree.getExtensions();
  977. if (v != null) {
  978. Enumeration e = v.elements();
  979. while (e.hasMoreElements()) {
  980. ExtensionObj ext = (ExtensionObj)e.nextElement();
  981. if (ext instanceof Outline) {
  982. renderOutline((Outline)ext);
  983. }
  984. }
  985. }
  986. }
  987. private void renderOutline(Outline outline)
  988. {
  989. if (rootOutline == null) {
  990. rootOutline = this.pdfDoc.makeOutlineRoot();
  991. }
  992. PDFOutline pdfOutline = null;
  993. Outline parent = outline.getParentOutline();
  994. if (parent == null) {
  995. pdfOutline = this.pdfDoc.makeOutline(rootOutline,
  996. outline.getLabel().toString(),
  997. outline.getInternalDestination());
  998. }
  999. else {
  1000. PDFOutline pdfParentOutline = (PDFOutline)parent.getRendererObject();
  1001. if (pdfParentOutline == null) {
  1002. MessageHandler.errorln("Error: pdfParentOutline is null");
  1003. }
  1004. else {
  1005. pdfOutline = this.pdfDoc.makeOutline(pdfParentOutline,
  1006. outline.getLabel().toString(),
  1007. outline.getInternalDestination());
  1008. }
  1009. }
  1010. outline.setRendererObject(pdfOutline);
  1011. // handle sub outlines
  1012. Vector v = outline.getOutlines();
  1013. Enumeration e = v.elements();
  1014. while (e.hasMoreElements()) {
  1015. renderOutline((Outline)e.nextElement());
  1016. }
  1017. }
  1018. protected class MUserAgent implements UserAgent {
  1019. AffineTransform currentTransform = null;
  1020. /**
  1021. * Creates a new SVGUserAgent.
  1022. */
  1023. protected MUserAgent(AffineTransform at) {
  1024. currentTransform = at;
  1025. }
  1026. /**
  1027. * Displays an error message.
  1028. */
  1029. public void displayError(String message) {
  1030. System.err.println(message);
  1031. }
  1032. /**
  1033. * Displays an error resulting from the specified Exception.
  1034. */
  1035. public void displayError(Exception ex) {
  1036. ex.printStackTrace(System.err);
  1037. }
  1038. /**
  1039. * Displays a message in the User Agent interface.
  1040. * The given message is typically displayed in a status bar.
  1041. */
  1042. public void displayMessage(String message) {
  1043. System.out.println(message);
  1044. }
  1045. /**
  1046. * Returns a customized the pixel to mm factor.
  1047. */
  1048. public float getPixelToMM() {
  1049. return 0.264583333333333333333f; // 72 dpi
  1050. }
  1051. /**
  1052. * Returns the language settings.
  1053. */
  1054. public String getLanguages() {
  1055. return "en";//userLanguages;
  1056. }
  1057. /**
  1058. * Returns the user stylesheet uri.
  1059. * @return null if no user style sheet was specified.
  1060. */
  1061. public String getUserStyleSheetURI() {
  1062. return null;//userStyleSheetURI;
  1063. }
  1064. /**
  1065. * Returns the class name of the XML parser.
  1066. */
  1067. public String getXMLParserClassName() {
  1068. String parserClassName =
  1069. System.getProperty("org.xml.sax.parser");
  1070. if (parserClassName == null) {
  1071. parserClassName = "org.apache.xerces.parsers.SAXParser";
  1072. }
  1073. return parserClassName;//application.getXMLParserClassName();
  1074. }
  1075. /**
  1076. * Opens a link in a new component.
  1077. * @param doc The current document.
  1078. * @param uri The document URI.
  1079. */
  1080. public void openLink(SVGAElement elt)
  1081. {
  1082. //application.openLink(uri);
  1083. }
  1084. public Point getClientAreaLocationOnScreen()
  1085. {
  1086. return new Point(0, 0);
  1087. }
  1088. public void setSVGCursor(java.awt.Cursor cursor)
  1089. {
  1090. }
  1091. public AffineTransform getTransform()
  1092. {
  1093. return currentTransform;
  1094. }
  1095. public Dimension2D getViewportSize()
  1096. {
  1097. return new Dimension(100, 100);
  1098. }
  1099. public EventDispatcher getEventDispatcher()
  1100. {
  1101. return null;
  1102. }
  1103. public boolean supportExtension(String str)
  1104. {
  1105. return false;
  1106. }
  1107. public boolean hasFeature(String str)
  1108. {
  1109. return false;
  1110. }
  1111. public void registerExtension(BridgeExtension be)
  1112. {
  1113. }
  1114. }
  1115. }