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

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