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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  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. currentStream.add(x + " " + y + " " + w + " " + h + " re f\n");
  667. }
  668. /**
  669. * Draw a line.
  670. *
  671. * @param startx the start x position
  672. * @param starty the start y position
  673. * @param endx the x end position
  674. * @param endy the y end position
  675. */
  676. private void drawLine(float startx, float starty, float endx, float endy) {
  677. currentStream.add(startx + " " + starty + " m ");
  678. currentStream.add(endx + " " + endy + " l S\n");
  679. }
  680. /**
  681. * @see org.apache.fop.render.AbstractRenderer#renderBlockViewport(BlockViewport, List)
  682. *//*
  683. protected void renderBlockViewport(BlockViewport bv, List children) {
  684. // clip and position viewport if necessary
  685. // save positions
  686. int saveIP = currentIPPosition;
  687. int saveBP = currentBPPosition;
  688. String saveFontName = currentFontName;
  689. CTM ctm = bv.getCTM();
  690. int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
  691. int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();
  692. float x, y;
  693. x = (float)(bv.getXOffset() + containingIPPosition) / 1000f;
  694. y = (float)(bv.getYOffset() + containingBPPosition) / 1000f;
  695. if (bv.getPositioning() == Block.ABSOLUTE
  696. || bv.getPositioning() == Block.FIXED) {
  697. //For FIXED, we need to break out of the current viewports to the
  698. //one established by the page. We save the state stack for restoration
  699. //after the block-container has been painted. See below.
  700. List breakOutList = null;
  701. if (bv.getPositioning() == Block.FIXED) {
  702. breakOutList = breakOutOfStateStack();
  703. }
  704. CTM tempctm = new CTM(containingIPPosition, containingBPPosition);
  705. ctm = tempctm.multiply(ctm);
  706. //This is the content-rect
  707. float width = (float)bv.getIPD() / 1000f;
  708. float height = (float)bv.getBPD() / 1000f;
  709. //Adjust for spaces (from margin or indirectly by start-indent etc.
  710. Integer spaceStart = (Integer) bv.getTrait(Trait.SPACE_START);
  711. if (spaceStart != null) {
  712. x += spaceStart.floatValue() / 1000;
  713. }
  714. Integer spaceBefore = (Integer) bv.getTrait(Trait.SPACE_BEFORE);
  715. if (spaceBefore != null) {
  716. y += spaceBefore.floatValue() / 1000;
  717. }
  718. float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd()) / 1000f;
  719. float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter()) / 1000f;
  720. drawBackAndBorders(bv, x, y, width + bpwidth, height + bpheight);
  721. //Now adjust for border/padding
  722. x += borderPaddingStart / 1000f;
  723. y += borderPaddingBefore / 1000f;
  724. if (bv.getClip()) {
  725. saveGraphicsState();
  726. clipRect(x, y, width, height);
  727. }
  728. startVParea(ctm);
  729. currentIPPosition = 0;
  730. currentBPPosition = 0;
  731. renderBlocks(bv, children);
  732. endVParea();
  733. if (bv.getClip()) {
  734. restoreGraphicsState();
  735. }
  736. // clip if necessary
  737. if (breakOutList != null) {
  738. restoreStateStackAfterBreakOut(breakOutList);
  739. }
  740. currentIPPosition = saveIP;
  741. currentBPPosition = saveBP;
  742. } else {
  743. Integer spaceBefore = (Integer)bv.getTrait(Trait.SPACE_BEFORE);
  744. if (spaceBefore != null) {
  745. currentBPPosition += spaceBefore.intValue();
  746. }
  747. //borders and background in the old coordinate system
  748. handleBlockTraits(bv);
  749. CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
  750. ctm = tempctm.multiply(ctm);
  751. //Now adjust for border/padding
  752. x += borderPaddingStart / 1000f;
  753. y += borderPaddingBefore / 1000f;
  754. // clip if necessary
  755. if (bv.getClip()) {
  756. saveGraphicsState();
  757. float width = (float)bv.getIPD() / 1000f;
  758. float height = (float)bv.getBPD() / 1000f;
  759. clipRect(x, y, width, height);
  760. }
  761. if (ctm != null) {
  762. startVParea(ctm);
  763. currentIPPosition = 0;
  764. currentBPPosition = 0;
  765. }
  766. renderBlocks(bv, children);
  767. if (ctm != null) {
  768. endVParea();
  769. }
  770. if (bv.getClip()) {
  771. restoreGraphicsState();
  772. }
  773. currentIPPosition = saveIP;
  774. currentBPPosition = saveBP;
  775. //Adjust BP position (alloc BPD + spaces)
  776. if (spaceBefore != null) {
  777. currentBPPosition += spaceBefore.intValue();
  778. }
  779. currentBPPosition += (int)(bv.getAllocBPD());
  780. Integer spaceAfter = (Integer)bv.getTrait(Trait.SPACE_AFTER);
  781. if (spaceAfter != null) {
  782. currentBPPosition += spaceAfter.intValue();
  783. }
  784. }
  785. currentFontName = saveFontName;
  786. }*/
  787. /**
  788. * Breaks out of the state stack to handle fixed block-containers.
  789. * @return the saved state stack to recreate later
  790. */
  791. protected List breakOutOfStateStack() {
  792. List breakOutList = new java.util.ArrayList();
  793. PDFState.Data data;
  794. while (true) {
  795. data = currentState.getData();
  796. if (currentState.pop() == null) {
  797. break;
  798. }
  799. if (breakOutList.size() == 0) {
  800. comment("------ break out!");
  801. }
  802. breakOutList.add(0, data); //Insert because of stack-popping
  803. restoreGraphicsState();
  804. }
  805. return breakOutList;
  806. }
  807. /**
  808. * Restores the state stack after a break out.
  809. * @param breakOutList the state stack to restore.
  810. */
  811. protected void restoreStateStackAfterBreakOut(List breakOutList) {
  812. CTM tempctm;
  813. comment("------ restoring context after break-out...");
  814. PDFState.Data data;
  815. Iterator i = breakOutList.iterator();
  816. double[] matrix = new double[6];
  817. while (i.hasNext()) {
  818. data = (PDFState.Data)i.next();
  819. currentState.push();
  820. saveGraphicsState();
  821. AffineTransform at = data.getTransform();
  822. if (!at.isIdentity()) {
  823. currentState.setTransform(at);
  824. at.getMatrix(matrix);
  825. tempctm = new CTM(matrix[0], matrix[1], matrix[2], matrix[3],
  826. matrix[4] * 1000, matrix[5] * 1000);
  827. currentStream.add(CTMHelper.toPDFString(tempctm) + " cm\n");
  828. }
  829. //TODO Break-out: Also restore items such as line width and color
  830. //Left out for now because all this painting stuff is very
  831. //inconsistent. Some values go over PDFState, some don't.
  832. }
  833. comment("------ done.");
  834. }
  835. /**
  836. * @see org.apache.fop.render.AbstractRenderer#renderLineArea(LineArea)
  837. */
  838. protected void renderLineArea(LineArea line) {
  839. super.renderLineArea(line);
  840. closeText();
  841. }
  842. /**
  843. * Render inline parent area.
  844. * For pdf this handles the inline parent area traits such as
  845. * links, border, background.
  846. * @param ip the inline parent area
  847. */
  848. public void renderInlineParent(InlineParent ip) {
  849. float start = currentIPPosition / 1000f;
  850. float top = (ip.getOffset() + currentBPPosition) / 1000f;
  851. float width = ip.getIPD() / 1000f;
  852. float height = ip.getBPD() / 1000f;
  853. // render contents
  854. super.renderInlineParent(ip);
  855. // place the link over the top
  856. Object tr = ip.getTrait(Trait.INTERNAL_LINK);
  857. boolean internal = false;
  858. String dest = null;
  859. float yoffset = 0;
  860. if (tr == null) {
  861. dest = (String)ip.getTrait(Trait.EXTERNAL_LINK);
  862. } else {
  863. String pvKey = (String)tr;
  864. dest = (String)pageReferences.get(pvKey);
  865. if (dest != null) {
  866. PageViewport pv = (PageViewport)pvReferences.get(pvKey);
  867. Rectangle2D bounds = pv.getViewArea();
  868. double h = bounds.getHeight();
  869. yoffset = (float)h / 1000f;
  870. internal = true;
  871. }
  872. }
  873. if (dest != null) {
  874. // add link to pdf document
  875. Rectangle2D rect = new Rectangle2D.Float(start, top, width, height);
  876. // transform rect to absolute coords
  877. AffineTransform transform = currentState.getTransform();
  878. rect = transform.createTransformedShape(rect).getBounds2D();
  879. rect = currentBasicTransform.createTransformedShape(rect).getBounds2D();
  880. int type = internal ? PDFLink.INTERNAL : PDFLink.EXTERNAL;
  881. PDFLink pdflink = pdfDoc.getFactory().makeLink(
  882. rect, dest, type, yoffset);
  883. currentPage.addAnnotation(pdflink);
  884. }
  885. }
  886. /**
  887. * @see org.apache.fop.render.AbstractRenderer#renderCharacter(Character)
  888. */
  889. public void renderCharacter(Character ch) {
  890. renderInlineAreaBackAndBorders(ch);
  891. beginTextObject();
  892. StringBuffer pdf = new StringBuffer();
  893. String name = (String) ch.getTrait(Trait.FONT_NAME);
  894. int size = ((Integer) ch.getTrait(Trait.FONT_SIZE)).intValue();
  895. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  896. Typeface tf = (Typeface) fontInfo.getFonts().get(name);
  897. boolean useMultiByte = tf.isMultiByte();
  898. // String startText = useMultiByte ? "<FEFF" : "(";
  899. String startText = useMultiByte ? "<" : "(";
  900. String endText = useMultiByte ? "> " : ") ";
  901. updateFont(name, size, pdf);
  902. ColorType ct = (ColorType) ch.getTrait(Trait.COLOR);
  903. if (ct != null) {
  904. updateColor(ct, true, pdf);
  905. }
  906. // word.getOffset() = only height of text itself
  907. // currentBlockIPPosition: 0 for beginning of line; nonzero
  908. // where previous line area failed to take up entire allocated space
  909. int rx = currentIPPosition + ch.getBorderAndPaddingWidthStart();
  910. int bl = currentBPPosition + ch.getOffset() + ch.getBaselineOffset();
  911. /* System.out.println("Text = " + ch.getTextArea() +
  912. "; text width: " + ch.getWidth() +
  913. "; BlockIP Position: " + currentBlockIPPosition +
  914. "; currentBPPosition: " + currentBPPosition +
  915. "; offset: " + ch.getOffset());
  916. */
  917. // Set letterSpacing
  918. //float ls = fs.getLetterSpacing() / this.currentFontSize;
  919. //pdf.append(ls).append(" Tc\n");
  920. if (!textOpen || bl != prevWordY) {
  921. closeText();
  922. pdf.append("1 0 0 -1 " + (rx / 1000f) + " " + (bl / 1000f) + " Tm "
  923. + (ch.getTextLetterSpaceAdjust() / 1000f) + " Tc "
  924. + (ch.getTextWordSpaceAdjust() / 1000f) + " Tw [" + startText);
  925. prevWordY = bl;
  926. textOpen = true;
  927. } else {
  928. closeText();
  929. pdf.append("1 0 0 -1 " + (rx / 1000f) + " " + (bl / 1000f) + " Tm "
  930. + (ch.getTextLetterSpaceAdjust() / 1000f) + " Tc "
  931. + (ch.getTextWordSpaceAdjust() / 1000f) + " Tw [" + startText);
  932. textOpen = true;
  933. }
  934. prevWordWidth = ch.getIPD();
  935. prevWordX = rx;
  936. String s = ch.getChar();
  937. FontMetrics metrics = fontInfo.getMetricsFor(name);
  938. Font fs = new Font(name, metrics, size);
  939. escapeText(s, fs, useMultiByte, pdf);
  940. pdf.append(endText);
  941. currentStream.add(pdf.toString());
  942. renderTextDecoration(tf, size, ch, bl, rx);
  943. super.renderCharacter(ch);
  944. }
  945. /**
  946. * @see org.apache.fop.render.AbstractRenderer#renderText(TextArea)
  947. */
  948. public void renderText(TextArea text) {
  949. renderInlineAreaBackAndBorders(text);
  950. beginTextObject();
  951. StringBuffer pdf = new StringBuffer();
  952. String name = (String) text.getTrait(Trait.FONT_NAME);
  953. int size = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue();
  954. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  955. Typeface tf = (Typeface) fontInfo.getFonts().get(name);
  956. boolean useMultiByte = tf.isMultiByte();
  957. updateFont(name, size, pdf);
  958. ColorType ct = (ColorType) text.getTrait(Trait.COLOR);
  959. updateColor(ct, true, pdf);
  960. // word.getOffset() = only height of text itself
  961. // currentBlockIPPosition: 0 for beginning of line; nonzero
  962. // where previous line area failed to take up entire allocated space
  963. int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
  964. int bl = currentBPPosition + text.getOffset() + text.getBaselineOffset();
  965. /* System.out.println("Text = " + text.getTextArea() +
  966. "; text width: " + text.getWidth() +
  967. "; BlockIP Position: " + currentBlockIPPosition +
  968. "; currentBPPosition: " + currentBPPosition +
  969. "; offset: " + text.getOffset());
  970. */
  971. // Set letterSpacing
  972. //float ls = fs.getLetterSpacing() / this.currentFontSize;
  973. //pdf.append(ls).append(" Tc\n");
  974. if (!textOpen || bl != prevWordY) {
  975. closeText();
  976. pdf.append("1 0 0 -1 " + (rx / 1000f) + " " + (bl / 1000f) + " Tm "
  977. + (text.getTextLetterSpaceAdjust() / 1000f) + " Tc "
  978. + (text.getTextWordSpaceAdjust() / 1000f) + " Tw [");
  979. prevWordY = bl;
  980. textOpen = true;
  981. } else {
  982. closeText();
  983. pdf.append("1 0 0 -1 " + (rx / 1000f) + " " + (bl / 1000f) + " Tm "
  984. + (text.getTextLetterSpaceAdjust() / 1000f) + " Tc "
  985. + (text.getTextWordSpaceAdjust() / 1000f) + " Tw [");
  986. textOpen = true;
  987. }
  988. prevWordWidth = text.getIPD();
  989. prevWordX = rx;
  990. currentStream.add(pdf.toString());
  991. super.renderText(text);
  992. renderTextDecoration(tf, size, text, bl, rx);
  993. }
  994. /**
  995. * @see org.apache.fop.render.AbstractRenderer#renderWord(WordArea)
  996. */
  997. public void renderWord(WordArea word) {
  998. String name = (String) word.getParentArea().getTrait(Trait.FONT_NAME);
  999. int size = ((Integer) word.getParentArea().getTrait(Trait.FONT_SIZE)).intValue();
  1000. Typeface tf = (Typeface) fontInfo.getFonts().get(name);
  1001. boolean useMultiByte = tf.isMultiByte();
  1002. String startText = useMultiByte ? "<" : "(";
  1003. String endText = useMultiByte ? "> " : ") ";
  1004. StringBuffer pdf = new StringBuffer();
  1005. pdf.append(startText);
  1006. String s = word.getWord();
  1007. FontMetrics metrics = fontInfo.getMetricsFor(name);
  1008. Font fs = new Font(name, metrics, size);
  1009. escapeText(s, fs, useMultiByte, pdf);
  1010. pdf.append(endText);
  1011. currentStream.add(pdf.toString());
  1012. super.renderWord(word);
  1013. }
  1014. /**
  1015. * @see org.apache.fop.render.AbstractRenderer#renderSpace(SpaceArea)
  1016. */
  1017. public void renderSpace(SpaceArea space) {
  1018. String name = (String) space.getParentArea().getTrait(Trait.FONT_NAME);
  1019. int size = ((Integer) space.getParentArea().getTrait(Trait.FONT_SIZE)).intValue();
  1020. Typeface tf = (Typeface) fontInfo.getFonts().get(name);
  1021. boolean useMultiByte = tf.isMultiByte();
  1022. String startText = useMultiByte ? "<" : "(";
  1023. String endText = useMultiByte ? "> " : ") ";
  1024. StringBuffer pdf = new StringBuffer();
  1025. pdf.append(startText);
  1026. String s = space.getSpace();
  1027. FontMetrics metrics = fontInfo.getMetricsFor(name);
  1028. Font fs = new Font(name, metrics, size);
  1029. escapeText(s, fs, useMultiByte, pdf);
  1030. pdf.append(endText);
  1031. if (useMultiByte) {
  1032. pdf.append(-(((TextArea) space.getParentArea()).getTextWordSpaceAdjust() / (size / 1000)) + " ");
  1033. }
  1034. currentStream.add(pdf.toString());
  1035. super.renderSpace(space);
  1036. }
  1037. /**
  1038. * Escapes text according to PDF rules.
  1039. * @param s Text to escape
  1040. * @param fs Font state
  1041. * @param useMultiByte Indicates the use of multi byte convention
  1042. * @param pdf target buffer for the escaped text
  1043. */
  1044. public void escapeText(String s, Font fs,
  1045. boolean useMultiByte, StringBuffer pdf) {
  1046. String startText = useMultiByte ? "<" : "(";
  1047. String endText = useMultiByte ? "> " : ") ";
  1048. boolean kerningAvailable = false;
  1049. Map kerning = fs.getKerning();
  1050. if (kerning != null && !kerning.isEmpty()) {
  1051. //kerningAvailable = true;
  1052. //TODO Reenable me when the layout engine supports kerning, too
  1053. log.warn("Kerning support is disabled until it is supported by the layout engine!");
  1054. }
  1055. int l = s.length();
  1056. for (int i = 0; i < l; i++) {
  1057. char ch = fs.mapChar(s.charAt(i));
  1058. if (!useMultiByte) {
  1059. if (ch > 127) {
  1060. pdf.append("\\");
  1061. pdf.append(Integer.toOctalString((int) ch));
  1062. } else {
  1063. switch (ch) {
  1064. case '(':
  1065. case ')':
  1066. case '\\':
  1067. pdf.append("\\");
  1068. break;
  1069. }
  1070. pdf.append(ch);
  1071. }
  1072. } else {
  1073. pdf.append(PDFText.toUnicodeHex(ch));
  1074. }
  1075. if (kerningAvailable && (i + 1) < l) {
  1076. addKerning(pdf, (new Integer((int) ch)),
  1077. (new Integer((int) fs.mapChar(s.charAt(i + 1)))
  1078. ), kerning, startText, endText);
  1079. }
  1080. }
  1081. }
  1082. private void addKerning(StringBuffer buf, Integer ch1, Integer ch2,
  1083. Map kerning, String startText, String endText) {
  1084. Map kernPair = (Map) kerning.get(ch1);
  1085. if (kernPair != null) {
  1086. Integer width = (Integer) kernPair.get(ch2);
  1087. if (width != null) {
  1088. buf.append(endText).append(-width.intValue());
  1089. buf.append(' ').append(startText);
  1090. }
  1091. }
  1092. }
  1093. /**
  1094. * Checks to see if we have some text rendering commands open
  1095. * still and writes out the TJ command to the stream if we do
  1096. */
  1097. protected void closeText() {
  1098. if (textOpen) {
  1099. currentStream.add("] TJ\n");
  1100. textOpen = false;
  1101. prevWordX = 0;
  1102. prevWordY = 0;
  1103. currentFontName = "";
  1104. }
  1105. }
  1106. /**
  1107. * Establishes a new foreground or fill color. In contrast to updateColor
  1108. * this method does not check the PDFState for optimization possibilities.
  1109. * @param col the color to apply
  1110. * @param fill true to set the fill color, false for the foreground color
  1111. * @param pdf StringBuffer to write the PDF code to, if null, the code is
  1112. * written to the current stream.
  1113. */
  1114. protected void setColor(Color col, boolean fill, StringBuffer pdf) {
  1115. PDFColor color = new PDFColor(col);
  1116. closeText();
  1117. if (pdf != null) {
  1118. pdf.append(color.getColorSpaceOut(fill));
  1119. } else {
  1120. currentStream.add(color.getColorSpaceOut(fill));
  1121. }
  1122. }
  1123. /**
  1124. * Establishes a new foreground or fill color.
  1125. * @param col the color to apply (null skips this operation)
  1126. * @param fill true to set the fill color, false for the foreground color
  1127. * @param pdf StringBuffer to write the PDF code to, if null, the code is
  1128. * written to the current stream.
  1129. */
  1130. private void updateColor(ColorType col, boolean fill, StringBuffer pdf) {
  1131. if (col == null) {
  1132. return;
  1133. }
  1134. Color newCol = toColor(col);
  1135. boolean update = false;
  1136. if (fill) {
  1137. update = currentState.setBackColor(newCol);
  1138. } else {
  1139. update = currentState.setColor(newCol);
  1140. }
  1141. if (update) {
  1142. setColor(newCol, fill, pdf);
  1143. }
  1144. }
  1145. /** @see org.apache.fop.render.AbstractPathOrientedRenderer */
  1146. protected void updateColor(ColorType col, boolean fill) {
  1147. updateColor(col, fill, null);
  1148. }
  1149. private void updateFont(String name, int size, StringBuffer pdf) {
  1150. if ((!name.equals(this.currentFontName))
  1151. || (size != this.currentFontSize)) {
  1152. closeText();
  1153. this.currentFontName = name;
  1154. this.currentFontSize = size;
  1155. pdf = pdf.append("/" + name + " " + ((float) size / 1000f)
  1156. + " Tf\n");
  1157. }
  1158. }
  1159. /**
  1160. * @see org.apache.fop.render.AbstractRenderer#renderImage(Image, Rectangle2D)
  1161. */
  1162. public void renderImage(Image image, Rectangle2D pos) {
  1163. endTextObject();
  1164. String url = image.getURL();
  1165. putImage(url, pos);
  1166. }
  1167. /** @see org.apache.fop.render.AbstractPathOrientedRenderer */
  1168. protected void drawImage(String url, Rectangle2D pos) {
  1169. endTextObject();
  1170. putImage(url, pos);
  1171. }
  1172. /**
  1173. * Adds a PDF XObject (a bitmap) to the PDF that will later be referenced.
  1174. * @param url URL of the bitmap
  1175. * @param pos Position of the bitmap
  1176. */
  1177. protected void putImage(String url, Rectangle2D pos) {
  1178. PDFXObject xobject = pdfDoc.getImage(url);
  1179. if (xobject != null) {
  1180. float w = (float) pos.getWidth() / 1000f;
  1181. float h = (float) pos.getHeight() / 1000f;
  1182. placeImage((float)pos.getX() / 1000f,
  1183. (float)pos.getY() / 1000f, w, h, xobject.getXNumber());
  1184. return;
  1185. }
  1186. url = ImageFactory.getURL(url);
  1187. ImageFactory fact = ImageFactory.getInstance();
  1188. FopImage fopimage = fact.getImage(url, userAgent);
  1189. if (fopimage == null) {
  1190. return;
  1191. }
  1192. if (!fopimage.load(FopImage.DIMENSIONS)) {
  1193. return;
  1194. }
  1195. String mime = fopimage.getMimeType();
  1196. if ("text/xml".equals(mime)) {
  1197. if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
  1198. return;
  1199. }
  1200. Document doc = ((XMLImage) fopimage).getDocument();
  1201. String ns = ((XMLImage) fopimage).getNameSpace();
  1202. renderDocument(doc, ns, pos);
  1203. } else if ("image/svg+xml".equals(mime)) {
  1204. if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
  1205. return;
  1206. }
  1207. Document doc = ((XMLImage) fopimage).getDocument();
  1208. String ns = ((XMLImage) fopimage).getNameSpace();
  1209. renderDocument(doc, ns, pos);
  1210. } else if ("image/eps".equals(mime)) {
  1211. FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
  1212. int xobj = pdfDoc.addImage(currentContext, pdfimage).getXNumber();
  1213. fact.releaseImage(url, userAgent);
  1214. } else if ("image/jpeg".equals(mime) || "image/tiff".equals(mime)) {
  1215. FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
  1216. int xobj = pdfDoc.addImage(currentContext, pdfimage).getXNumber();
  1217. fact.releaseImage(url, userAgent);
  1218. float w = (float)pos.getWidth() / 1000f;
  1219. float h = (float)pos.getHeight() / 1000f;
  1220. placeImage((float) pos.getX() / 1000,
  1221. (float) pos.getY() / 1000, w, h, xobj);
  1222. } else {
  1223. if (!fopimage.load(FopImage.BITMAP)) {
  1224. return;
  1225. }
  1226. FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
  1227. int xobj = pdfDoc.addImage(currentContext, pdfimage).getXNumber();
  1228. fact.releaseImage(url, userAgent);
  1229. float w = (float) pos.getWidth() / 1000f;
  1230. float h = (float) pos.getHeight() / 1000f;
  1231. placeImage((float) pos.getX() / 1000f,
  1232. (float) pos.getY() / 1000f, w, h, xobj);
  1233. }
  1234. // output new data
  1235. try {
  1236. this.pdfDoc.output(ostream);
  1237. } catch (IOException ioe) {
  1238. // ioexception will be caught later
  1239. }
  1240. }
  1241. /**
  1242. * Places a previously registered image at a certain place on the page.
  1243. * @param x X coordinate
  1244. * @param y Y coordinate
  1245. * @param w width for image
  1246. * @param h height for image
  1247. * @param xobj object number of the referenced image
  1248. */
  1249. protected void placeImage(float x, float y, float w, float h, int xobj) {
  1250. saveGraphicsState();
  1251. currentStream.add(w + " 0 0 "
  1252. + -h + " "
  1253. + (currentIPPosition / 1000f + x) + " "
  1254. + (currentBPPosition / 1000f + h + y)
  1255. + " cm\n" + "/Im" + xobj + " Do\n");
  1256. restoreGraphicsState();
  1257. }
  1258. /**
  1259. * @see org.apache.fop.render.AbstractRenderer#renderForeignObject(ForeignObject, Rectangle2D)
  1260. */
  1261. public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
  1262. endTextObject();
  1263. Document doc = fo.getDocument();
  1264. String ns = fo.getNameSpace();
  1265. renderDocument(doc, ns, pos);
  1266. }
  1267. /**
  1268. * Renders an XML document (SVG for example).
  1269. * @param doc DOM document representing the XML document
  1270. * @param ns Namespace for the document
  1271. * @param pos Position on the page
  1272. */
  1273. public void renderDocument(Document doc, String ns, Rectangle2D pos) {
  1274. RendererContext context;
  1275. context = new RendererContext(this, MIME_TYPE);
  1276. context.setUserAgent(userAgent);
  1277. context.setProperty(PDFSVGHandler.PDF_DOCUMENT, pdfDoc);
  1278. context.setProperty(PDFSVGHandler.OUTPUT_STREAM, ostream);
  1279. context.setProperty(PDFSVGHandler.PDF_STATE, currentState);
  1280. context.setProperty(PDFSVGHandler.PDF_PAGE, currentPage);
  1281. context.setProperty(PDFSVGHandler.PDF_CONTEXT,
  1282. currentContext == null ? currentPage : currentContext);
  1283. context.setProperty(PDFSVGHandler.PDF_CONTEXT, currentContext);
  1284. context.setProperty(PDFSVGHandler.PDF_STREAM, currentStream);
  1285. context.setProperty(PDFSVGHandler.PDF_XPOS,
  1286. new Integer(currentIPPosition + (int) pos.getX()));
  1287. context.setProperty(PDFSVGHandler.PDF_YPOS,
  1288. new Integer(currentBPPosition + (int) pos.getY()));
  1289. context.setProperty(PDFSVGHandler.PDF_FONT_INFO, fontInfo);
  1290. context.setProperty(PDFSVGHandler.PDF_FONT_NAME, currentFontName);
  1291. context.setProperty(PDFSVGHandler.PDF_FONT_SIZE,
  1292. new Integer(currentFontSize));
  1293. context.setProperty(PDFSVGHandler.PDF_WIDTH,
  1294. new Integer((int) pos.getWidth()));
  1295. context.setProperty(PDFSVGHandler.PDF_HEIGHT,
  1296. new Integer((int) pos.getHeight()));
  1297. renderXML(context, doc, ns);
  1298. }
  1299. /**
  1300. * Render leader area.
  1301. * This renders a leader area which is an area with a rule.
  1302. * @param area the leader area to render
  1303. */
  1304. public void renderLeader(Leader area) {
  1305. renderInlineAreaBackAndBorders(area);
  1306. currentState.push();
  1307. saveGraphicsState();
  1308. int style = area.getRuleStyle();
  1309. boolean alt = false;
  1310. switch(style) {
  1311. case EN_SOLID:
  1312. currentStream.add("[] 0 d\n");
  1313. break;
  1314. case EN_DOTTED:
  1315. currentStream.add("[2] 0 d\n");
  1316. break;
  1317. case EN_DASHED:
  1318. currentStream.add("[6 4] 0 d\n");
  1319. break;
  1320. case EN_DOUBLE:
  1321. case EN_GROOVE:
  1322. case EN_RIDGE:
  1323. alt = true;
  1324. break;
  1325. }
  1326. float startx = (currentIPPosition + area.getBorderAndPaddingWidthStart()) / 1000f;
  1327. float starty = (currentBPPosition + area.getOffset()) / 1000f;
  1328. float endx = (currentIPPosition + area.getBorderAndPaddingWidthStart()
  1329. + area.getIPD()) / 1000f;
  1330. // PDF draws lines centered on the Y coordiante, therefore we need to
  1331. // add half of the line thickness to the Y positions.
  1332. if (!alt) {
  1333. updateLineWidth(area.getRuleThickness() / 1000f);
  1334. drawLine(startx, starty + area.getRuleThickness() / 2000f
  1335. , endx, starty + area.getRuleThickness() / 2000f);
  1336. } else {
  1337. if (style == EN_DOUBLE) {
  1338. float third = area.getRuleThickness() / 3000f;
  1339. updateLineWidth(third);
  1340. drawLine(startx, starty + 0.5f * third, endx, starty + 0.5f * third);
  1341. drawLine(startx, (starty + 2.5f * third), endx, (starty + 2.5f * third));
  1342. } else {
  1343. float half = area.getRuleThickness() / 2000f;
  1344. currentStream.add("1 g\n");
  1345. currentStream.add(startx + " " + starty + " m\n");
  1346. currentStream.add(endx + " " + starty + " l\n");
  1347. currentStream.add(endx + " " + (starty + 2 * half) + " l\n");
  1348. currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
  1349. currentStream.add("h\n");
  1350. currentStream.add("f\n");
  1351. if (style == EN_GROOVE) {
  1352. currentStream.add("0 g\n");
  1353. currentStream.add(startx + " " + starty + " m\n");
  1354. currentStream.add(endx + " " + starty + " l\n");
  1355. currentStream.add(endx + " " + (starty + half) + " l\n");
  1356. currentStream.add((startx + half) + " " + (starty + half) + " l\n");
  1357. currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
  1358. } else {
  1359. currentStream.add("0 g\n");
  1360. currentStream.add(endx + " " + starty + " m\n");
  1361. currentStream.add(endx + " " + (starty + 2 * half) + " l\n");
  1362. currentStream.add(startx + " " + (starty + 2 * half) + " l\n");
  1363. currentStream.add(startx + " " + (starty + half) + " l\n");
  1364. currentStream.add((endx - half) + " " + (starty + half) + " l\n");
  1365. }
  1366. currentStream.add("h\n");
  1367. currentStream.add("f\n");
  1368. }
  1369. }
  1370. restoreGraphicsState();
  1371. currentState.pop();
  1372. beginTextObject();
  1373. super.renderLeader(area);
  1374. }
  1375. /** @see org.apache.fop.render.AbstractRenderer */
  1376. public String getMimeType() {
  1377. return MIME_TYPE;
  1378. }
  1379. }