Debian Codegraph @

src/main/java/org/jfree/pdf/stream/GraphicsStream.java

raw
1 /* =====================================================================
2 * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform
3 * =====================================================================
4 *
5 * (C)opyright 2013-2022, by David Gilbert. All rights reserved.
6 *
7 * https://github.com/jfree/orsonpdf
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
23 * Other names may be trademarks of their respective owners.]
24 *
25 * If you do not wish to be bound by the terms of the GPL, an alternative
26 * runtime license is available to JFree sponsors:
27 *
28 * https://github.com/sponsors/jfree
29 *
30 */
31
32 package org.jfree.pdf.stream;
33
34 import java.awt.AlphaComposite;
35 import java.awt.BasicStroke;
36 import java.awt.Color;
37 import java.awt.Font;
38 import java.awt.GradientPaint;
39 import java.awt.Image;
40 import java.awt.RadialGradientPaint;
41 import java.awt.Shape;
42 import java.awt.Stroke;
43 import java.awt.geom.AffineTransform;
44 import java.awt.geom.Line2D;
45 import java.awt.geom.NoninvertibleTransformException;
46 import java.awt.geom.Path2D;
47 import java.awt.geom.PathIterator;
48 import java.io.ByteArrayOutputStream;
49 import java.io.IOException;
50 import java.text.DecimalFormat;
51 import java.text.DecimalFormatSymbols;
52 import org.jfree.pdf.PDFGraphics2D;
53 import org.jfree.pdf.Page;
54 import org.jfree.pdf.util.Args;
55 import org.jfree.pdf.util.PDFUtils;
56
57 /**
58 * A {@code Stream} that contains graphics for the PDF document that
59 * can be generated via the {@link PDFGraphics2D} class. The {@link Page}
60 * class will create a {@code GraphicsStream} instance to represent its
61 * content. You won't normally interact directly with this class, it is
62 * intended that the {@code PDFGraphics2D} class drives the calls to the
63 * methods of this class.
64 */
65 public class GraphicsStream extends Stream {
66
67 /**
68 * The page the graphics stream belongs to. We need this reference to
69 * our "parent" so that we can access fonts in the document.
70 */
71 private Page page;
72
73 /** The stream content. */
74 private ByteArrayOutputStream content;
75
76 /** The most recent font applied. */
77 private Font font;
78
79 /** The most recent alpha transparency value (in the range 0 to 255). */
80 private int alpha;
81
82 private AffineTransform prevTransInv;
83
84 /**
85 * The decimal formatter for coordinates of geometrical shapes.
86 */
87 private DecimalFormat geometryFormat;
88
89 /**
90 * The decimal formatter for transform matrices.
91 */
92 private DecimalFormat transformFormat;
93
94 /**
95 * Creates a new instance.
96 *
97 * @param number the PDF object number.
98 * @param page the parent page ({@code null} not permitted).
99 */
100 public GraphicsStream(int number, Page page) {
101 super(number);
102 this.page = page;
103 this.content = new ByteArrayOutputStream();
104 this.font = new Font("Dialog", Font.PLAIN, 12);
105 this.alpha = 255;
106 // force the formatters to use a '.' for the decimal point
107 DecimalFormatSymbols dfs = new DecimalFormatSymbols();
108 dfs.setDecimalSeparator('.');
109 this.geometryFormat = new DecimalFormat("0.##", dfs);
110 this.transformFormat = new DecimalFormat("0.######", dfs);
111 }
112
113 private void addContent(String s) {
114 try {
115 this.content.write(PDFUtils.toBytes(s));
116 } catch (IOException e) {
117 throw new RuntimeException(e);
118 }
119 }
120
121 /**
122 * Pushes the current graphics state onto a stack for later retrieval.
123 */
124 public void pushGraphicsState() {
125 addContent("q\n");
126 }
127
128 /**
129 * Pops the graphics state that was previously pushed onto the stack.
130 */
131 public void popGraphicsState() {
132 addContent("Q\n");
133 }
134
135 /**
136 * Applies a graphics transform.
137 *
138 * @param t the transform ({@code null} not permitted).
139 */
140 public void applyTransform(AffineTransform t) {
141 StringBuilder b = new StringBuilder();
142 b.append(transformDP(t.getScaleX())).append(" ");
143 b.append(transformDP(t.getShearY())).append(" ");
144 b.append(transformDP(t.getShearX())).append(" ");
145 b.append(transformDP(t.getScaleY())).append(" ");
146 b.append(transformDP(t.getTranslateX())).append(" ");
147 b.append(transformDP(t.getTranslateY())).append(" cm\n");
148 addContent(b.toString());
149 }
150
151 /**
152 * Sets the transform.
153 *
154 * @param t the transform ({@code null} not permitted).
155 */
156 public void setTransform(AffineTransform t) {
157 AffineTransform tt = new AffineTransform(t);
158 try {
159 AffineTransform inv = tt.createInverse();
160 AffineTransform comb;
161 if (this.prevTransInv != null) {
162 comb = new AffineTransform(this.prevTransInv);
163 comb.concatenate(tt);
164 } else {
165 comb = tt;
166 }
167 this.prevTransInv = inv;
168 applyTransform(comb);
169 } catch (NoninvertibleTransformException e) {
170 // do nothing
171 }
172 }
173
174 /**
175 * Applies a text transform.
176 *
177 * @param t the transform ({@code null} not permitted).
178 */
179 private void applyTextTransform(AffineTransform t) {
180 StringBuilder b = new StringBuilder();
181 b.append(t.getScaleX()).append(" ");
182 b.append(t.getShearY()).append(" ");
183 b.append(t.getShearX()).append(" ");
184 b.append(t.getScaleY()).append(" ");
185 b.append(t.getTranslateX()).append(" ");
186 b.append(t.getTranslateY()).append(" Tm\n");
187 addContent(b.toString());
188 }
189
190 /**
191 * Applies the specified clip to the current clip.
192 *
193 * @param clip the clip ({@code null} not permitted).
194 */
195 public void applyClip(Shape clip) {
196 Args.nullNotPermitted(clip, "clip");
197 StringBuilder b = new StringBuilder();
198 Path2D p = new Path2D.Double(clip);
199 b.append(getPDFPath(p));
200 b.append("W n\n");
201 addContent(b.toString());
202 }
203
204 /**
205 * Applies a stroke. If the stroke is not an instance of
206 * {@code BasicStroke} this method will do nothing.
207 *
208 * @param s the stroke.
209 */
210 public void applyStroke(Stroke s) {
211 if (!(s instanceof BasicStroke)) {
212 return;
213 }
214 BasicStroke bs = (BasicStroke) s;
215 StringBuilder b = new StringBuilder();
216 b.append(bs.getLineWidth()).append(" ").append("w\n");
217 b.append(bs.getEndCap()).append(" J\n");
218 b.append(bs.getLineJoin()).append(" j\n");
219 float[] dashArray = bs.getDashArray();
220 if (dashArray != null) {
221 b.append(PDFUtils.toPDFArray(dashArray)).append(" 0 d\n");
222 } else {
223 b.append("[] 0 d\n");
224 }
225 addContent(b.toString());
226 }
227
228 /**
229 * Applies a color for stroking.
230 *
231 * @param c the color ({@code null} not permitted).
232 */
233 public void applyStrokeColor(Color c) {
234 float red = c.getRed() / 255f;
235 float green = c.getGreen() / 255f;
236 float blue = c.getBlue() / 255f;
237 StringBuilder b = new StringBuilder();
238 b.append(red).append(" ").append(green).append(" ").append(blue)
239 .append(" RG\n");
240 addContent(b.toString());
241 applyAlpha(c.getAlpha());
242 }
243
244 /**
245 * Applies a color for filling.
246 *
247 * @param c the color ({@code null} not permitted).
248 */
249 public void applyFillColor(Color c) {
250 float red = c.getRed() / 255f;
251 float green = c.getGreen() / 255f;
252 float blue = c.getBlue() / 255f;
253 StringBuilder b = new StringBuilder();
254 b.append(red).append(" ").append(green).append(" ").append(blue)
255 .append(" rg\n");
256 addContent(b.toString());
257 applyAlpha(c.getAlpha());
258 }
259
260 /**
261 * Applies a {@code GradientPaint} for stroking.
262 *
263 * @param gp the gradient paint ({@code null} not permitted).
264 */
265 public void applyStrokeGradient(GradientPaint gp) {
266 // delegate arg checking
267 String patternName = this.page.findOrCreatePattern(gp);
268 StringBuilder b = new StringBuilder("/Pattern CS\n");
269 b.append(patternName).append(" SCN\n");
270 addContent(b.toString());
271 }
272
273 /**
274 * Applies a {@code RadialGradientPaint} for stroking.
275 *
276 * @param rgp the gradient paint ({@code null} not permitted).
277 */
278 public void applyStrokeGradient(RadialGradientPaint rgp) {
279 // delegate arg checking
280 String patternName = this.page.findOrCreatePattern(rgp);
281 StringBuilder b = new StringBuilder("/Pattern CS\n");
282 b.append(patternName).append(" SCN\n");
283 addContent(b.toString());
284 }
285
286 /**
287 * Applies a {@code GradientPaint} for filling.
288 *
289 * @param gp the gradient paint ({@code null} not permitted).
290 */
291 public void applyFillGradient(GradientPaint gp) {
292 // delegate arg checking
293 String patternName = this.page.findOrCreatePattern(gp);
294 StringBuilder b = new StringBuilder("/Pattern cs\n");
295 b.append(patternName).append(" scn\n");
296 addContent(b.toString());
297 }
298
299 /**
300 * Applies a {@code RadialGradientPaint} for filling.
301 *
302 * @param rgp the gradient paint ({@code null} not permitted).
303 */
304 public void applyFillGradient(RadialGradientPaint rgp) {
305 // delegate arg checking
306 String patternName = this.page.findOrCreatePattern(rgp);
307 StringBuilder b = new StringBuilder("/Pattern cs\n");
308 b.append(patternName).append(" scn\n");
309 addContent(b.toString());
310 }
311
312 private float alphaFactor = 1.0f;
313
314 /**
315 * Applies the specified alpha composite.
316 *
317 * @param alphaComp the alpha composite ({@code null} permitted).
318 */
319 public void applyComposite(AlphaComposite alphaComp) {
320 if (alphaComp == null) {
321 this.alphaFactor = 1.0f;
322 } else {
323 this.alphaFactor = alphaComp.getAlpha();
324 int a = (int) (alphaComp.getAlpha() * 255f);
325 if (this.alpha != a) {
326 String name = this.page.findOrCreateGSDictionary(a);
327 StringBuilder b = new StringBuilder();
328 b.append(name).append(" gs\n");
329 addContent(b.toString());
330 this.alpha = a;
331 }
332 }
333 }
334
335 /**
336 * Applies the alpha transparency.
337 *
338 * @param alpha the new alpha value (in the range {@code 0}
339 * to {@code 255}).
340 */
341 private void applyAlpha(int alpha) {
342 int a = (int) (alpha * this.alphaFactor);
343 if (this.alpha != a) {
344 String name = this.page.findOrCreateGSDictionary(a);
345 StringBuilder b = new StringBuilder();
346 b.append(name).append(" gs\n");
347 addContent(b.toString());
348 this.alpha = a;
349 }
350 }
351
352 private String geomDP(double d) {
353 if (this.geometryFormat != null) {
354 return geometryFormat.format(d);
355 } else {
356 return String.valueOf(d);
357 }
358 }
359
360 private String transformDP(double d) {
361 if (this.transformFormat != null) {
362 return transformFormat.format(d);
363 } else {
364 return String.valueOf(d);
365 }
366 }
367
368 /**
369 * Draws the specified line.
370 *
371 * @param line the line ({@code null} not permitted).
372 */
373 public void drawLine(Line2D line) {
374 StringBuilder b = new StringBuilder();
375 b.append(geomDP(line.getX1())).append(" ").append(geomDP(line.getY1()))
376 .append(" ").append("m\n");
377 b.append(geomDP(line.getX2())).append(" ").append(geomDP(line.getY2()))
378 .append(" ").append("l\n");
379 b.append("S\n");
380 addContent(b.toString());
381 }
382
383 /**
384 * Draws the specified path.
385 *
386 * @param path the path ({@code null} not permitted).
387 */
388 public void drawPath2D(Path2D path) {
389 StringBuilder b = new StringBuilder();
390 b.append(getPDFPath(path)).append("S\n");
391 addContent(b.toString());
392 }
393
394 /**
395 * Fills the specified path.
396 *
397 * @param path the path ({@code null} not permitted).
398 */
399 public void fillPath2D(Path2D path) {
400 StringBuilder b = new StringBuilder();
401 b.append(getPDFPath(path)).append("f\n");
402 addContent(b.toString());
403 }
404
405 /**
406 * Applies the specified font (in fact, no change is made to the stream
407 * until the next call
408 * to {@link #drawString(java.lang.String, float, float)}).
409 *
410 * @param font the font.
411 */
412 public void applyFont(Font font) {
413 this.font = font;
414 }
415
416 /**
417 * Draws a string at the specified location.
418 *
419 * @param text the text.
420 * @param x the x-coordinate.
421 * @param y the y-coordinate.
422 */
423 public void drawString(String text, float x, float y) {
424 // we need to get the reference for the current font (creating a
425 // new font object if there isn't already one)
426 String fontRef = this.page.findOrCreateFontReference(this.font);
427 addContent("BT ");
428 AffineTransform t = new AffineTransform(1.0, 0.0, 0.0, -1.0, 0.0,
429 y * 2);
430 applyTextTransform(t);
431 StringBuilder b = new StringBuilder();
432 b.append(fontRef).append(" ").append(this.font.getSize())
433 .append(" Tf ");
434 b.append(geomDP(x)).append(" ").append(geomDP(y)).append(" Td (")
435 .append(text).append(") Tj ET\n");
436 addContent(b.toString());
437 }
438
439 /**
440 * Draws the specified image into the rectangle {@code (x, y, w, h)}.
441 *
442 * @param img the image.
443 * @param x the x-coordinate of the destination.
444 * @param y the y-coordinate of the destination.
445 * @param w the width of the destination.
446 * @param h the height of the destination.
447 */
448 public void drawImage(Image img, int x, int y, int w, int h) {
449 String imageRef = this.page.addImage(img, true);
450 StringBuilder b = new StringBuilder();
451 b.append("q\n");
452 b.append(geomDP(w)).append(" 0 0 ").append(geomDP(h)).append(" ");
453 b.append(geomDP(x)).append(" ").append(geomDP(y)).append(" cm\n");
454 b.append(imageRef).append(" Do\n");
455 b.append("Q\n");
456 addContent(b.toString());
457 }
458
459 /**
460 * A utility method to convert a {@code Path2D} instance to a PDF
461 * path string.
462 *
463 * @param path the path ({@code null} not permitted).
464 *
465 * @return The string.
466 */
467 private String getPDFPath(Path2D path) {
468 StringBuilder b = new StringBuilder();
469 float[] coords = new float[6];
470 float lastX = 0;
471 float lastY = 0;
472 PathIterator iterator = path.getPathIterator(null);
473 while (!iterator.isDone()) {
474 int type = iterator.currentSegment(coords);
475 switch (type) {
476 case (PathIterator.SEG_MOVETO):
477 b.append(geomDP(coords[0])).append(" ");
478 b.append(geomDP(coords[1])).append(" m\n");
479 lastX = coords[0];
480 lastY = coords[1];
481 break;
482 case (PathIterator.SEG_LINETO):
483 b.append(geomDP(coords[0])).append(" ");
484 b.append(geomDP(coords[1])).append(" l\n");
485 lastX = coords[0];
486 lastY = coords[1];
487 break;
488 case (PathIterator.SEG_QUADTO):
489 // PDF doesn't support quadratic Bézier curves; it only supports
490 // cubic Bézier curves, so we need to perform "degree elevation"
491 // to convert the quadratic Bézier curve into a cubic Bézier
492 // curve. This is the only way to preserve the original curve's
493 // shape accurately for all arbitrary cases.
494 //
495 // https://pages.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-elev.html
496 //
497 // https://en.wikipedia.org/wiki/Bézier_curve#Degree_elevation
498 //
499 // A quadratic curve has degree 2; a cubic curve has degree 3.
500 //
501 // The code is simplified to improve performance and accuracy
502 final float x0 = ( lastX + ( 2f * coords[0] ) ) / 3f;
503 final float y0 = ( lastY + ( 2f * coords[1] ) ) / 3f;
504 final float x1 = ( ( 2f * coords[0] ) + coords[2] ) / 3f;
505 final float y1 = ( ( 2f * coords[1] ) + coords[3] ) / 3f;
506 b.append(geomDP(x0)).append(" ");
507 b.append(geomDP(y0)).append(" ");
508 b.append(geomDP(x1)).append(" ");
509 b.append(geomDP(y1)).append(" ");
510 b.append(geomDP(coords[2])).append(" ");
511 b.append(geomDP(coords[3])).append(" c\n");
512 lastX = coords[2];
513 lastY = coords[3];
514 break;
515 case (PathIterator.SEG_CUBICTO):
516 b.append(geomDP(coords[0])).append(" ");
517 b.append(geomDP(coords[1])).append(" ");
518 b.append(geomDP(coords[2])).append(" ");
519 b.append(geomDP(coords[3])).append(" ");
520 b.append(geomDP(coords[4])).append(" ");
521 b.append(geomDP(coords[5])).append(" c\n");
522 lastX = coords[4];
523 lastY = coords[5];
524 break;
525 case (PathIterator.SEG_CLOSE):
526 b.append("h\n");
527 break;
528 default:
529 break;
530 }
531 iterator.next();
532 }
533 return b.toString();
534 }
535
536 @Override
537 public byte[] getRawStreamData() {
538 return this.content.toByteArray();
539 }
540
541 }