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

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