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

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