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.

PDFRenderer.java 55KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  1. /*
  2. * Copyright 1999-2005 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /* $Id$ */
  17. package org.apache.fop.render.pdf;
  18. // Java
  19. import java.io.IOException;
  20. import java.io.OutputStream;
  21. import java.awt.Color;
  22. import java.awt.geom.Rectangle2D;
  23. import java.awt.geom.AffineTransform;
  24. import java.util.Iterator;
  25. import java.util.Map;
  26. import java.util.List;
  27. // XML
  28. import org.w3c.dom.Document;
  29. // Avalon
  30. import org.apache.avalon.framework.configuration.Configuration;
  31. import org.apache.avalon.framework.configuration.ConfigurationException;
  32. // FOP
  33. import org.apache.fop.apps.FOPException;
  34. import org.apache.fop.apps.FOUserAgent;
  35. import org.apache.fop.area.CTM;
  36. import org.apache.fop.area.LineArea;
  37. import org.apache.fop.area.Page;
  38. import org.apache.fop.area.PageViewport;
  39. import org.apache.fop.area.RegionViewport;
  40. import org.apache.fop.area.Trait;
  41. import org.apache.fop.area.OffDocumentItem;
  42. import org.apache.fop.area.BookmarkData;
  43. import org.apache.fop.area.inline.Character;
  44. import org.apache.fop.area.inline.TextArea;
  45. import org.apache.fop.area.inline.ForeignObject;
  46. import org.apache.fop.area.inline.Image;
  47. import org.apache.fop.area.inline.Leader;
  48. import org.apache.fop.area.inline.InlineParent;
  49. import org.apache.fop.area.inline.WordArea;
  50. import org.apache.fop.area.inline.SpaceArea;
  51. import org.apache.fop.datatypes.ColorType;
  52. import org.apache.fop.fonts.Typeface;
  53. import org.apache.fop.fonts.Font;
  54. import org.apache.fop.fonts.FontSetup;
  55. import org.apache.fop.fonts.FontMetrics;
  56. import org.apache.fop.image.FopImage;
  57. import org.apache.fop.image.ImageFactory;
  58. import org.apache.fop.image.XMLImage;
  59. import org.apache.fop.pdf.PDFAnnotList;
  60. import org.apache.fop.pdf.PDFColor;
  61. import org.apache.fop.pdf.PDFDocument;
  62. import org.apache.fop.pdf.PDFEncryptionManager;
  63. import org.apache.fop.pdf.PDFFilterList;
  64. import org.apache.fop.pdf.PDFInfo;
  65. import org.apache.fop.pdf.PDFLink;
  66. import org.apache.fop.pdf.PDFOutline;
  67. import org.apache.fop.pdf.PDFPage;
  68. import org.apache.fop.pdf.PDFResourceContext;
  69. import org.apache.fop.pdf.PDFResources;
  70. import org.apache.fop.pdf.PDFState;
  71. import org.apache.fop.pdf.PDFStream;
  72. import org.apache.fop.pdf.PDFText;
  73. import org.apache.fop.pdf.PDFXObject;
  74. import org.apache.fop.render.AbstractPathOrientedRenderer;
  75. import org.apache.fop.render.RendererContext;
  76. import org.apache.fop.fo.Constants;
  77. /*
  78. todo:
  79. word rendering and optimistion
  80. pdf state optimisation
  81. line and border
  82. background pattern
  83. writing mode
  84. text decoration
  85. */
  86. /**
  87. * Renderer that renders areas to PDF
  88. *
  89. */
  90. public class PDFRenderer extends AbstractPathOrientedRenderer {
  91. /**
  92. * The mime type for pdf
  93. */
  94. public static final String MIME_TYPE = "application/pdf";
  95. /** Controls whether comments are written to the PDF stream. */
  96. protected static final boolean WRITE_COMMENTS = true;
  97. /**
  98. * the PDF Document being created
  99. */
  100. protected PDFDocument pdfDoc;
  101. /**
  102. * Map of pages using the PageViewport as the key
  103. * this is used for prepared pages that cannot be immediately
  104. * rendered
  105. */
  106. protected Map pages = null;
  107. /**
  108. * Page references are stored using the PageViewport as the key
  109. * when a reference is made the PageViewport is used
  110. * for pdf this means we need the pdf page reference
  111. */
  112. protected Map pageReferences = new java.util.HashMap();
  113. /** Page viewport references */
  114. protected Map pvReferences = new java.util.HashMap();
  115. /**
  116. * The output stream to write the document to
  117. */
  118. protected OutputStream ostream;
  119. /**
  120. * the /Resources object of the PDF document being created
  121. */
  122. protected PDFResources pdfResources;
  123. /**
  124. * the current stream to add PDF commands to
  125. */
  126. protected PDFStream currentStream;
  127. /**
  128. * the current annotation list to add annotations to
  129. */
  130. protected PDFResourceContext currentContext = null;
  131. /**
  132. * the current page to add annotations to
  133. */
  134. protected PDFPage currentPage;
  135. /** The current Transform */
  136. protected AffineTransform currentBasicTransform;
  137. /** drawing state */
  138. protected PDFState currentState = null;
  139. /** Name of currently selected font */
  140. protected String currentFontName = "";
  141. /** Size of currently selected font */
  142. protected int currentFontSize = 0;
  143. /** page height */
  144. protected int pageHeight;
  145. /** Registry of PDF filters */
  146. protected Map filterMap;
  147. /**
  148. * true if a TJ command is left to be written
  149. */
  150. protected boolean textOpen = false;
  151. /**
  152. * true if a BT command has been written.
  153. */
  154. protected boolean inTextMode = false;
  155. /**
  156. * the previous Y coordinate of the last word written.
  157. * Used to decide if we can draw the next word on the same line.
  158. */
  159. protected int prevWordY = 0;
  160. /**
  161. * the previous X coordinate of the last word written.
  162. * used to calculate how much space between two words
  163. */
  164. protected int prevWordX = 0;
  165. /**
  166. * The width of the previous word. Used to calculate space between
  167. */
  168. protected int prevWordWidth = 0;
  169. /**
  170. * reusable word area string buffer to reduce memory usage
  171. */
  172. //private StringBuffer wordAreaPDF = new StringBuffer();
  173. /**
  174. * create the PDF renderer
  175. */
  176. public PDFRenderer() {
  177. }
  178. /**
  179. * Configure the PDF renderer.
  180. * Get the configuration to be used for pdf stream filters,
  181. * fonts etc.
  182. * @see org.apache.avalon.framework.configuration.Configurable#configure(Configuration)
  183. */
  184. public void configure(Configuration cfg) throws ConfigurationException {
  185. //PDF filters
  186. this.filterMap = PDFFilterList.buildFilterMapFromConfiguration(cfg);
  187. //Font configuration
  188. List cfgFonts = FontSetup.buildFontListFromConfiguration(cfg);
  189. if (this.fontList == null) {
  190. this.fontList = cfgFonts;
  191. } else {
  192. this.fontList.addAll(cfgFonts);
  193. }
  194. }
  195. /**
  196. * @see org.apache.fop.render.Renderer#setUserAgent(FOUserAgent)
  197. */
  198. public void setUserAgent(FOUserAgent agent) {
  199. super.setUserAgent(agent);
  200. PDFSVGHandler xmlHandler = new PDFSVGHandler();
  201. userAgent.getXMLHandlerRegistry().addXMLHandler(xmlHandler);
  202. }
  203. /**
  204. * @see org.apache.fop.render.Renderer#startRenderer(OutputStream)
  205. */
  206. public void startRenderer(OutputStream stream) throws IOException {
  207. if (userAgent == null) {
  208. throw new IllegalStateException("UserAgent must be set before starting the renderer");
  209. }
  210. ostream = stream;
  211. this.pdfDoc = new PDFDocument(
  212. userAgent.getProducer() != null ? userAgent.getProducer() : "");
  213. this.pdfDoc.setCreator(userAgent.getCreator());
  214. this.pdfDoc.setCreationDate(userAgent.getCreationDate());
  215. this.pdfDoc.getInfo().setAuthor(userAgent.getAuthor());
  216. this.pdfDoc.getInfo().setTitle(userAgent.getTitle());
  217. this.pdfDoc.getInfo().setKeywords(userAgent.getKeywords());
  218. this.pdfDoc.setFilterMap(filterMap);
  219. this.pdfDoc.outputHeader(stream);
  220. //Setup encryption if necessary
  221. PDFEncryptionManager.setupPDFEncryption(
  222. userAgent.getPDFEncryptionParams(), this.pdfDoc);
  223. }
  224. /**
  225. * @see org.apache.fop.render.Renderer#stopRenderer()
  226. */
  227. public void stopRenderer() throws IOException {
  228. pdfDoc.getResources().addFonts(pdfDoc, fontInfo);
  229. pdfDoc.outputTrailer(ostream);
  230. this.pdfDoc = null;
  231. ostream = null;
  232. pages = null;
  233. pageReferences.clear();
  234. pvReferences.clear();
  235. pdfResources = null;
  236. currentStream = null;
  237. currentContext = null;
  238. currentPage = null;
  239. currentState = null;
  240. currentFontName = "";
  241. }
  242. /**
  243. * @see org.apache.fop.render.Renderer#supportsOutOfOrder()
  244. */
  245. public boolean supportsOutOfOrder() {
  246. //return false;
  247. return true;
  248. }
  249. /**
  250. * @see org.apache.fop.render.Renderer#processOffDocumentItem(OffDocumentItem)
  251. */
  252. public void processOffDocumentItem(OffDocumentItem odi) {
  253. // render Bookmark-Tree
  254. if (odi instanceof BookmarkData) {
  255. renderBookmarkTree((BookmarkData) odi);
  256. }
  257. }
  258. /**
  259. * Renders a Bookmark-Tree object
  260. * @param bookmarks the BookmarkData object containing all the Bookmark-Items
  261. */
  262. protected void renderBookmarkTree(BookmarkData bookmarks) {
  263. for (int i = 0; i < bookmarks.getCount(); i++) {
  264. BookmarkData ext = bookmarks.getSubData(i);
  265. renderBookmarkItem(ext, null);
  266. }
  267. }
  268. private void renderBookmarkItem(BookmarkData bookmarkItem,
  269. PDFOutline parentBookmarkItem) {
  270. PDFOutline pdfOutline = null;
  271. PageViewport pv = bookmarkItem.getPageViewport();
  272. if (pv != null) {
  273. Rectangle2D bounds = pv.getViewArea();
  274. double h = bounds.getHeight();
  275. float yoffset = (float)h / 1000f;
  276. String intDest = (String)pageReferences.get(pv.getKey());
  277. if (parentBookmarkItem == null) {
  278. PDFOutline outlineRoot = pdfDoc.getOutlineRoot();
  279. pdfOutline = pdfDoc.getFactory().makeOutline(outlineRoot,
  280. bookmarkItem.getBookmarkTitle(),
  281. intDest, yoffset,
  282. bookmarkItem.showChildItems());
  283. } else {
  284. pdfOutline = pdfDoc.getFactory().makeOutline(parentBookmarkItem,
  285. bookmarkItem.getBookmarkTitle(),
  286. intDest, yoffset,
  287. bookmarkItem.showChildItems());
  288. }
  289. }
  290. for (int i = 0; i < bookmarkItem.getCount(); i++) {
  291. renderBookmarkItem(bookmarkItem.getSubData(i), pdfOutline);
  292. }
  293. }
  294. /**
  295. * writes out a comment.
  296. * @param text text for the comment
  297. */
  298. protected void comment(String text) {
  299. if (WRITE_COMMENTS) {
  300. currentStream.add("% " + text + "\n");
  301. }
  302. }
  303. /** Saves the graphics state of the rendering engine. */
  304. protected void saveGraphicsState() {
  305. endTextObject();
  306. currentStream.add("q\n");
  307. }
  308. /** Restores the last graphics state of the rendering engine. */
  309. protected void restoreGraphicsState() {
  310. endTextObject();
  311. currentStream.add("Q\n");
  312. }
  313. /** Indicates the beginning of a text object. */
  314. protected void beginTextObject() {
  315. if (!inTextMode) {
  316. currentStream.add("BT\n");
  317. inTextMode = true;
  318. }
  319. }
  320. /** Indicates the end of a text object. */
  321. protected void endTextObject() {
  322. closeText();
  323. if (inTextMode) {
  324. currentStream.add("ET\n");
  325. inTextMode = false;
  326. }
  327. }
  328. /**
  329. * Start the next page sequence.
  330. * For the pdf renderer there is no concept of page sequences
  331. * but it uses the first available page sequence title to set
  332. * as the title of the pdf document.
  333. *
  334. * @param seqTitle the title of the page sequence
  335. */
  336. public void startPageSequence(LineArea seqTitle) {
  337. if (seqTitle != null) {
  338. String str = convertTitleToString(seqTitle);
  339. PDFInfo info = this.pdfDoc.getInfo();
  340. if (info.getTitle() == null) {
  341. info.setTitle(str);
  342. }
  343. }
  344. }
  345. /**
  346. * The pdf page is prepared by making the page.
  347. * The page is made in the pdf document without any contents
  348. * and then stored to add the contents later.
  349. * The page objects is stored using the area tree PageViewport
  350. * as a key.
  351. *
  352. * @param page the page to prepare
  353. */
  354. public void preparePage(PageViewport page) {
  355. setupPage(page);
  356. if (pages == null) {
  357. pages = new java.util.HashMap();
  358. }
  359. pages.put(page, currentPage);
  360. }
  361. private void setupPage(PageViewport page) {
  362. this.pdfResources = this.pdfDoc.getResources();
  363. Rectangle2D bounds = page.getViewArea();
  364. double w = bounds.getWidth();
  365. double h = bounds.getHeight();
  366. currentPage = this.pdfDoc.getFactory().makePage(
  367. this.pdfResources,
  368. (int) Math.round(w / 1000), (int) Math.round(h / 1000),
  369. page.getPageIndex());
  370. pageReferences.put(page.getKey(), currentPage.referencePDF());
  371. pvReferences.put(page.getKey(), page);
  372. }
  373. /**
  374. * This method creates a pdf stream for the current page
  375. * uses it as the contents of a new page. The page is written
  376. * immediately to the output stream.
  377. * @see org.apache.fop.render.Renderer#renderPage(PageViewport)
  378. */
  379. public void renderPage(PageViewport page)
  380. throws IOException, FOPException {
  381. if (pages != null
  382. && (currentPage = (PDFPage) pages.get(page)) != null) {
  383. //Retrieve previously prepared page (out-of-line rendering)
  384. pages.remove(page);
  385. } else {
  386. setupPage(page);
  387. }
  388. Rectangle2D bounds = page.getViewArea();
  389. double h = bounds.getHeight();
  390. pageHeight = (int) h;
  391. currentStream = this.pdfDoc.getFactory()
  392. .makeStream(PDFFilterList.CONTENT_FILTER, false);
  393. currentState = new PDFState();
  394. /* This transform shouldn't affect PDFState as it only sets the basic
  395. * coordinate system for the rendering process.
  396. *
  397. currentState.setTransform(new AffineTransform(1, 0, 0, -1, 0,
  398. (int) Math.round(pageHeight / 1000)));
  399. */
  400. // Transform origin at top left to origin at bottom left
  401. currentBasicTransform = new AffineTransform(1, 0, 0, -1, 0,
  402. pageHeight / 1000f);
  403. currentStream.add(CTMHelper.toPDFString(currentBasicTransform, false) + " cm\n");
  404. currentFontName = "";
  405. Page p = page.getPage();
  406. renderPageAreas(p);
  407. this.pdfDoc.registerObject(currentStream);
  408. currentPage.setContents(currentStream);
  409. PDFAnnotList annots = currentPage.getAnnotations();
  410. if (annots != null) {
  411. this.pdfDoc.addObject(annots);
  412. }
  413. this.pdfDoc.addObject(currentPage);
  414. this.pdfDoc.output(ostream);
  415. }
  416. /**
  417. * @see org.apache.fop.render.AbstractRenderer#startVParea(CTM)
  418. */
  419. protected void startVParea(CTM ctm) {
  420. // Set the given CTM in the graphics state
  421. currentState.push();
  422. currentState.setTransform(
  423. new AffineTransform(CTMHelper.toPDFArray(ctm)));
  424. saveGraphicsState();
  425. // multiply with current CTM
  426. currentStream.add(CTMHelper.toPDFString(ctm) + " cm\n");
  427. // Set clip?
  428. }
  429. /**
  430. * @see org.apache.fop.render.AbstractRenderer#endVParea()
  431. */
  432. protected void endVParea() {
  433. restoreGraphicsState();
  434. currentState.pop();
  435. }
  436. /**
  437. * Handle the traits for a region
  438. * This is used to draw the traits for the given page region.
  439. * (See Sect. 6.4.1.2 of XSL-FO spec.)
  440. * @param region the RegionViewport whose region is to be drawn
  441. */
  442. protected void handleRegionTraits(RegionViewport region) {
  443. currentFontName = "";
  444. super.handleRegionTraits(region);
  445. }
  446. /** @see org.apache.fop.render.AbstractPathOrientedRenderer */
  447. protected void drawBorderLine(float x1, float y1, float x2, float y2,
  448. boolean horz, boolean startOrBefore, int style, ColorType col) {
  449. float w = x2 - x1;
  450. float h = y2 - y1;
  451. if ((w < 0) || (h < 0)) {
  452. log.error("Negative extent received. Border won't be painted.");
  453. return;
  454. }
  455. switch (style) {
  456. case Constants.EN_DASHED:
  457. setColor(toColor(col), false, null);
  458. if (horz) {
  459. float unit = Math.abs(2 * h);
  460. int rep = (int)(w / unit);
  461. if (rep % 2 == 0) {
  462. rep++;
  463. }
  464. unit = w / rep;
  465. currentStream.add("[" + unit + "] 0 d ");
  466. currentStream.add(h + " w\n");
  467. float ym = y1 + (h / 2);
  468. currentStream.add(x1 + " " + ym + " m " + x2 + " " + ym + " l S\n");
  469. } else {
  470. float unit = Math.abs(2 * w);
  471. int rep = (int)(h / unit);
  472. if (rep % 2 == 0) {
  473. rep++;
  474. }
  475. unit = h / rep;
  476. currentStream.add("[" + unit + "] 0 d ");
  477. currentStream.add(w + " w\n");
  478. float xm = x1 + (w / 2);
  479. currentStream.add(xm + " " + y1 + " m " + xm + " " + y2 + " l S\n");
  480. }
  481. break;
  482. case Constants.EN_DOTTED:
  483. setColor(toColor(col), false, null);
  484. currentStream.add("1 J ");
  485. if (horz) {
  486. float unit = Math.abs(2 * h);
  487. int rep = (int)(w / unit);
  488. if (rep % 2 == 0) {
  489. rep++;
  490. }
  491. unit = w / rep;
  492. currentStream.add("[0 " + unit + "] 0 d ");
  493. currentStream.add(h + " w\n");
  494. float ym = y1 + (h / 2);
  495. currentStream.add(x1 + " " + ym + " m " + x2 + " " + ym + " l S\n");
  496. } else {
  497. float unit = Math.abs(2 * w);
  498. int rep = (int)(h / unit);
  499. if (rep % 2 == 0) {
  500. rep++;
  501. }
  502. unit = h / rep;
  503. currentStream.add("[0 " + unit + " ] 0 d ");
  504. currentStream.add(w + " w\n");
  505. float xm = x1 + (w / 2);
  506. currentStream.add(xm + " " + y1 + " m " + xm + " " + y2 + " l S\n");
  507. }
  508. break;
  509. case Constants.EN_DOUBLE:
  510. setColor(toColor(col), false, null);
  511. currentStream.add("[] 0 d ");
  512. if (horz) {
  513. float h3 = h / 3;
  514. currentStream.add(h3 + " w\n");
  515. float ym1 = y1 + (h3 / 2);
  516. float ym2 = ym1 + h3 + h3;
  517. currentStream.add(x1 + " " + ym1 + " m " + x2 + " " + ym1 + " l S\n");
  518. currentStream.add(x1 + " " + ym2 + " m " + x2 + " " + ym2 + " l S\n");
  519. } else {
  520. float w3 = w / 3;
  521. currentStream.add(w3 + " w\n");
  522. float xm1 = x1 + (w3 / 2);
  523. float xm2 = xm1 + w3 + w3;
  524. currentStream.add(xm1 + " " + y1 + " m " + xm1 + " " + y2 + " l S\n");
  525. currentStream.add(xm2 + " " + y1 + " m " + xm2 + " " + y2 + " l S\n");
  526. }
  527. break;
  528. case Constants.EN_GROOVE:
  529. case Constants.EN_RIDGE:
  530. {
  531. float colFactor = (style == EN_GROOVE ? 0.4f : -0.4f);
  532. currentStream.add("[] 0 d ");
  533. Color c = toColor(col);
  534. if (horz) {
  535. Color uppercol = lightenColor(c, -colFactor);
  536. Color lowercol = lightenColor(c, colFactor);
  537. float h3 = h / 3;
  538. currentStream.add(h3 + " w\n");
  539. float ym1 = y1 + (h3 / 2);
  540. setColor(uppercol, false, null);
  541. currentStream.add(x1 + " " + ym1 + " m " + x2 + " " + ym1 + " l S\n");
  542. setColor(c, false, null);
  543. currentStream.add(x1 + " " + (ym1 + h3) + " m "
  544. + x2 + " " + (ym1 + h3) + " l S\n");
  545. setColor(lowercol, false, null);
  546. currentStream.add(x1 + " " + (ym1 + h3 + h3) + " m "
  547. + x2 + " " + (ym1 + h3 + h3) + " l S\n");
  548. } else {
  549. Color leftcol = lightenColor(c, -colFactor);
  550. Color rightcol = lightenColor(c, colFactor);
  551. float w3 = w / 3;
  552. currentStream.add(w3 + " w\n");
  553. float xm1 = x1 + (w3 / 2);
  554. setColor(leftcol, false, null);
  555. currentStream.add(xm1 + " " + y1 + " m " + xm1 + " " + y2 + " l S\n");
  556. setColor(c, false, null);
  557. currentStream.add((xm1 + w3) + " " + y1 + " m "
  558. + (xm1 + w3) + " " + y2 + " l S\n");
  559. setColor(rightcol, false, null);
  560. currentStream.add((xm1 + w3 + w3) + " " + y1 + " m "
  561. + (xm1 + w3 + w3) + " " + y2 + " l S\n");
  562. }
  563. break;
  564. }
  565. case Constants.EN_INSET:
  566. case Constants.EN_OUTSET:
  567. {
  568. float colFactor = (style == EN_OUTSET ? 0.4f : -0.4f);
  569. currentStream.add("[] 0 d ");
  570. Color c = toColor(col);
  571. if (horz) {
  572. c = lightenColor(c, (startOrBefore ? 1 : -1) * colFactor);
  573. currentStream.add(h + " w\n");
  574. float ym1 = y1 + (h / 2);
  575. setColor(c, false, null);
  576. currentStream.add(x1 + " " + ym1 + " m " + x2 + " " + ym1 + " l S\n");
  577. } else {
  578. c = lightenColor(c, (startOrBefore ? 1 : -1) * colFactor);
  579. currentStream.add(w + " w\n");
  580. float xm1 = x1 + (w / 2);
  581. setColor(c, false, null);
  582. currentStream.add(xm1 + " " + y1 + " m " + xm1 + " " + y2 + " l S\n");
  583. }
  584. break;
  585. }
  586. case Constants.EN_HIDDEN:
  587. break;
  588. default:
  589. setColor(toColor(col), false, null);
  590. currentStream.add("[] 0 d ");
  591. if (horz) {
  592. currentStream.add(h + " w\n");
  593. float ym = y1 + (h / 2);
  594. currentStream.add(x1 + " " + ym + " m " + x2 + " " + ym + " l S\n");
  595. } else {
  596. currentStream.add(w + " w\n");
  597. float xm = x1 + (w / 2);
  598. currentStream.add(xm + " " + y1 + " m " + xm + " " + y2 + " l S\n");
  599. }
  600. }
  601. }
  602. /**
  603. * Sets the current line width in points.
  604. * @param width line width in points
  605. */
  606. private void updateLineWidth(float width) {
  607. if (currentState.setLineWidth(width)) {
  608. //Only write if value has changed WRT the current line width
  609. currentStream.add(width + " w\n");
  610. }
  611. }
  612. /**
  613. * Clip a rectangular area.
  614. * write a clipping operation given coordinates in the current
  615. * transform.
  616. * @param x the x coordinate
  617. * @param y the y coordinate
  618. * @param width the width of the area
  619. * @param height the height of the area
  620. */
  621. protected void clipRect(float x, float y, float width, float height) {
  622. currentStream.add(x + " " + y + " " + width + " " + height + " re ");
  623. clip();
  624. }
  625. /**
  626. * Clip an area.
  627. */
  628. protected void clip() {
  629. currentStream.add("W\n");
  630. currentStream.add("n\n");
  631. }
  632. /**
  633. * Moves the current point to (x, y), omitting any connecting line segment.
  634. * @param x x coordinate
  635. * @param y y coordinate
  636. */
  637. protected void moveTo(float x, float y) {
  638. currentStream.add(x + " " + y + " m ");
  639. }
  640. /**
  641. * Appends a straight line segment from the current point to (x, y). The
  642. * new current point is (x, y).
  643. * @param x x coordinate
  644. * @param y y coordinate
  645. */
  646. protected void lineTo(float x, float y) {
  647. currentStream.add(x + " " + y + " l ");
  648. }
  649. /**
  650. * Closes the current subpath by appending a straight line segment from
  651. * the current point to the starting point of the subpath.
  652. */
  653. protected void closePath() {
  654. currentStream.add("h ");
  655. }
  656. /**
  657. * @see org.apache.fop.render.AbstractPathOrientedRenderer#fillRect(float, float, float, float)
  658. */
  659. protected void fillRect(float x, float y, float w, float h) {
  660. currentStream.add(x + " " + y + " " + w + " " + h + " re f\n");
  661. }
  662. /**
  663. * Draw a line.
  664. *
  665. * @param startx the start x position
  666. * @param starty the start y position
  667. * @param endx the x end position
  668. * @param endy the y end position
  669. */
  670. private void drawLine(float startx, float starty, float endx, float endy) {
  671. currentStream.add(startx + " " + starty + " m ");
  672. currentStream.add(endx + " " + endy + " l S\n");
  673. }
  674. /**
  675. * @see org.apache.fop.render.AbstractRenderer#renderBlockViewport(BlockViewport, List)
  676. *//*
  677. protected void renderBlockViewport(BlockViewport bv, List children) {
  678. // clip and position viewport if necessary
  679. // save positions
  680. int saveIP = currentIPPosition;
  681. int saveBP = currentBPPosition;
  682. String saveFontName = currentFontName;
  683. CTM ctm = bv.getCTM();
  684. int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
  685. int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();
  686. float x, y;
  687. x = (float)(bv.getXOffset() + containingIPPosition) / 1000f;
  688. y = (float)(bv.getYOffset() + containingBPPosition) / 1000f;
  689. if (bv.getPositioning() == Block.ABSOLUTE
  690. || bv.getPositioning() == Block.FIXED) {
  691. //For FIXED, we need to break out of the current viewports to the
  692. //one established by the page. We save the state stack for restoration
  693. //after the block-container has been painted. See below.
  694. List breakOutList = null;
  695. if (bv.getPositioning() == Block.FIXED) {
  696. breakOutList = breakOutOfStateStack();
  697. }
  698. CTM tempctm = new CTM(containingIPPosition, containingBPPosition);
  699. ctm = tempctm.multiply(ctm);
  700. //This is the content-rect
  701. float width = (float)bv.getIPD() / 1000f;
  702. float height = (float)bv.getBPD() / 1000f;
  703. //Adjust for spaces (from margin or indirectly by start-indent etc.
  704. Integer spaceStart = (Integer) bv.getTrait(Trait.SPACE_START);
  705. if (spaceStart != null) {
  706. x += spaceStart.floatValue() / 1000;
  707. }
  708. Integer spaceBefore = (Integer) bv.getTrait(Trait.SPACE_BEFORE);
  709. if (spaceBefore != null) {
  710. y += spaceBefore.floatValue() / 1000;
  711. }
  712. float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd()) / 1000f;
  713. float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter()) / 1000f;
  714. drawBackAndBorders(bv, x, y, width + bpwidth, height + bpheight);
  715. //Now adjust for border/padding
  716. x += borderPaddingStart / 1000f;
  717. y += borderPaddingBefore / 1000f;
  718. if (bv.getClip()) {
  719. saveGraphicsState();
  720. clipRect(x, y, width, height);
  721. }
  722. startVParea(ctm);
  723. currentIPPosition = 0;
  724. currentBPPosition = 0;
  725. renderBlocks(bv, children);
  726. endVParea();
  727. if (bv.getClip()) {
  728. restoreGraphicsState();
  729. }
  730. // clip if necessary
  731. if (breakOutList != null) {
  732. restoreStateStackAfterBreakOut(breakOutList);
  733. }
  734. currentIPPosition = saveIP;
  735. currentBPPosition = saveBP;
  736. } else {
  737. Integer spaceBefore = (Integer)bv.getTrait(Trait.SPACE_BEFORE);
  738. if (spaceBefore != null) {
  739. currentBPPosition += spaceBefore.intValue();
  740. }
  741. //borders and background in the old coordinate system
  742. handleBlockTraits(bv);
  743. CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
  744. ctm = tempctm.multiply(ctm);
  745. //Now adjust for border/padding
  746. x += borderPaddingStart / 1000f;
  747. y += borderPaddingBefore / 1000f;
  748. // clip if necessary
  749. if (bv.getClip()) {
  750. saveGraphicsState();
  751. float width = (float)bv.getIPD() / 1000f;
  752. float height = (float)bv.getBPD() / 1000f;
  753. clipRect(x, y, width, height);
  754. }
  755. if (ctm != null) {
  756. startVParea(ctm);
  757. currentIPPosition = 0;
  758. currentBPPosition = 0;
  759. }
  760. renderBlocks(bv, children);
  761. if (ctm != null) {
  762. endVParea();
  763. }
  764. if (bv.getClip()) {
  765. restoreGraphicsState();
  766. }
  767. currentIPPosition = saveIP;
  768. currentBPPosition = saveBP;
  769. //Adjust BP position (alloc BPD + spaces)
  770. if (spaceBefore != null) {
  771. currentBPPosition += spaceBefore.intValue();
  772. }
  773. currentBPPosition += (int)(bv.getAllocBPD());
  774. Integer spaceAfter = (Integer)bv.getTrait(Trait.SPACE_AFTER);
  775. if (spaceAfter != null) {
  776. currentBPPosition += spaceAfter.intValue();
  777. }
  778. }
  779. currentFontName = saveFontName;
  780. }*/
  781. /**
  782. * Breaks out of the state stack to handle fixed block-containers.
  783. * @return the saved state stack to recreate later
  784. */
  785. protected List breakOutOfStateStack() {
  786. List breakOutList = new java.util.ArrayList();
  787. PDFState.Data data;
  788. while (true) {
  789. data = currentState.getData();
  790. if (currentState.pop() == null) {
  791. break;
  792. }
  793. if (breakOutList.size() == 0) {
  794. comment("------ break out!");
  795. }
  796. breakOutList.add(0, data); //Insert because of stack-popping
  797. restoreGraphicsState();
  798. }
  799. return breakOutList;
  800. }
  801. /**
  802. * Restores the state stack after a break out.
  803. * @param breakOutList the state stack to restore.
  804. */
  805. protected void restoreStateStackAfterBreakOut(List breakOutList) {
  806. CTM tempctm;
  807. comment("------ restoring context after break-out...");
  808. PDFState.Data data;
  809. Iterator i = breakOutList.iterator();
  810. double[] matrix = new double[6];
  811. while (i.hasNext()) {
  812. data = (PDFState.Data)i.next();
  813. currentState.push();
  814. saveGraphicsState();
  815. AffineTransform at = data.getTransform();
  816. if (!at.isIdentity()) {
  817. currentState.setTransform(at);
  818. at.getMatrix(matrix);
  819. tempctm = new CTM(matrix[0], matrix[1], matrix[2], matrix[3],
  820. matrix[4] * 1000, matrix[5] * 1000);
  821. currentStream.add(CTMHelper.toPDFString(tempctm) + " cm\n");
  822. }
  823. //TODO Break-out: Also restore items such as line width and color
  824. //Left out for now because all this painting stuff is very
  825. //inconsistent. Some values go over PDFState, some don't.
  826. }
  827. comment("------ done.");
  828. }
  829. /**
  830. * @see org.apache.fop.render.AbstractRenderer#renderLineArea(LineArea)
  831. */
  832. protected void renderLineArea(LineArea line) {
  833. super.renderLineArea(line);
  834. closeText();
  835. }
  836. /**
  837. * Render inline parent area.
  838. * For pdf this handles the inline parent area traits such as
  839. * links, border, background.
  840. * @param ip the inline parent area
  841. */
  842. public void renderInlineParent(InlineParent ip) {
  843. float start = currentIPPosition / 1000f;
  844. float top = (ip.getOffset() + currentBPPosition) / 1000f;
  845. float width = ip.getIPD() / 1000f;
  846. float height = ip.getBPD() / 1000f;
  847. // render contents
  848. super.renderInlineParent(ip);
  849. // place the link over the top
  850. Object tr = ip.getTrait(Trait.INTERNAL_LINK);
  851. boolean internal = false;
  852. String dest = null;
  853. float yoffset = 0;
  854. if (tr == null) {
  855. dest = (String)ip.getTrait(Trait.EXTERNAL_LINK);
  856. } else {
  857. String pvKey = (String)tr;
  858. dest = (String)pageReferences.get(pvKey);
  859. if (dest != null) {
  860. PageViewport pv = (PageViewport)pvReferences.get(pvKey);
  861. Rectangle2D bounds = pv.getViewArea();
  862. double h = bounds.getHeight();
  863. yoffset = (float)h / 1000f;
  864. internal = true;
  865. }
  866. }
  867. if (dest != null) {
  868. // add link to pdf document
  869. Rectangle2D rect = new Rectangle2D.Float(start, top, width, height);
  870. // transform rect to absolute coords
  871. AffineTransform transform = currentState.getTransform();
  872. rect = transform.createTransformedShape(rect).getBounds2D();
  873. rect = currentBasicTransform.createTransformedShape(rect).getBounds2D();
  874. int type = internal ? PDFLink.INTERNAL : PDFLink.EXTERNAL;
  875. PDFLink pdflink = pdfDoc.getFactory().makeLink(
  876. rect, dest, type, yoffset);
  877. currentPage.addAnnotation(pdflink);
  878. }
  879. }
  880. /**
  881. * @see org.apache.fop.render.AbstractRenderer#renderCharacter(Character)
  882. */
  883. public void renderCharacter(Character ch) {
  884. renderInlineAreaBackAndBorders(ch);
  885. beginTextObject();
  886. StringBuffer pdf = new StringBuffer();
  887. String name = (String) ch.getTrait(Trait.FONT_NAME);
  888. int size = ((Integer) ch.getTrait(Trait.FONT_SIZE)).intValue();
  889. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  890. Typeface tf = (Typeface) fontInfo.getFonts().get(name);
  891. boolean useMultiByte = tf.isMultiByte();
  892. // String startText = useMultiByte ? "<FEFF" : "(";
  893. String startText = useMultiByte ? "<" : "(";
  894. String endText = useMultiByte ? "> " : ") ";
  895. updateFont(name, size, pdf);
  896. ColorType ct = (ColorType) ch.getTrait(Trait.COLOR);
  897. if (ct != null) {
  898. updateColor(ct, true, pdf);
  899. }
  900. // word.getOffset() = only height of text itself
  901. // currentBlockIPPosition: 0 for beginning of line; nonzero
  902. // where previous line area failed to take up entire allocated space
  903. int rx = currentIPPosition + ch.getBorderAndPaddingWidthStart();
  904. int bl = currentBPPosition + ch.getOffset() + ch.getBaselineOffset();
  905. /* System.out.println("Text = " + ch.getTextArea() +
  906. "; text width: " + ch.getWidth() +
  907. "; BlockIP Position: " + currentBlockIPPosition +
  908. "; currentBPPosition: " + currentBPPosition +
  909. "; offset: " + ch.getOffset());
  910. */
  911. // Set letterSpacing
  912. //float ls = fs.getLetterSpacing() / this.currentFontSize;
  913. //pdf.append(ls).append(" Tc\n");
  914. if (!textOpen || bl != prevWordY) {
  915. closeText();
  916. pdf.append("1 0 0 -1 " + (rx / 1000f) + " " + (bl / 1000f) + " Tm "
  917. + (ch.getTextLetterSpaceAdjust() / 1000f) + " Tc "
  918. + (ch.getTextWordSpaceAdjust() / 1000f) + " Tw [" + startText);
  919. prevWordY = bl;
  920. textOpen = true;
  921. } else {
  922. closeText();
  923. pdf.append("1 0 0 -1 " + (rx / 1000f) + " " + (bl / 1000f) + " Tm "
  924. + (ch.getTextLetterSpaceAdjust() / 1000f) + " Tc "
  925. + (ch.getTextWordSpaceAdjust() / 1000f) + " Tw [" + startText);
  926. textOpen = true;
  927. }
  928. prevWordWidth = ch.getIPD();
  929. prevWordX = rx;
  930. String s = ch.getChar();
  931. FontMetrics metrics = fontInfo.getMetricsFor(name);
  932. Font fs = new Font(name, metrics, size);
  933. escapeText(s, fs, useMultiByte, pdf);
  934. pdf.append(endText);
  935. currentStream.add(pdf.toString());
  936. renderTextDecoration(tf, size, ch, bl, rx);
  937. super.renderCharacter(ch);
  938. }
  939. /**
  940. * @see org.apache.fop.render.AbstractRenderer#renderText(TextArea)
  941. */
  942. public void renderText(TextArea text) {
  943. renderInlineAreaBackAndBorders(text);
  944. beginTextObject();
  945. StringBuffer pdf = new StringBuffer();
  946. String name = (String) text.getTrait(Trait.FONT_NAME);
  947. int size = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue();
  948. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  949. Typeface tf = (Typeface) fontInfo.getFonts().get(name);
  950. boolean useMultiByte = tf.isMultiByte();
  951. updateFont(name, size, pdf);
  952. ColorType ct = (ColorType) text.getTrait(Trait.COLOR);
  953. updateColor(ct, true, pdf);
  954. // word.getOffset() = only height of text itself
  955. // currentBlockIPPosition: 0 for beginning of line; nonzero
  956. // where previous line area failed to take up entire allocated space
  957. int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
  958. int bl = currentBPPosition + text.getOffset() + text.getBaselineOffset();
  959. /* System.out.println("Text = " + text.getTextArea() +
  960. "; text width: " + text.getWidth() +
  961. "; BlockIP Position: " + currentBlockIPPosition +
  962. "; currentBPPosition: " + currentBPPosition +
  963. "; offset: " + text.getOffset());
  964. */
  965. // Set letterSpacing
  966. //float ls = fs.getLetterSpacing() / this.currentFontSize;
  967. //pdf.append(ls).append(" Tc\n");
  968. if (!textOpen || bl != prevWordY) {
  969. closeText();
  970. pdf.append("1 0 0 -1 " + (rx / 1000f) + " " + (bl / 1000f) + " Tm "
  971. + (text.getTextLetterSpaceAdjust() / 1000f) + " Tc "
  972. + (text.getTextWordSpaceAdjust() / 1000f) + " Tw [");
  973. prevWordY = bl;
  974. textOpen = true;
  975. } else {
  976. closeText();
  977. pdf.append("1 0 0 -1 " + (rx / 1000f) + " " + (bl / 1000f) + " Tm "
  978. + (text.getTextLetterSpaceAdjust() / 1000f) + " Tc "
  979. + (text.getTextWordSpaceAdjust() / 1000f) + " Tw [");
  980. textOpen = true;
  981. }
  982. prevWordWidth = text.getIPD();
  983. prevWordX = rx;
  984. currentStream.add(pdf.toString());
  985. renderTextDecoration(tf, size, text, bl, rx);
  986. super.renderText(text);
  987. }
  988. /**
  989. * @see org.apache.fop.render.AbstractRenderer#renderWord(WordArea)
  990. */
  991. public void renderWord(WordArea word) {
  992. String name = (String) word.getParentArea().getTrait(Trait.FONT_NAME);
  993. int size = ((Integer) word.getParentArea().getTrait(Trait.FONT_SIZE)).intValue();
  994. Typeface tf = (Typeface) fontInfo.getFonts().get(name);
  995. boolean useMultiByte = tf.isMultiByte();
  996. String startText = useMultiByte ? "<" : "(";
  997. String endText = useMultiByte ? "> " : ") ";
  998. StringBuffer pdf = new StringBuffer();
  999. pdf.append(startText);
  1000. String s = word.getWord();
  1001. FontMetrics metrics = fontInfo.getMetricsFor(name);
  1002. Font fs = new Font(name, metrics, size);
  1003. escapeText(s, fs, useMultiByte, pdf);
  1004. pdf.append(endText);
  1005. currentStream.add(pdf.toString());
  1006. super.renderWord(word);
  1007. }
  1008. /**
  1009. * @see org.apache.fop.render.AbstractRenderer#renderSpace(SpaceArea)
  1010. */
  1011. public void renderSpace(SpaceArea space) {
  1012. String name = (String) space.getParentArea().getTrait(Trait.FONT_NAME);
  1013. int size = ((Integer) space.getParentArea().getTrait(Trait.FONT_SIZE)).intValue();
  1014. Typeface tf = (Typeface) fontInfo.getFonts().get(name);
  1015. boolean useMultiByte = tf.isMultiByte();
  1016. String startText = useMultiByte ? "<" : "(";
  1017. String endText = useMultiByte ? "> " : ") ";
  1018. StringBuffer pdf = new StringBuffer();
  1019. pdf.append(startText);
  1020. String s = space.getSpace();
  1021. FontMetrics metrics = fontInfo.getMetricsFor(name);
  1022. Font fs = new Font(name, metrics, size);
  1023. escapeText(s, fs, useMultiByte, pdf);
  1024. pdf.append(endText);
  1025. if (useMultiByte) {
  1026. pdf.append(-(((TextArea) space.getParentArea()).getTextWordSpaceAdjust() / (size / 1000)) + " ");
  1027. }
  1028. currentStream.add(pdf.toString());
  1029. super.renderSpace(space);
  1030. }
  1031. /**
  1032. * Escapes text according to PDF rules.
  1033. * @param s Text to escape
  1034. * @param fs Font state
  1035. * @param useMultiByte Indicates the use of multi byte convention
  1036. * @param pdf target buffer for the escaped text
  1037. */
  1038. public void escapeText(String s, Font fs,
  1039. boolean useMultiByte, StringBuffer pdf) {
  1040. String startText = useMultiByte ? "<" : "(";
  1041. String endText = useMultiByte ? "> " : ") ";
  1042. boolean kerningAvailable = false;
  1043. Map kerning = fs.getKerning();
  1044. if (kerning != null && !kerning.isEmpty()) {
  1045. //kerningAvailable = true;
  1046. //TODO Reenable me when the layout engine supports kerning, too
  1047. log.warn("Kerning support is disabled until it is supported by the layout engine!");
  1048. }
  1049. int l = s.length();
  1050. for (int i = 0; i < l; i++) {
  1051. char ch = fs.mapChar(s.charAt(i));
  1052. if (!useMultiByte) {
  1053. if (ch > 127) {
  1054. pdf.append("\\");
  1055. pdf.append(Integer.toOctalString((int) ch));
  1056. } else {
  1057. switch (ch) {
  1058. case '(':
  1059. case ')':
  1060. case '\\':
  1061. pdf.append("\\");
  1062. break;
  1063. }
  1064. pdf.append(ch);
  1065. }
  1066. } else {
  1067. pdf.append(PDFText.toUnicodeHex(ch));
  1068. }
  1069. if (kerningAvailable && (i + 1) < l) {
  1070. addKerning(pdf, (new Integer((int) ch)),
  1071. (new Integer((int) fs.mapChar(s.charAt(i + 1)))
  1072. ), kerning, startText, endText);
  1073. }
  1074. }
  1075. }
  1076. private void addKerning(StringBuffer buf, Integer ch1, Integer ch2,
  1077. Map kerning, String startText, String endText) {
  1078. Map kernPair = (Map) kerning.get(ch1);
  1079. if (kernPair != null) {
  1080. Integer width = (Integer) kernPair.get(ch2);
  1081. if (width != null) {
  1082. buf.append(endText).append(-width.intValue());
  1083. buf.append(' ').append(startText);
  1084. }
  1085. }
  1086. }
  1087. /**
  1088. * Checks to see if we have some text rendering commands open
  1089. * still and writes out the TJ command to the stream if we do
  1090. */
  1091. protected void closeText() {
  1092. if (textOpen) {
  1093. currentStream.add("] TJ\n");
  1094. textOpen = false;
  1095. prevWordX = 0;
  1096. prevWordY = 0;
  1097. currentFontName = "";
  1098. }
  1099. }
  1100. /**
  1101. * Establishes a new foreground or fill color. In contrast to updateColor
  1102. * this method does not check the PDFState for optimization possibilities.
  1103. * @param col the color to apply
  1104. * @param fill true to set the fill color, false for the foreground color
  1105. * @param pdf StringBuffer to write the PDF code to, if null, the code is
  1106. * written to the current stream.
  1107. */
  1108. protected void setColor(Color col, boolean fill, StringBuffer pdf) {
  1109. PDFColor color = new PDFColor(col);
  1110. closeText();
  1111. if (pdf != null) {
  1112. pdf.append(color.getColorSpaceOut(fill));
  1113. } else {
  1114. currentStream.add(color.getColorSpaceOut(fill));
  1115. }
  1116. }
  1117. /**
  1118. * Establishes a new foreground or fill color.
  1119. * @param col the color to apply (null skips this operation)
  1120. * @param fill true to set the fill color, false for the foreground color
  1121. * @param pdf StringBuffer to write the PDF code to, if null, the code is
  1122. * written to the current stream.
  1123. */
  1124. private void updateColor(ColorType col, boolean fill, StringBuffer pdf) {
  1125. if (col == null) {
  1126. return;
  1127. }
  1128. Color newCol = toColor(col);
  1129. boolean update = false;
  1130. if (fill) {
  1131. update = currentState.setBackColor(newCol);
  1132. } else {
  1133. update = currentState.setColor(newCol);
  1134. }
  1135. if (update) {
  1136. setColor(newCol, fill, pdf);
  1137. }
  1138. }
  1139. /** @see org.apache.fop.render.AbstractPathOrientedRenderer */
  1140. protected void updateColor(ColorType col, boolean fill) {
  1141. updateColor(col, fill, null);
  1142. }
  1143. private void updateFont(String name, int size, StringBuffer pdf) {
  1144. if ((!name.equals(this.currentFontName))
  1145. || (size != this.currentFontSize)) {
  1146. closeText();
  1147. this.currentFontName = name;
  1148. this.currentFontSize = size;
  1149. pdf = pdf.append("/" + name + " " + ((float) size / 1000f)
  1150. + " Tf\n");
  1151. }
  1152. }
  1153. /**
  1154. * @see org.apache.fop.render.AbstractRenderer#renderImage(Image, Rectangle2D)
  1155. */
  1156. public void renderImage(Image image, Rectangle2D pos) {
  1157. endTextObject();
  1158. String url = image.getURL();
  1159. putImage(url, pos);
  1160. }
  1161. /** @see org.apache.fop.render.AbstractPathOrientedRenderer */
  1162. protected void drawImage(String url, Rectangle2D pos) {
  1163. endTextObject();
  1164. putImage(url, pos);
  1165. }
  1166. /**
  1167. * Adds a PDF XObject (a bitmap) to the PDF that will later be referenced.
  1168. * @param url URL of the bitmap
  1169. * @param pos Position of the bitmap
  1170. */
  1171. protected void putImage(String url, Rectangle2D pos) {
  1172. PDFXObject xobject = pdfDoc.getImage(url);
  1173. if (xobject != null) {
  1174. float w = (float) pos.getWidth() / 1000f;
  1175. float h = (float) pos.getHeight() / 1000f;
  1176. placeImage((float)pos.getX() / 1000f,
  1177. (float)pos.getY() / 1000f, w, h, xobject.getXNumber());
  1178. return;
  1179. }
  1180. url = ImageFactory.getURL(url);
  1181. ImageFactory fact = ImageFactory.getInstance();
  1182. FopImage fopimage = fact.getImage(url, userAgent);
  1183. if (fopimage == null) {
  1184. return;
  1185. }
  1186. if (!fopimage.load(FopImage.DIMENSIONS)) {
  1187. return;
  1188. }
  1189. String mime = fopimage.getMimeType();
  1190. if ("text/xml".equals(mime)) {
  1191. if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
  1192. return;
  1193. }
  1194. Document doc = ((XMLImage) fopimage).getDocument();
  1195. String ns = ((XMLImage) fopimage).getNameSpace();
  1196. renderDocument(doc, ns, pos);
  1197. } else if ("image/svg+xml".equals(mime)) {
  1198. if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
  1199. return;
  1200. }
  1201. Document doc = ((XMLImage) fopimage).getDocument();
  1202. String ns = ((XMLImage) fopimage).getNameSpace();
  1203. renderDocument(doc, ns, pos);
  1204. } else if ("image/eps".equals(mime)) {
  1205. FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
  1206. int xobj = pdfDoc.addImage(currentContext, pdfimage).getXNumber();
  1207. fact.releaseImage(url, userAgent);
  1208. } else if ("image/jpeg".equals(mime) || "image/tiff".equals(mime)) {
  1209. FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
  1210. int xobj = pdfDoc.addImage(currentContext, pdfimage).getXNumber();
  1211. fact.releaseImage(url, userAgent);
  1212. float w = (float)pos.getWidth() / 1000f;
  1213. float h = (float)pos.getHeight() / 1000f;
  1214. placeImage((float) pos.getX() / 1000,
  1215. (float) pos.getY() / 1000, w, h, xobj);
  1216. } else {
  1217. FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
  1218. int xobj = pdfDoc.addImage(currentContext, pdfimage).getXNumber();
  1219. fact.releaseImage(url, userAgent);
  1220. float w = (float) pos.getWidth() / 1000f;
  1221. float h = (float) pos.getHeight() / 1000f;
  1222. placeImage((float) pos.getX() / 1000f,
  1223. (float) pos.getY() / 1000f, w, h, xobj);
  1224. }
  1225. // output new data
  1226. try {
  1227. this.pdfDoc.output(ostream);
  1228. } catch (IOException ioe) {
  1229. // ioexception will be caught later
  1230. }
  1231. }
  1232. /**
  1233. * Places a previously registered image at a certain place on the page.
  1234. * @param x X coordinate
  1235. * @param y Y coordinate
  1236. * @param w width for image
  1237. * @param h height for image
  1238. * @param xobj object number of the referenced image
  1239. */
  1240. protected void placeImage(float x, float y, float w, float h, int xobj) {
  1241. saveGraphicsState();
  1242. currentStream.add(w + " 0 0 "
  1243. + -h + " "
  1244. + (currentIPPosition / 1000f + x) + " "
  1245. + (currentBPPosition / 1000f + h + y)
  1246. + " cm\n" + "/Im" + xobj + " Do\n");
  1247. restoreGraphicsState();
  1248. }
  1249. /**
  1250. * @see org.apache.fop.render.AbstractRenderer#renderForeignObject(ForeignObject, Rectangle2D)
  1251. */
  1252. public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
  1253. endTextObject();
  1254. Document doc = fo.getDocument();
  1255. String ns = fo.getNameSpace();
  1256. renderDocument(doc, ns, pos);
  1257. }
  1258. /**
  1259. * Renders an XML document (SVG for example).
  1260. * @param doc DOM document representing the XML document
  1261. * @param ns Namespace for the document
  1262. * @param pos Position on the page
  1263. */
  1264. public void renderDocument(Document doc, String ns, Rectangle2D pos) {
  1265. RendererContext context;
  1266. context = new RendererContext(this, MIME_TYPE);
  1267. context.setUserAgent(userAgent);
  1268. context.setProperty(PDFSVGHandler.PDF_DOCUMENT, pdfDoc);
  1269. context.setProperty(PDFSVGHandler.OUTPUT_STREAM, ostream);
  1270. context.setProperty(PDFSVGHandler.PDF_STATE, currentState);
  1271. context.setProperty(PDFSVGHandler.PDF_PAGE, currentPage);
  1272. context.setProperty(PDFSVGHandler.PDF_CONTEXT,
  1273. currentContext == null ? currentPage : currentContext);
  1274. context.setProperty(PDFSVGHandler.PDF_CONTEXT, currentContext);
  1275. context.setProperty(PDFSVGHandler.PDF_STREAM, currentStream);
  1276. context.setProperty(PDFSVGHandler.PDF_XPOS,
  1277. new Integer(currentIPPosition + (int) pos.getX()));
  1278. context.setProperty(PDFSVGHandler.PDF_YPOS,
  1279. new Integer(currentBPPosition + (int) pos.getY()));
  1280. context.setProperty(PDFSVGHandler.PDF_FONT_INFO, fontInfo);
  1281. context.setProperty(PDFSVGHandler.PDF_FONT_NAME, currentFontName);
  1282. context.setProperty(PDFSVGHandler.PDF_FONT_SIZE,
  1283. new Integer(currentFontSize));
  1284. context.setProperty(PDFSVGHandler.PDF_WIDTH,
  1285. new Integer((int) pos.getWidth()));
  1286. context.setProperty(PDFSVGHandler.PDF_HEIGHT,
  1287. new Integer((int) pos.getHeight()));
  1288. renderXML(context, doc, ns);
  1289. }
  1290. /**
  1291. * Render leader area.
  1292. * This renders a leader area which is an area with a rule.
  1293. * @param area the leader area to render
  1294. */
  1295. public void renderLeader(Leader area) {
  1296. renderInlineAreaBackAndBorders(area);
  1297. currentState.push();
  1298. saveGraphicsState();
  1299. int style = area.getRuleStyle();
  1300. boolean alt = false;
  1301. switch(style) {
  1302. case EN_SOLID:
  1303. currentStream.add("[] 0 d\n");
  1304. break;
  1305. case EN_DOTTED:
  1306. currentStream.add("[2] 0 d\n");
  1307. break;
  1308. case EN_DASHED:
  1309. currentStream.add("[6 4] 0 d\n");
  1310. break;
  1311. case EN_DOUBLE:
  1312. case EN_GROOVE:
  1313. case EN_RIDGE:
  1314. alt = true;
  1315. break;
  1316. }
  1317. float startx = (currentIPPosition + area.getBorderAndPaddingWidthStart()) / 1000f;
  1318. float starty = (currentBPPosition + area.getOffset()) / 1000f;
  1319. float endx = (currentIPPosition + area.getBorderAndPaddingWidthStart()
  1320. + area.getIPD()) / 1000f;
  1321. // PDF draws lines centered on the Y coordiante, therefore we need to
  1322. // add half of the line thickness to the Y positions.
  1323. if (!alt) {
  1324. updateLineWidth(area.getRuleThickness() / 1000f);
  1325. drawLine(startx, starty + area.getRuleThickness() / 2000f
  1326. , endx, starty + area.getRuleThickness() / 2000f);
  1327. } else {
  1328. if (style == EN_DOUBLE) {
  1329. float third = area.getRuleThickness() / 3000f;
  1330. updateLineWidth(third);
  1331. drawLine(startx, starty + 0.5f * third, endx, starty + 0.5f * third);
  1332. drawLine(startx, (starty + 2.5f * third), endx, (starty + 2.5f * third));
  1333. } else {
  1334. float half = area.getRuleThickness() / 2000f;
  1335. currentStream.add("1 g\n");
  1336. currentStream.add(startx + " " + starty + " m\n");
  1337. currentStream.add(endx + " " + starty + " l\n");
  1338. currentStream.add(endx + " " + (starty + 2 * half) + " l\n");
  1339. currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
  1340. currentStream.add("h\n");
  1341. currentStream.add("f\n");
  1342. if (style == EN_GROOVE) {
  1343. currentStream.add("0 g\n");
  1344. currentStream.add(startx + " " + starty + " m\n");
  1345. currentStream.add(endx + " " + starty + " l\n");
  1346. currentStream.add(endx + " " + (starty + half) + " l\n");
  1347. currentStream.add((startx + half) + " " + (starty + half) + " l\n");
  1348. currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
  1349. } else {
  1350. currentStream.add("0 g\n");
  1351. currentStream.add(endx + " " + starty + " m\n");
  1352. currentStream.add(endx + " " + (starty + 2 * half) + " l\n");
  1353. currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
  1354. currentStream.add(startx + " " + (starty + half) + " l\n");
  1355. currentStream.add((endx - half) + " " + (starty + half) + " l\n");
  1356. }
  1357. currentStream.add("h\n");
  1358. currentStream.add("f\n");
  1359. }
  1360. }
  1361. restoreGraphicsState();
  1362. currentState.pop();
  1363. beginTextObject();
  1364. super.renderLeader(area);
  1365. }
  1366. /** @see org.apache.fop.render.AbstractRenderer */
  1367. public String getMimeType() {
  1368. return MIME_TYPE;
  1369. }
  1370. }