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.

PDFPainter.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.render.pdf;
  19. import java.awt.Color;
  20. import java.awt.Dimension;
  21. import java.awt.Paint;
  22. import java.awt.Point;
  23. import java.awt.Rectangle;
  24. import java.awt.geom.AffineTransform;
  25. import java.io.IOException;
  26. import org.w3c.dom.Document;
  27. import org.apache.fop.fonts.Font;
  28. import org.apache.fop.fonts.FontInfo;
  29. import org.apache.fop.fonts.FontTriplet;
  30. import org.apache.fop.fonts.LazyFont;
  31. import org.apache.fop.fonts.SingleByteFont;
  32. import org.apache.fop.fonts.Typeface;
  33. import org.apache.fop.pdf.PDFDocument;
  34. import org.apache.fop.pdf.PDFNumber;
  35. import org.apache.fop.pdf.PDFStructElem;
  36. import org.apache.fop.pdf.PDFTextUtil;
  37. import org.apache.fop.pdf.PDFXObject;
  38. import org.apache.fop.render.RenderingContext;
  39. import org.apache.fop.render.intermediate.AbstractIFPainter;
  40. import org.apache.fop.render.intermediate.IFContext;
  41. import org.apache.fop.render.intermediate.IFException;
  42. import org.apache.fop.render.intermediate.IFState;
  43. import org.apache.fop.render.pdf.PDFLogicalStructureHandler.MarkedContentInfo;
  44. import org.apache.fop.traits.BorderProps;
  45. import org.apache.fop.traits.RuleStyle;
  46. import org.apache.fop.util.CharUtilities;
  47. /**
  48. * IFPainter implementation that produces PDF.
  49. */
  50. public class PDFPainter extends AbstractIFPainter {
  51. private final PDFDocumentHandler documentHandler;
  52. /** The current content generator */
  53. protected PDFContentGenerator generator;
  54. private final PDFBorderPainter borderPainter;
  55. private boolean accessEnabled;
  56. private MarkedContentInfo imageMCI;
  57. private PDFLogicalStructureHandler logicalStructureHandler;
  58. /**
  59. * Default constructor.
  60. * @param documentHandler the parent document handler
  61. * @param logicalStructureHandler the logical structure handler
  62. */
  63. public PDFPainter(PDFDocumentHandler documentHandler,
  64. PDFLogicalStructureHandler logicalStructureHandler) {
  65. super();
  66. this.documentHandler = documentHandler;
  67. this.logicalStructureHandler = logicalStructureHandler;
  68. this.generator = documentHandler.generator;
  69. this.borderPainter = new PDFBorderPainter(this.generator);
  70. this.state = IFState.create();
  71. accessEnabled = this.getUserAgent().isAccessibilityEnabled();
  72. }
  73. /** {@inheritDoc} */
  74. @Override
  75. protected IFContext getContext() {
  76. return this.documentHandler.getContext();
  77. }
  78. PDFRenderingUtil getPDFUtil() {
  79. return this.documentHandler.pdfUtil;
  80. }
  81. PDFDocument getPDFDoc() {
  82. return this.documentHandler.pdfDoc;
  83. }
  84. FontInfo getFontInfo() {
  85. return this.documentHandler.getFontInfo();
  86. }
  87. /** {@inheritDoc} */
  88. public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect)
  89. throws IFException {
  90. generator.saveGraphicsState();
  91. generator.concatenate(toPoints(transform));
  92. if (clipRect != null) {
  93. clipRect(clipRect);
  94. }
  95. }
  96. /** {@inheritDoc} */
  97. public void endViewport() throws IFException {
  98. generator.restoreGraphicsState();
  99. }
  100. /** {@inheritDoc} */
  101. public void startGroup(AffineTransform transform) throws IFException {
  102. generator.saveGraphicsState();
  103. generator.concatenate(toPoints(transform));
  104. }
  105. /** {@inheritDoc} */
  106. public void endGroup() throws IFException {
  107. generator.restoreGraphicsState();
  108. }
  109. /** {@inheritDoc} */
  110. public void drawImage(String uri, Rectangle rect)
  111. throws IFException {
  112. PDFXObject xobject = getPDFDoc().getXObject(uri);
  113. if (xobject != null) {
  114. if (accessEnabled) {
  115. PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement();
  116. prepareImageMCID(structElem);
  117. placeImageAccess(rect, xobject);
  118. } else {
  119. placeImage(rect, xobject);
  120. }
  121. } else {
  122. if (accessEnabled) {
  123. PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement();
  124. prepareImageMCID(structElem);
  125. }
  126. drawImageUsingURI(uri, rect);
  127. flushPDFDoc();
  128. }
  129. }
  130. private void prepareImageMCID(PDFStructElem structElem) {
  131. imageMCI = logicalStructureHandler.addImageContentItem(structElem);
  132. }
  133. /** {@inheritDoc} */
  134. @Override
  135. protected RenderingContext createRenderingContext() {
  136. PDFRenderingContext pdfContext = new PDFRenderingContext(
  137. getUserAgent(), generator, this.documentHandler.currentPage, getFontInfo());
  138. pdfContext.setMarkedContentInfo(imageMCI);
  139. return pdfContext;
  140. }
  141. /**
  142. * Places a previously registered image at a certain place on the page.
  143. * @param rect the rectangle for the image
  144. * @param xobj the image XObject
  145. */
  146. private void placeImage(Rectangle rect, PDFXObject xobj) {
  147. generator.saveGraphicsState();
  148. generator.add(format(rect.width) + " 0 0 "
  149. + format(-rect.height) + " "
  150. + format(rect.x) + " "
  151. + format(rect.y + rect.height )
  152. + " cm " + xobj.getName() + " Do\n");
  153. generator.restoreGraphicsState();
  154. }
  155. /**
  156. * Places a previously registered image at a certain place on the page - Accessibility version
  157. * @param rect the rectangle for the image
  158. * @param xobj the image XObject
  159. */
  160. private void placeImageAccess(Rectangle rect, PDFXObject xobj) {
  161. generator.saveGraphicsState(imageMCI.tag, imageMCI.mcid);
  162. generator.add(format(rect.width) + " 0 0 "
  163. + format(-rect.height) + " "
  164. + format(rect.x) + " "
  165. + format(rect.y + rect.height )
  166. + " cm " + xobj.getName() + " Do\n");
  167. generator.restoreGraphicsStateAccess();
  168. }
  169. /** {@inheritDoc} */
  170. public void drawImage(Document doc, Rectangle rect) throws IFException {
  171. if (accessEnabled) {
  172. PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement();
  173. prepareImageMCID(structElem);
  174. }
  175. drawImageUsingDocument(doc, rect);
  176. flushPDFDoc();
  177. }
  178. private void flushPDFDoc() throws IFException {
  179. // output new data
  180. try {
  181. generator.flushPDFDoc();
  182. } catch (IOException ioe) {
  183. throw new IFException("I/O error flushing the PDF document", ioe);
  184. }
  185. }
  186. /**
  187. * Formats a integer value (normally coordinates in millipoints) to a String.
  188. * @param value the value (in millipoints)
  189. * @return the formatted value
  190. */
  191. protected static String format(int value) {
  192. return PDFNumber.doubleOut(value / 1000f);
  193. }
  194. /** {@inheritDoc} */
  195. public void clipRect(Rectangle rect) throws IFException {
  196. generator.endTextObject();
  197. generator.clipRect(rect);
  198. }
  199. /** {@inheritDoc} */
  200. public void fillRect(Rectangle rect, Paint fill) throws IFException {
  201. if (fill == null) {
  202. return;
  203. }
  204. if (rect.width != 0 && rect.height != 0) {
  205. generator.endTextObject();
  206. if (fill != null) {
  207. if (fill instanceof Color) {
  208. generator.updateColor((Color)fill, true, null);
  209. } else {
  210. throw new UnsupportedOperationException("Non-Color paints NYI");
  211. }
  212. }
  213. StringBuffer sb = new StringBuffer();
  214. sb.append(format(rect.x)).append(' ');
  215. sb.append(format(rect.y)).append(' ');
  216. sb.append(format(rect.width)).append(' ');
  217. sb.append(format(rect.height)).append(" re");
  218. if (fill != null) {
  219. sb.append(" f");
  220. }
  221. /* Removed from method signature as it is currently not used
  222. if (stroke != null) {
  223. sb.append(" S");
  224. }*/
  225. sb.append('\n');
  226. generator.add(sb.toString());
  227. }
  228. }
  229. /** {@inheritDoc} */
  230. @Override
  231. public void drawBorderRect(Rectangle rect, BorderProps before, BorderProps after,
  232. BorderProps start, BorderProps end) throws IFException {
  233. if (before != null || after != null || start != null || end != null) {
  234. generator.endTextObject();
  235. try {
  236. this.borderPainter.drawBorders(rect, before, after, start, end);
  237. } catch (IOException ioe) {
  238. throw new IFException("I/O error while drawing borders", ioe);
  239. }
  240. }
  241. }
  242. /** {@inheritDoc} */
  243. @Override
  244. public void drawLine(Point start, Point end, int width, Color color, RuleStyle style)
  245. throws IFException {
  246. generator.endTextObject();
  247. this.borderPainter.drawLine(start, end, width, color, style);
  248. }
  249. private Typeface getTypeface(String fontName) {
  250. if (fontName == null) {
  251. throw new NullPointerException("fontName must not be null");
  252. }
  253. Typeface tf = getFontInfo().getFonts().get(fontName);
  254. if (tf instanceof LazyFont) {
  255. tf = ((LazyFont)tf).getRealFont();
  256. }
  257. return tf;
  258. }
  259. /** {@inheritDoc} */
  260. public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[] dx,
  261. String text)
  262. throws IFException {
  263. if (accessEnabled) {
  264. PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement();
  265. MarkedContentInfo mci = logicalStructureHandler.addTextContentItem(structElem);
  266. if (generator.getTextUtil().isInTextObject()) {
  267. generator.separateTextElements(mci.tag, mci.mcid);
  268. }
  269. generator.updateColor(state.getTextColor(), true, null);
  270. generator.beginTextObject(mci.tag, mci.mcid);
  271. } else {
  272. generator.updateColor(state.getTextColor(), true, null);
  273. generator.beginTextObject();
  274. }
  275. FontTriplet triplet = new FontTriplet(
  276. state.getFontFamily(), state.getFontStyle(), state.getFontWeight());
  277. //TODO Ignored: state.getFontVariant()
  278. //TODO Opportunity for font caching if font state is more heavily used
  279. String fontKey = getFontInfo().getInternalFontKey(triplet);
  280. int sizeMillipoints = state.getFontSize();
  281. float fontSize = sizeMillipoints / 1000f;
  282. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  283. Typeface tf = getTypeface(fontKey);
  284. SingleByteFont singleByteFont = null;
  285. if (tf instanceof SingleByteFont) {
  286. singleByteFont = (SingleByteFont)tf;
  287. }
  288. Font font = getFontInfo().getFontInstance(triplet, sizeMillipoints);
  289. String fontName = font.getFontName();
  290. PDFTextUtil textutil = generator.getTextUtil();
  291. textutil.updateTf(fontKey, fontSize, tf.isMultiByte());
  292. generator.updateCharacterSpacing(letterSpacing / 1000f);
  293. textutil.writeTextMatrix(new AffineTransform(1, 0, 0, -1, x / 1000f, y / 1000f));
  294. int l = text.length();
  295. int dxl = (dx != null ? dx.length : 0);
  296. if (dx != null && dxl > 0 && dx[0] != 0) {
  297. textutil.adjustGlyphTJ(-dx[0] / fontSize);
  298. }
  299. for (int i = 0; i < l; i++) {
  300. char orgChar = text.charAt(i);
  301. char ch;
  302. float glyphAdjust = 0;
  303. if (font.hasChar(orgChar)) {
  304. ch = font.mapChar(orgChar);
  305. ch = selectAndMapSingleByteFont(singleByteFont, fontName, fontSize, textutil, ch);
  306. if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) {
  307. glyphAdjust += wordSpacing;
  308. }
  309. } else {
  310. if (CharUtilities.isFixedWidthSpace(orgChar)) {
  311. //Fixed width space are rendered as spaces so copy/paste works in a reader
  312. ch = font.mapChar(CharUtilities.SPACE);
  313. int spaceDiff = font.getCharWidth(ch) - font.getCharWidth(orgChar);
  314. glyphAdjust = -spaceDiff;
  315. } else {
  316. ch = font.mapChar(orgChar);
  317. if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) {
  318. glyphAdjust += wordSpacing;
  319. }
  320. }
  321. ch = selectAndMapSingleByteFont(singleByteFont, fontName, fontSize,
  322. textutil, ch);
  323. }
  324. textutil.writeTJMappedChar(ch);
  325. if (dx != null && i < dxl - 1) {
  326. glyphAdjust += dx[i + 1];
  327. }
  328. if (glyphAdjust != 0) {
  329. textutil.adjustGlyphTJ(-glyphAdjust / fontSize);
  330. }
  331. }
  332. textutil.writeTJ();
  333. }
  334. private char selectAndMapSingleByteFont(SingleByteFont singleByteFont, String fontName,
  335. float fontSize, PDFTextUtil textutil, char ch) {
  336. if (singleByteFont != null && singleByteFont.hasAdditionalEncodings()) {
  337. int encoding = ch / 256;
  338. if (encoding == 0) {
  339. textutil.updateTf(fontName, fontSize, singleByteFont.isMultiByte());
  340. } else {
  341. textutil.updateTf(fontName + "_" + Integer.toString(encoding),
  342. fontSize, singleByteFont.isMultiByte());
  343. ch = (char)(ch % 256);
  344. }
  345. }
  346. return ch;
  347. }
  348. }