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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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.FontTriplet;
  29. import org.apache.fop.fonts.LazyFont;
  30. import org.apache.fop.fonts.SingleByteFont;
  31. import org.apache.fop.fonts.Typeface;
  32. import org.apache.fop.pdf.PDFNumber;
  33. import org.apache.fop.pdf.PDFStructElem;
  34. import org.apache.fop.pdf.PDFTextUtil;
  35. import org.apache.fop.pdf.PDFXObject;
  36. import org.apache.fop.render.RenderingContext;
  37. import org.apache.fop.render.intermediate.AbstractIFPainter;
  38. import org.apache.fop.render.intermediate.BorderPainter;
  39. import org.apache.fop.render.intermediate.GraphicsPainter;
  40. import org.apache.fop.render.intermediate.IFException;
  41. import org.apache.fop.render.intermediate.IFState;
  42. import org.apache.fop.render.intermediate.IFUtil;
  43. import org.apache.fop.render.pdf.PDFLogicalStructureHandler.MarkedContentInfo;
  44. import org.apache.fop.traits.BorderProps;
  45. import org.apache.fop.traits.Direction;
  46. import org.apache.fop.traits.RuleStyle;
  47. import org.apache.fop.util.CharUtilities;
  48. /**
  49. * IFPainter implementation that produces PDF.
  50. */
  51. public class PDFPainter extends AbstractIFPainter<PDFDocumentHandler> {
  52. /** The current content generator */
  53. protected PDFContentGenerator generator;
  54. private final GraphicsPainter graphicsPainter;
  55. private final BorderPainter borderPainter;
  56. private boolean accessEnabled;
  57. private MarkedContentInfo imageMCI;
  58. private PDFLogicalStructureHandler logicalStructureHandler;
  59. /**
  60. * Default constructor.
  61. * @param documentHandler the parent document handler
  62. * @param logicalStructureHandler the logical structure handler
  63. */
  64. public PDFPainter(PDFDocumentHandler documentHandler,
  65. PDFLogicalStructureHandler logicalStructureHandler) {
  66. super(documentHandler);
  67. this.logicalStructureHandler = logicalStructureHandler;
  68. this.generator = documentHandler.getGenerator();
  69. this.graphicsPainter = new PDFGraphicsPainter(this.generator);
  70. this.borderPainter = new BorderPainter(this.graphicsPainter);
  71. this.state = IFState.create();
  72. accessEnabled = this.getUserAgent().isAccessibilityEnabled();
  73. }
  74. /** {@inheritDoc} */
  75. public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect)
  76. throws IFException {
  77. generator.saveGraphicsState();
  78. generator.concatenate(toPoints(transform));
  79. if (clipRect != null) {
  80. clipRect(clipRect);
  81. }
  82. }
  83. /** {@inheritDoc} */
  84. public void endViewport() throws IFException {
  85. generator.restoreGraphicsState();
  86. }
  87. /** {@inheritDoc} */
  88. public void startGroup(AffineTransform transform) throws IFException {
  89. generator.saveGraphicsState();
  90. generator.concatenate(toPoints(transform));
  91. }
  92. /** {@inheritDoc} */
  93. public void endGroup() throws IFException {
  94. generator.restoreGraphicsState();
  95. }
  96. /** {@inheritDoc} */
  97. public void drawImage(String uri, Rectangle rect)
  98. throws IFException {
  99. PDFXObject xobject = getDocumentHandler().getPDFDocument().getXObject(uri);
  100. if (xobject != null) {
  101. if (accessEnabled) {
  102. PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement();
  103. prepareImageMCID(structElem);
  104. placeImageAccess(rect, xobject);
  105. } else {
  106. placeImage(rect, xobject);
  107. }
  108. } else {
  109. if (accessEnabled) {
  110. PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement();
  111. prepareImageMCID(structElem);
  112. }
  113. drawImageUsingURI(uri, rect);
  114. flushPDFDoc();
  115. }
  116. }
  117. private void prepareImageMCID(PDFStructElem structElem) {
  118. imageMCI = logicalStructureHandler.addImageContentItem(structElem);
  119. }
  120. /** {@inheritDoc} */
  121. @Override
  122. protected RenderingContext createRenderingContext() {
  123. PDFRenderingContext pdfContext = new PDFRenderingContext(
  124. getUserAgent(), generator, getDocumentHandler().getCurrentPage(), getFontInfo());
  125. pdfContext.setMarkedContentInfo(imageMCI);
  126. return pdfContext;
  127. }
  128. /**
  129. * Places a previously registered image at a certain place on the page.
  130. * @param rect the rectangle for the image
  131. * @param xobj the image XObject
  132. */
  133. private void placeImage(Rectangle rect, PDFXObject xobj) {
  134. generator.saveGraphicsState();
  135. generator.add(format(rect.width) + " 0 0 "
  136. + format(-rect.height) + " "
  137. + format(rect.x) + " "
  138. + format(rect.y + rect.height )
  139. + " cm " + xobj.getName() + " Do\n");
  140. generator.restoreGraphicsState();
  141. }
  142. /**
  143. * Places a previously registered image at a certain place on the page - Accessibility version
  144. * @param rect the rectangle for the image
  145. * @param xobj the image XObject
  146. */
  147. private void placeImageAccess(Rectangle rect, PDFXObject xobj) {
  148. generator.saveGraphicsState(imageMCI.tag, imageMCI.mcid);
  149. generator.add(format(rect.width) + " 0 0 "
  150. + format(-rect.height) + " "
  151. + format(rect.x) + " "
  152. + format(rect.y + rect.height )
  153. + " cm " + xobj.getName() + " Do\n");
  154. generator.restoreGraphicsStateAccess();
  155. }
  156. /** {@inheritDoc} */
  157. public void drawImage(Document doc, Rectangle rect) throws IFException {
  158. if (accessEnabled) {
  159. PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement();
  160. prepareImageMCID(structElem);
  161. }
  162. drawImageUsingDocument(doc, rect);
  163. flushPDFDoc();
  164. }
  165. private void flushPDFDoc() throws IFException {
  166. // output new data
  167. try {
  168. generator.flushPDFDoc();
  169. } catch (IOException ioe) {
  170. throw new IFException("I/O error flushing the PDF document", ioe);
  171. }
  172. }
  173. /**
  174. * Formats a integer value (normally coordinates in millipoints) to a String.
  175. * @param value the value (in millipoints)
  176. * @return the formatted value
  177. */
  178. protected static String format(int value) {
  179. return PDFNumber.doubleOut(value / 1000f);
  180. }
  181. /** {@inheritDoc} */
  182. public void clipRect(Rectangle rect) throws IFException {
  183. generator.endTextObject();
  184. generator.clipRect(rect);
  185. }
  186. /** {@inheritDoc} */
  187. public void clipBackground(Rectangle rect,
  188. BorderProps bpsBefore, BorderProps bpsAfter,
  189. BorderProps bpsStart, BorderProps bpsEnd) throws IFException {
  190. try {
  191. borderPainter.clipBackground(rect,
  192. bpsBefore, bpsAfter, bpsStart, bpsEnd);
  193. } catch (IOException ioe) {
  194. throw new IFException("I/O error while clipping background", ioe);
  195. }
  196. }
  197. /** {@inheritDoc} */
  198. public void fillRect(Rectangle rect, Paint fill) throws IFException {
  199. if (fill == null) {
  200. return;
  201. }
  202. if (rect.width != 0 && rect.height != 0) {
  203. generator.endTextObject();
  204. if (fill != null) {
  205. if (fill instanceof Color) {
  206. generator.updateColor((Color)fill, true, null);
  207. } else {
  208. throw new UnsupportedOperationException("Non-Color paints NYI");
  209. }
  210. }
  211. StringBuffer sb = new StringBuffer();
  212. sb.append(format(rect.x)).append(' ');
  213. sb.append(format(rect.y)).append(' ');
  214. sb.append(format(rect.width)).append(' ');
  215. sb.append(format(rect.height)).append(" re");
  216. if (fill != null) {
  217. sb.append(" f");
  218. }
  219. /* Removed from method signature as it is currently not used
  220. if (stroke != null) {
  221. sb.append(" S");
  222. }*/
  223. sb.append('\n');
  224. generator.add(sb.toString());
  225. }
  226. }
  227. /** {@inheritDoc} */
  228. @Override
  229. public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom,
  230. BorderProps left, BorderProps right, Color innerBackgroundColor) throws IFException {
  231. if (top != null || bottom != null || left != null || right != null) {
  232. generator.endTextObject();
  233. this.borderPainter.drawBorders(rect, top, bottom, left, right, innerBackgroundColor);
  234. }
  235. }
  236. /** {@inheritDoc} */
  237. @Override
  238. public void drawLine(Point start, Point end, int width, Color color, RuleStyle style)
  239. throws IFException {
  240. generator.endTextObject();
  241. try {
  242. this.graphicsPainter.drawLine(start, end, width, color, style);
  243. } catch (IOException ioe) {
  244. throw new IFException("Cannot draw line", ioe);
  245. }
  246. }
  247. private Typeface getTypeface(String fontName) {
  248. if (fontName == null) {
  249. throw new NullPointerException("fontName must not be null");
  250. }
  251. Typeface tf = getFontInfo().getFonts().get(fontName);
  252. if (tf instanceof LazyFont) {
  253. tf = ((LazyFont)tf).getRealFont();
  254. }
  255. return tf;
  256. }
  257. /** {@inheritDoc} */
  258. public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp,
  259. String text)
  260. throws IFException {
  261. if (accessEnabled) {
  262. PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement();
  263. MarkedContentInfo mci = logicalStructureHandler.addTextContentItem(structElem);
  264. if (generator.getTextUtil().isInTextObject()) {
  265. generator.separateTextElements(mci.tag, mci.mcid);
  266. }
  267. generator.updateColor(state.getTextColor(), true, null);
  268. generator.beginTextObject(mci.tag, mci.mcid);
  269. } else {
  270. generator.updateColor(state.getTextColor(), true, null);
  271. generator.beginTextObject();
  272. }
  273. FontTriplet triplet = new FontTriplet(
  274. state.getFontFamily(), state.getFontStyle(), state.getFontWeight());
  275. if ( ( dp == null ) || IFUtil.isDPOnlyDX ( dp ) ) {
  276. drawTextWithDX ( x, y, text, triplet, letterSpacing,
  277. wordSpacing, IFUtil.convertDPToDX ( dp ) );
  278. } else {
  279. drawTextWithDP ( x, y, text, triplet, letterSpacing,
  280. wordSpacing, dp );
  281. }
  282. }
  283. private void drawTextWithDX(int x, int y, String text, FontTriplet triplet,
  284. int letterSpacing, int wordSpacing, int[] dx) throws IFException {
  285. //TODO Ignored: state.getFontVariant()
  286. //TODO Opportunity for font caching if font state is more heavily used
  287. String fontKey = getFontKey(triplet);
  288. int sizeMillipoints = state.getFontSize();
  289. float fontSize = sizeMillipoints / 1000f;
  290. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  291. Typeface tf = getTypeface(fontKey);
  292. SingleByteFont singleByteFont = null;
  293. if (tf instanceof SingleByteFont) {
  294. singleByteFont = (SingleByteFont)tf;
  295. }
  296. Font font = getFontInfo().getFontInstance(triplet, sizeMillipoints);
  297. String fontName = font.getFontName();
  298. PDFTextUtil textutil = generator.getTextUtil();
  299. textutil.updateTf(fontKey, fontSize, tf.isMultiByte());
  300. generator.updateCharacterSpacing(letterSpacing / 1000f);
  301. textutil.writeTextMatrix(new AffineTransform(1, 0, 0, -1, x / 1000f, y / 1000f));
  302. int l = text.length();
  303. int dxl = (dx != null ? dx.length : 0);
  304. if (dx != null && dxl > 0 && dx[0] != 0) {
  305. textutil.adjustGlyphTJ(-dx[0] / fontSize);
  306. }
  307. for (int i = 0; i < l; i++) {
  308. char orgChar = text.charAt(i);
  309. char ch;
  310. float glyphAdjust = 0;
  311. if (font.hasChar(orgChar)) {
  312. ch = font.mapChar(orgChar);
  313. ch = selectAndMapSingleByteFont(singleByteFont, fontName, fontSize, textutil, ch);
  314. if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) {
  315. glyphAdjust += wordSpacing;
  316. }
  317. } else {
  318. if (CharUtilities.isFixedWidthSpace(orgChar)) {
  319. //Fixed width space are rendered as spaces so copy/paste works in a reader
  320. ch = font.mapChar(CharUtilities.SPACE);
  321. int spaceDiff = font.getCharWidth(ch) - font.getCharWidth(orgChar);
  322. glyphAdjust = -spaceDiff;
  323. } else {
  324. ch = font.mapChar(orgChar);
  325. if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) {
  326. glyphAdjust += wordSpacing;
  327. }
  328. }
  329. ch = selectAndMapSingleByteFont(singleByteFont, fontName, fontSize,
  330. textutil, ch);
  331. }
  332. textutil.writeTJMappedChar(ch);
  333. if (dx != null && i < dxl - 1) {
  334. glyphAdjust += dx[i + 1];
  335. }
  336. if (glyphAdjust != 0) {
  337. textutil.adjustGlyphTJ(-glyphAdjust / fontSize);
  338. }
  339. }
  340. textutil.writeTJ();
  341. }
  342. private static int[] paZero = new int[4];
  343. private void drawTextWithDP ( int x, int y, String text, FontTriplet triplet,
  344. int letterSpacing, int wordSpacing, int[][] dp ) {
  345. assert text != null;
  346. assert triplet != null;
  347. assert dp != null;
  348. String fk = getFontInfo().getInternalFontKey(triplet);
  349. Typeface tf = getTypeface(fk);
  350. if ( tf.isMultiByte() ) {
  351. int fs = state.getFontSize();
  352. float fsPoints = fs / 1000f;
  353. Font f = getFontInfo().getFontInstance(triplet, fs);
  354. // String fn = f.getFontName();
  355. PDFTextUtil tu = generator.getTextUtil();
  356. double xc = 0f;
  357. double yc = 0f;
  358. double xoLast = 0f;
  359. double yoLast = 0f;
  360. double wox = wordSpacing;
  361. tu.writeTextMatrix ( new AffineTransform ( 1, 0, 0, -1, x / 1000f, y / 1000f ) );
  362. tu.updateTf ( fk, fsPoints, true );
  363. generator.updateCharacterSpacing ( letterSpacing / 1000f );
  364. for ( int i = 0, n = text.length(); i < n; i++ ) {
  365. char ch = text.charAt ( i );
  366. int[] pa = ( i < dp.length ) ? dp [ i ] : paZero;
  367. double xo = xc + pa[0];
  368. double yo = yc + pa[1];
  369. double xa = f.getCharWidth(ch) + maybeWordOffsetX ( wox, ch, null );
  370. double ya = 0;
  371. double xd = ( xo - xoLast ) / 1000f;
  372. double yd = ( yo - yoLast ) / 1000f;
  373. tu.writeTd ( xd, yd );
  374. tu.writeTj ( f.mapChar ( ch ) );
  375. xc += xa + pa[2];
  376. yc += ya + pa[3];
  377. xoLast = xo;
  378. yoLast = yo;
  379. }
  380. }
  381. }
  382. private double maybeWordOffsetX ( double wox, char ch, Direction dir ) {
  383. if ( ( wox != 0 )
  384. && CharUtilities.isAdjustableSpace ( ch )
  385. && ( ( dir == null ) || dir.isHorizontal() ) ) {
  386. return wox;
  387. } else {
  388. return 0;
  389. }
  390. }
  391. /*
  392. private double maybeWordOffsetY ( double woy, char ch, Direction dir ) {
  393. if ( ( woy != 0 )
  394. && CharUtilities.isAdjustableSpace ( ch ) && dir.isVertical()
  395. && ( ( dir != null ) && dir.isVertical() ) ) {
  396. return woy;
  397. } else {
  398. return 0;
  399. }
  400. }
  401. */
  402. private char selectAndMapSingleByteFont(SingleByteFont singleByteFont, String fontName,
  403. float fontSize, PDFTextUtil textutil, char ch) {
  404. if (singleByteFont != null && singleByteFont.hasAdditionalEncodings()) {
  405. int encoding = ch / 256;
  406. if (encoding == 0) {
  407. textutil.updateTf(fontName, fontSize, singleByteFont.isMultiByte());
  408. } else {
  409. textutil.updateTf(fontName + "_" + Integer.toString(encoding),
  410. fontSize, singleByteFont.isMultiByte());
  411. ch = (char)(ch % 256);
  412. }
  413. }
  414. return ch;
  415. }
  416. }