Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

PDFPainter.java 19KB

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