Debian Codegraph @

freehep-graphicsio-pdf/src/main/java/org/freehep/graphicsio/pdf/PDFGraphics2D.java

raw
1 // Copyright 2000-2007, FreeHEP
2 package org.freehep.graphicsio.pdf;
3
4 import java.awt.BasicStroke;
5 import java.awt.Color;
6 import java.awt.Component;
7 import java.awt.Dimension;
8 import java.awt.Font;
9 import java.awt.GradientPaint;
10 import java.awt.Graphics;
11 import java.awt.GraphicsConfiguration;
12 import java.awt.Insets;
13 import java.awt.Paint;
14 import java.awt.Rectangle;
15 import java.awt.Shape;
16 import java.awt.Stroke;
17 import java.awt.TexturePaint;
18 import java.awt.font.LineMetrics;
19 import java.awt.geom.AffineTransform;
20 import java.awt.geom.Rectangle2D;
21 import java.awt.image.BufferedImage;
22 import java.awt.image.RenderedImage;
23 import java.io.BufferedOutputStream;
24 import java.io.File;
25 import java.io.FileNotFoundException;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.OutputStream;
29 import java.util.ArrayList;
30 import java.util.Calendar;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Properties;
36
37 import org.freehep.graphics2d.TagString;
38 import org.freehep.graphics2d.font.FontUtilities;
39 import org.freehep.graphics2d.font.Lookup;
40 import org.freehep.graphicsbase.util.UserProperties;
41 import org.freehep.graphicsio.AbstractVectorGraphicsIO;
42 import org.freehep.graphicsio.FontConstants;
43 import org.freehep.graphicsio.ImageConstants;
44 import org.freehep.graphicsio.ImageGraphics2D;
45 import org.freehep.graphicsio.InfoConstants;
46 import org.freehep.graphicsio.MultiPageDocument;
47 import org.freehep.graphicsio.PageConstants;
48
49 /**
50 * Implementation of <tt>VectorGraphics</tt> that writes the output to a PDF
51 * file. Users of this class have to generate a <tt>PDFWriter</tt> and create
52 * an instance by invoking the factory method or the constructor. Document
53 * specific settings like page size can then be made by the appropriate setter
54 * methods. Before starting to draw, <tt>startExport()</tt> must be called.
55 * When drawing is finished, call <tt>endExport()</tt>.
56 *
57 * @author Simon Fischer
58 * @author Mark Donszelmann
59 * @version $Id: freehep-graphicsio-pdf/src/main/java/org/freehep/graphicsio/pdf/PDFGraphics2D.java 59372df5e0d9 2007/02/06 21:11:19 duns $
60 */
61 public class PDFGraphics2D extends AbstractVectorGraphicsIO implements
62 MultiPageDocument, FontUtilities.ShowString {
63
64 /*
65 * ================================================================================
66 * Table of Contents: ------------------ 1. Constructors & Factory Methods
67 * 2. Document Settings 3. Header, Trailer, Multipage & Comments 3.1 Header &
68 * Trailer 3.2 MultipageDocument methods 4. Create & Dispose 5. Drawing
69 * Methods 5.1. shapes (draw/fill) 5.1.1. lines, rectangles, round
70 * rectangles 5.1.2. polylines, polygons 5.1.3. ovals, arcs 5.1.4. shapes
71 * 5.2. Images 5.3. Strings 6. Transformations 7. Clipping 8. Graphics State /
72 * Settings 8.1. stroke/linewidth 8.2. paint/color 8.3. font 8.4. rendering
73 * hints 9. Private/Utility Methods 9.1. drawing, shape creation 9.2. font,
74 * strings 9.3. images 9.4. transformations 10. Auxiliary
75 * ================================================================================
76 */
77
78 private static final String rootKey = PDFGraphics2D.class.getName();
79
80 public static final String VERSION6 = "Acrobat Reader 6.x";
81
82 public static final String VERSION5 = "Acrobat Reader 5.x";
83
84 public static final String VERSION4 = "Acrobat Reader 4.x";
85
86 public static final String TRANSPARENT = rootKey + "."
87 + PageConstants.TRANSPARENT;
88
89 public static final String BACKGROUND = rootKey + "."
90 + PageConstants.BACKGROUND;
91
92 public static final String BACKGROUND_COLOR = rootKey + "."
93 + PageConstants.BACKGROUND_COLOR;
94
95 /**
96 * Property name for setting the size of the pages output by this {@code PDFGraphics2D}.
97 * <p>
98 * To set a pre-defined page size, set this property to one of the page size constants defined
99 * in {@link PageConstants} - for instance, {@linkplain PageConstants#A4},
100 * {@linkplain PageConstants#LETTER}.
101 * <p>
102 * To set a custom page size, set this property to the value {@link CUSTOM_PAGE_SIZE}. Then,
103 * set the {@link CUSTOM_PAGE_SIZE} property to a {@link Dimension} object.
104 * @see UserProperties
105 */
106 public static final String PAGE_SIZE = rootKey + "."
107 + PageConstants.PAGE_SIZE;
108
109 /**
110 * Property name (and value!) for setting a custom page size.
111 * <p>
112 * If the {@link PAGE_SIZE} property is set to THIS VALUE, then the properties are consulted
113 * for the value of THIS KEY. The value of this key should be a {@link Dimension} object,
114 * in the "user coordinates" of Java2D.
115 *
116 */
117 public static final String CUSTOM_PAGE_SIZE = rootKey + "."
118 + PageConstants.CUSTOM_PAGE_SIZE;
119
120 public static final String PAGE_MARGINS = rootKey + "."
121 + PageConstants.PAGE_MARGINS;
122
123 public static final String ORIENTATION = rootKey + "."
124 + PageConstants.ORIENTATION;
125
126 public static final String FIT_TO_PAGE = rootKey + "."
127 + PageConstants.FIT_TO_PAGE;
128
129 public static final String EMBED_FONTS = rootKey + "."
130 + FontConstants.EMBED_FONTS;
131
132 public static final String EMBED_FONTS_AS = rootKey + "."
133 + FontConstants.EMBED_FONTS_AS;
134
135 public static final String THUMBNAILS = rootKey + ".Thumbnails";
136
137 public static final String THUMBNAIL_SIZE = rootKey + ".ThumbnailSize";
138
139 public static final String COMPRESS = rootKey + ".Compress";
140
141 public static final String VERSION = rootKey + ".Version";
142
143 public static final String WRITE_IMAGES_AS = rootKey + "."
144 + ImageConstants.WRITE_IMAGES_AS;
145
146 public static final String AUTHOR = rootKey + "." + InfoConstants.AUTHOR;
147
148 public static final String TITLE = rootKey + "." + InfoConstants.TITLE;
149
150 public static final String SUBJECT = rootKey + "." + InfoConstants.SUBJECT;
151
152 public static final String KEYWORDS = rootKey + "."
153 + InfoConstants.KEYWORDS;
154
155 private static final UserProperties defaultProperties = new UserProperties();
156 static {
157 defaultProperties.setProperty(TRANSPARENT, true);
158 defaultProperties.setProperty(BACKGROUND, false);
159 defaultProperties.setProperty(BACKGROUND_COLOR, Color.GRAY);
160
161 defaultProperties.setProperty(VERSION, VERSION5);
162 defaultProperties.setProperty(COMPRESS, false);
163 defaultProperties.setProperty(PAGE_SIZE, PageConstants.INTERNATIONAL);
164 defaultProperties.setProperty(PAGE_MARGINS, PageConstants
165 .getMargins(PageConstants.SMALL));
166 defaultProperties.setProperty(ORIENTATION, PageConstants.PORTRAIT);
167 defaultProperties.setProperty(FIT_TO_PAGE, true);
168 defaultProperties.setProperty(EMBED_FONTS, false);
169 defaultProperties.setProperty(EMBED_FONTS_AS,
170 FontConstants.EMBED_FONTS_TYPE3);
171 defaultProperties.setProperty(THUMBNAILS, defaultProperties
172 .getProperty(VERSION).equals(VERSION4));
173 defaultProperties.setProperty(THUMBNAIL_SIZE, new Dimension(128, 128));
174 defaultProperties.setProperty(WRITE_IMAGES_AS, ImageConstants.SMALLEST);
175
176 defaultProperties.setProperty(AUTHOR, "");
177 defaultProperties.setProperty(TITLE, "");
178 defaultProperties.setProperty(SUBJECT, "");
179 defaultProperties.setProperty(KEYWORDS, "");
180
181 defaultProperties.setProperty(CLIP, true);
182 defaultProperties.setProperty(TEXT_AS_SHAPES, true);
183 }
184
185 public static Properties getDefaultProperties() {
186 return defaultProperties;
187 }
188
189 public static void setDefaultProperties(Properties newProperties) {
190 defaultProperties.setProperties(newProperties);
191 }
192
193 public static final String version = "$Revision$";
194
195 private static final String PDF_VERSION = "1.4";
196
197 private static final String[] COMPRESS_FILTERS = { ImageConstants.ENCODING_FLATE, ImageConstants.ENCODING_ASCII85};
198
199 private static final String[] NO_FILTERS = {};
200
201 private static final double FONTSIZE_CORRECTION = 1.0;
202
203 /*
204 * Not Used private static final CharTable STANDARD_CHAR_TABLES[] = {
205 * Lookup.getInstance().getTable("PDFLatin"),
206 * Lookup.getInstance().getTable("Symbol"),
207 * Lookup.getInstance().getTable("Zapfdingbats") };
208 *
209 * private static final Font STANDARD_FONT[] = { null, new Font("Symbol",
210 * Font.PLAIN, 10), new Font("ZapfDingbats", Font.PLAIN, 10), };
211 */
212
213 // output
214 private OutputStream ros;
215
216 private PDFWriter os;
217
218 private PDFStream pageStream;
219
220 // remember some things to do
221 private PDFFontTable fontTable; // remember which standard fonts were used
222
223 private PDFImageDelayQueue delayImageQueue; // remember images XObjects to
224
225 // include in the file
226
227 private PDFPaintDelayQueue delayPaintQueue; // remember patterns to include
228
229 // in the file
230
231 // multipage
232 private int currentPage;
233
234 private boolean multiPage;
235
236 private TagString[] headerText;
237
238 private int headerUnderline;
239
240 private Font headerFont;
241
242 private TagString[] footerText;
243
244 private int footerUnderline;
245
246 private Font footerFont;
247
248 private List<String> titles;
249
250 // extra pointers
251 int alphaIndex;
252
253 Map<Float, String> extGStates;
254
255 /*
256 * ================================================================================ |
257 * 1. Constructors & Factory Methods
258 * ================================================================================
259 */
260
261 public PDFGraphics2D(File file, Dimension size)
262 throws FileNotFoundException {
263 this(new FileOutputStream(file), size);
264 }
265
266 public PDFGraphics2D(File file, Component component)
267 throws FileNotFoundException {
268 this(new FileOutputStream(file), component);
269 }
270
271 public PDFGraphics2D(OutputStream ros, Dimension size) {
272 super(size, false);
273 init(ros);
274 }
275
276 public PDFGraphics2D(OutputStream ros, Component component) {
277 super(component, false);
278 init(ros);
279 }
280
281 private void init(OutputStream ros) {
282 this.ros = new BufferedOutputStream(ros);
283
284 currentPage = 0;
285 multiPage = false;
286 titles = new ArrayList<String>();
287 initProperties(defaultProperties);
288 }
289
290 /** Cloneconstructor */
291 protected PDFGraphics2D(PDFGraphics2D graphics, boolean doRestoreOnDispose) {
292 super(graphics, doRestoreOnDispose);
293
294 this.os = graphics.os;
295 this.pageStream = graphics.pageStream;
296
297 this.delayImageQueue = graphics.delayImageQueue;
298 this.delayPaintQueue = graphics.delayPaintQueue;
299 this.fontTable = graphics.fontTable;
300
301 this.currentPage = graphics.currentPage;
302 this.multiPage = graphics.multiPage;
303 this.titles = graphics.titles;
304
305 this.alphaIndex = graphics.alphaIndex;
306 this.extGStates = graphics.extGStates;
307 }
308
309 /*
310 * ================================================================================ |
311 * 2. Document Settings
312 * ================================================================================
313 */
314 public void setMultiPage(boolean multiPage) {
315 this.multiPage = multiPage;
316 }
317
318 public boolean isMultiPage() {
319 return multiPage;
320 }
321
322 /**
323 * Set the clipping enabled flag. This will affect all output operations
324 * after this call completes. In some circumstances the clipping region is
325 * set incorrectly (not yet understood; AWT seems to not correctly dispose
326 * of graphic contexts). A workaround is to simply switch it off.
327 */
328 public static void setClipEnabled(boolean enabled) {
329 defaultProperties.setProperty(CLIP, enabled);
330 }
331
332 /*
333 * ================================================================================ |
334 * 3. Header, Trailer, Multipage & Comments
335 * ================================================================================
336 */
337 /* 3.1 Header & Trailer */
338
339 /**
340 * Writes the catalog, docinfo, preferences, and (as we use only single page
341 * output the page tree.
342 */
343 public void writeHeader() throws IOException {
344 os = new PDFWriter(new BufferedOutputStream(ros), PDF_VERSION);
345
346 delayImageQueue = new PDFImageDelayQueue(os);
347 delayPaintQueue = new PDFPaintDelayQueue(os, delayImageQueue);
348
349 fontTable = new PDFFontTable(os);
350
351 String producer = getClass().getName();
352 if (!isDeviceIndependent()) {
353 producer += " " + version.substring(1, version.length() - 1);
354 }
355
356 PDFDocInfo info = os.openDocInfo("DocInfo");
357 info.setTitle(getProperty(TITLE));
358 info.setAuthor(getProperty(AUTHOR));
359 info.setSubject(getProperty(SUBJECT));
360 info.setKeywords(getProperty(KEYWORDS));
361
362 info.setCreator(getCreator());
363 info.setProducer(producer);
364 if (!isDeviceIndependent()) {
365 Calendar now = Calendar.getInstance();
366 info.setCreationDate(now);
367 info.setModificationDate(now);
368 }
369 info.setTrapped("False");
370 os.close(info);
371
372 // catalog
373 PDFCatalog catalog = os.openCatalog("Catalog", "RootPage");
374 catalog.setOutlines("Outlines");
375 catalog.setPageMode("UseOutlines");
376 catalog.setViewerPreferences("Preferences");
377 catalog.setOpenAction(new Object[] { os.ref("Page1"), os.name("Fit") });
378 os.close(catalog);
379
380 // preferences
381 PDFViewerPreferences prefs = os.openViewerPreferences("Preferences");
382 prefs.setFitWindow(true);
383 prefs.setCenterWindow(false);
384 os.close(prefs);
385
386 // extra stuff
387 alphaIndex = 1;
388 extGStates = new HashMap<Float, String>();
389
390 // hide the multipage functionality to the user in case of single page
391 // output by opening the first and only page immediately
392 if (!isMultiPage())
393 openPage(getSize(), null, getComponent());
394 }
395
396 public void writeBackground() {
397 if (isProperty(TRANSPARENT)) {
398 setBackground(null);
399 } else if (isProperty(BACKGROUND)) {
400 setBackground(getPropertyColor(BACKGROUND_COLOR));
401 clearRect(0.0, 0.0, getSize().width, getSize().height);
402 } else {
403 setBackground(getComponent() != null ? getComponent()
404 .getBackground() : Color.WHITE);
405 clearRect(0.0, 0.0, getSize().width, getSize().height);
406 }
407 }
408
409 public void writeTrailer() throws IOException {
410 if (!isMultiPage())
411 closePage();
412
413 // pages
414 PDFPageTree pages = os.openPageTree("RootPage", null);
415 for (int i = 1; i <= currentPage; i++) {
416 pages.addPage("Page" + i);
417 }
418 Dimension pageSize = getPageSize();
419 pages.setMediaBox(0, 0, pageSize.getWidth(), pageSize.getHeight());
420 pages.setResources("Resources");
421 os.close(pages);
422
423 // ProcSet
424 os.object("PageProcSet", new Object[] { os.name("PDF"),
425 os.name("Text"), os.name("ImageC") });
426
427 // Font
428 int nFonts = fontTable.addFontDictionary();
429
430 // XObject
431 int nXObjects = delayImageQueue.addXObjects();
432
433 // Pattern
434 int nPatterns = delayPaintQueue.addPatterns();
435
436 // ExtGState
437 if (extGStates.size() > 0) {
438 PDFDictionary extGState = os.openDictionary("ExtGState");
439
440 for (Iterator<Float> i = extGStates.keySet().iterator(); i.hasNext();) {
441 Float alpha = i.next();
442 String alphaName = extGStates.get(alpha);
443 PDFDictionary alphaDictionary = extGState
444 .openDictionary(alphaName);
445 alphaDictionary.entry("ca", alpha.floatValue());
446 alphaDictionary.entry("CA", alpha.floatValue());
447 alphaDictionary.entry("BM", os.name("Normal"));
448 alphaDictionary.entry("AIS", false);
449 extGState.close(alphaDictionary);
450 }
451 os.close(extGState);
452 }
453
454 // resources
455 PDFDictionary resources = os.openDictionary("Resources");
456 resources.entry("ProcSet", os.ref("PageProcSet"));
457 if (nFonts > 0)
458 resources.entry("Font", os.ref("FontList"));
459 if (nXObjects > 0)
460 resources.entry("XObject", os.ref("XObjects"));
461 if (nPatterns > 0)
462 resources.entry("Pattern", os.ref("Pattern"));
463 if (extGStates.size() > 0)
464 resources.entry("ExtGState", os.ref("ExtGState"));
465 os.close(resources);
466
467 // outlines
468 PDFOutlineList outlines = os.openOutlineList("Outlines", "Outline1",
469 "Outline" + currentPage);
470 os.close(outlines);
471
472 for (int i = 1; i <= currentPage; i++) {
473 String prev = i > 1 ? "Outline" + (i - 1) : null;
474 String next = i < currentPage ? "Outline" + (i + 1) : null;
475 PDFOutline outline = os.openOutline("Outline" + i, titles
476 .get(i - 1), "Outlines", prev, next);
477 outline
478 .setDest(new Object[] { os.ref("Page" + i), os.name("Fit") });
479 os.close(outline);
480 }
481
482 // delayed objects (images, patterns, fonts)
483 processDelayed();
484 }
485
486 public void closeStream() throws IOException {
487 os.close();
488 }
489
490 private void processDelayed() throws IOException {
491 delayImageQueue.processAll();
492 delayPaintQueue.processAll();
493 fontTable.embedAll(getFontRenderContext(), isProperty(EMBED_FONTS),
494 getProperty(EMBED_FONTS_AS));
495 }
496
497 /* 3.2 MultipageDocument methods */
498 public void openPage(Component component) throws IOException {
499 openPage(component.getSize(), component.getName(), component);
500 }
501
502 public void openPage(Dimension size, String title) throws IOException {
503 openPage(size, title, null);
504 }
505
506 private void openPage(Dimension size, String title, Component component)
507 throws IOException {
508 if (size == null)
509 size = component.getSize();
510
511 resetClip(new Rectangle(0, 0, size.width, size.height));
512
513 if (pageStream != null) {
514 writeWarning("Page " + currentPage + " already open. "
515 + "Call closePage() before starting a new one.");
516 return;
517 }
518
519 BufferedImage thumbnail = null;
520 // prepare thumbnail if possible
521 if ((component != null) && isProperty(PDFGraphics2D.THUMBNAILS)) {
522 thumbnail = ImageGraphics2D.generateThumbnail(component,
523 getPropertyDimension(PDFGraphics2D.THUMBNAIL_SIZE));
524 }
525
526 currentPage++;
527
528 if (title == null)
529 title = "Page " + currentPage + " (untitled)";
530 titles.add(title);
531
532 PDFPage page = os.openPage("Page" + currentPage, "RootPage");
533 page.setContents("PageContents" + currentPage);
534
535 if (thumbnail != null)
536 page.setThumb("Thumb" + currentPage);
537
538 os.close(page);
539
540 if (thumbnail != null) {
541 PDFStream thumbnailStream = os.openStream("Thumb" + currentPage);
542 thumbnailStream.image(thumbnail, Color.black, ImageConstants.ZLIB);
543 os.close(thumbnailStream);
544 }
545
546 pageStream = os.openStream("PageContents" + currentPage,
547 isProperty(COMPRESS) ? COMPRESS_FILTERS : NO_FILTERS);
548
549 // transform the coordinate system as necessary
550 // 1. flip the coordinate system down and translate it upwards again
551 // so that the origin is the upper left corner of the page.
552 AffineTransform pageTrafo = new AffineTransform();
553 pageTrafo.scale(1, -1);
554 Dimension pageSize = getPageSize();
555 Insets margins = PageConstants.getMargins(
556 getPropertyInsets(PAGE_MARGINS), getProperty(ORIENTATION));
557 pageTrafo
558 .translate(margins.left, -(pageSize.getHeight() - margins.top));
559
560 // in between write the header and footer (which should not be scaled!)
561 writeHeadline(pageTrafo);
562 writeFootline(pageTrafo);
563
564 // 2. check whether we have to rescale the image to fit onto the page
565 double scaleFactor = Math.min(getWidth() / size.width, getHeight()
566 / size.height);
567 if ((scaleFactor < 1) || isProperty(FIT_TO_PAGE)) {
568 pageTrafo.scale(scaleFactor, scaleFactor);
569 } else {
570 scaleFactor = 1;
571 }
572
573 // 3. center the image on the page
574 double dx = (getWidth() - size.width * scaleFactor) / 2 / scaleFactor;
575 double dy = (getHeight() - size.height * scaleFactor) / 2 / scaleFactor;
576 pageTrafo.translate(dx, dy);
577
578 writeTransform(pageTrafo);
579
580 // save the graphics context resets before setClip
581 writeGraphicsSave();
582
583 clipRect(0, 0, size.width, size.height);
584
585 // save the graphics context resets before setClip
586 writeGraphicsSave();
587
588 delayPaintQueue.setPageMatrix(pageTrafo);
589
590 writeGraphicsState();
591 writeBackground();
592 }
593
594 public void closePage() throws IOException {
595 if (pageStream == null) {
596 writeWarning("Page " + currentPage + " already closed. "
597 + "Call openPage() to start a new one.");
598 return;
599 }
600 writeGraphicsRestore();
601 writeGraphicsRestore();
602 os.close(pageStream);
603 pageStream = null;
604
605 processDelayed(); // This does not work properly with acrobat reader
606 // 4!
607 }
608
609 public void setHeader(Font font, TagString left, TagString center,
610 TagString right, int underlineThickness) {
611 this.headerFont = font;
612 this.headerText = new TagString[3];
613 this.headerText[0] = left;
614 this.headerText[1] = center;
615 this.headerText[2] = right;
616 this.headerUnderline = underlineThickness;
617 }
618
619 public void setFooter(Font font, TagString left, TagString center,
620 TagString right, int underlineThickness) {
621 this.footerFont = font;
622 this.footerText = new TagString[3];
623 this.footerText[0] = left;
624 this.footerText[1] = center;
625 this.footerText[2] = right;
626 this.footerUnderline = underlineThickness;
627 }
628
629 private void writeHeadline(AffineTransform pageTrafo) throws IOException {
630 if (headerText != null) {
631 LineMetrics metrics = headerFont.getLineMetrics("mM",
632 getFontRenderContext());
633 writeLine(pageTrafo, headerFont, headerText, -metrics.getLeading()
634 - headerFont.getSize2D() / 2, TEXT_BOTTOM, -headerFont
635 .getSize2D() / 2, headerUnderline);
636
637 }
638 }
639
640 private void writeFootline(AffineTransform pageTrafo) throws IOException {
641 if (footerText != null) {
642 LineMetrics metrics = footerFont.getLineMetrics("mM",
643 getFontRenderContext());
644 double y = getHeight() + footerFont.getSize2D() / 2;
645 writeLine(pageTrafo, footerFont, footerText, y
646 + metrics.getLeading(), TEXT_TOP, y, footerUnderline);
647 }
648 }
649
650 private void writeLine(AffineTransform trafo, Font font, TagString[] text,
651 double ty, int yAlign, double ly, int underline) throws IOException {
652 writeGraphicsSave();
653 setColor(Color.black);
654 setFont(font);
655 writeTransform(trafo);
656 if (text[0] != null)
657 drawString(text[0], 0, ty, TEXT_LEFT, yAlign);
658 if (text[1] != null)
659 drawString(text[1], getWidth() / 2, ty, TEXT_CENTER, yAlign);
660 if (text[2] != null)
661 drawString(text[2], getWidth(), ty, TEXT_RIGHT, yAlign);
662 if (underline >= 0) {
663 setLineWidth((double) underline);
664 drawLine(0, ly, getWidth(), ly);
665 }
666 writeGraphicsRestore();
667 }
668
669 /*
670 * ================================================================================ |
671 * 4. Create & Dispose
672 * ================================================================================
673 */
674
675 public Graphics create() {
676 try {
677 writeGraphicsSave();
678 } catch (IOException e) {
679 handleException(e);
680 }
681 return new PDFGraphics2D(this, true);
682 }
683
684 public Graphics create(double x, double y, double width, double height) {
685 try {
686 writeGraphicsSave();
687 } catch (IOException e) {
688 handleException(e);
689 }
690 PDFGraphics2D graphics = new PDFGraphics2D(this, true);
691 graphics.translate(x, y);
692 graphics.clipRect(0, 0, width, height);
693 return graphics;
694 }
695
696 protected void writeGraphicsSave() throws IOException {
697 pageStream.save();
698 }
699
700 protected void writeGraphicsRestore() throws IOException {
701 pageStream.restore();
702 }
703
704 /*
705 * ================================================================================ |
706 * 5. Drawing Methods
707 * ================================================================================ /*
708 * 5.1.4. shapes
709 */
710 public void draw(Shape s) {
711 try {
712 if (getStroke() instanceof BasicStroke) {
713 // in this case we've already handled the stroke
714 pageStream.drawPath(s);
715 pageStream.stroke();
716 } else {
717 // otherwise handle it now
718 pageStream.drawPath(getStroke().createStrokedShape(s));
719 pageStream.fill();
720 }
721 } catch (IOException e) {
722 handleException(e);
723 }
724 }
725
726 public void fill(Shape s) {
727 try {
728 boolean eofill = pageStream.drawPath(s);
729 if (eofill) {
730 pageStream.fillEvenOdd();
731 } else {
732 pageStream.fill();
733 }
734 } catch (IOException e) {
735 handleException(e);
736 }
737 }
738
739 /* 5.2 Images */
740 public void copyArea(int x, int y, int width, int height, int dx, int dy) {
741 writeWarning(getClass()
742 + ": copyArea(int, int, int, int, int, int) not implemented.");
743 }
744
745 protected void writeImage(RenderedImage image, AffineTransform xform,
746 Color bkg) throws IOException {
747 PDFName ref = delayImageQueue.delayImage(image, bkg,
748 getProperty(WRITE_IMAGES_AS));
749
750 AffineTransform imageTransform = new AffineTransform(image.getWidth(),
751 0.0, 0.0, -image.getHeight(), 0.0, image.getHeight());
752 xform.concatenate(imageTransform);
753
754 writeGraphicsSave();
755 pageStream.matrix(xform);
756 pageStream.xObject(ref);
757 writeGraphicsRestore();
758 }
759
760 /* 5.3. Strings */
761 protected void writeString(String str, double x, double y)
762 throws IOException {
763 // save the graphics context, especially the transformation matrix
764 writeGraphicsSave();
765
766 // translate the offset to x and y
767 AffineTransform at = new AffineTransform(1, 0, 0, 1, x, y);
768 // transform for font
769 at.concatenate(getFont().getTransform());
770 // mirror the matrix
771 at.scale(1, -1);
772
773 // write transform
774 writeTransform(at);
775
776 pageStream.beginText();
777 pageStream.text(0, 0);
778 showCharacterCodes(str);
779 pageStream.endText();
780
781 // restore the transformation matrix
782 writeGraphicsRestore();
783 }
784
785 /*
786 * ================================================================================ |
787 * 6. Transformations
788 * ================================================================================
789 */
790 /** Write the given transformation matrix to the file. */
791 protected void writeTransform(AffineTransform t) throws IOException {
792 pageStream.matrix(t);
793 }
794
795 /*
796 * ================================================================================ |
797 * 7. Clipping
798 * ================================================================================
799 */
800 protected void writeSetClip(Shape s) throws IOException {
801 // clear old clip
802 try {
803 AffineTransform at = getTransform();
804 Stroke stroke = getStroke();
805
806 writeGraphicsRestore();
807 writeGraphicsSave();
808
809 writeStroke(stroke);
810 writeTransform(at);
811 } catch (IOException e) {
812 handleException(e);
813 }
814
815 // write clip
816 writeClip(s);
817 }
818
819 protected void writeClip(Shape s) throws IOException {
820 if (s == null || !isProperty(CLIP)) {
821 return;
822 }
823
824 if (s instanceof Rectangle2D) {
825 pageStream.move(((Rectangle2D) s).getMinX(), ((Rectangle2D) s)
826 .getMinY());
827 pageStream.line(((Rectangle2D) s).getMaxX(), ((Rectangle2D) s)
828 .getMinY());
829 pageStream.line(((Rectangle2D) s).getMaxX(), ((Rectangle2D) s)
830 .getMaxY());
831 pageStream.line(((Rectangle2D) s).getMinX(), ((Rectangle2D) s)
832 .getMaxY());
833 pageStream.closePath();
834 pageStream.clip();
835 pageStream.endPath();
836 } else {
837 boolean eoclip = pageStream.drawPath(s);
838 if (eoclip) {
839 pageStream.clipEvenOdd();
840 } else {
841 pageStream.clip();
842 }
843
844 pageStream.endPath();
845 }
846 }
847
848 /*
849 * ================================================================================ |
850 * 8. Graphics State
851 * ================================================================================
852 */
853 /* 8.1. stroke/linewidth */
854 protected void writeWidth(float width) throws IOException {
855 pageStream.width(width);
856 }
857
858 protected void writeCap(int cap) throws IOException {
859 switch (cap) {
860 default:
861 case BasicStroke.CAP_BUTT:
862 pageStream.cap(0);
863 break;
864 case BasicStroke.CAP_ROUND:
865 pageStream.cap(1);
866 break;
867 case BasicStroke.CAP_SQUARE:
868 pageStream.cap(2);
869 break;
870 }
871 }
872
873 protected void writeJoin(int join) throws IOException {
874 switch (join) {
875 default:
876 case BasicStroke.JOIN_MITER:
877 pageStream.join(0);
878 break;
879 case BasicStroke.JOIN_ROUND:
880 pageStream.join(1);
881 break;
882 case BasicStroke.JOIN_BEVEL:
883 pageStream.join(2);
884 break;
885 }
886 }
887
888 protected void writeMiterLimit(float limit) throws IOException {
889 pageStream.mitterLimit(limit);
890 }
891
892 protected void writeDash(float[] dash, float phase) throws IOException {
893 pageStream.dash(dash, phase);
894 }
895
896 /* 8.2. paint/color */
897 public void setPaintMode() {
898 writeWarning(getClass() + ": setPaintMode() not implemented.");
899 }
900
901 public void setXORMode(Color c1) {
902 writeWarning(getClass() + ": setXORMode(Color) not implemented.");
903 }
904
905 protected void writePaint(Color c) throws IOException {
906 float[] cc = c.getRGBComponents(null);
907 // System.out.println("alpha = "+cc[3]);
908 Float alpha = new Float(cc[3]);
909 String alphaName = extGStates.get(alpha);
910 if (alphaName == null) {
911 alphaName = "Alpha" + alphaIndex;
912 alphaIndex++;
913 extGStates.put(alpha, alphaName);
914 }
915 pageStream.state(os.name(alphaName));
916 pageStream.colorSpace(cc[0], cc[1], cc[2]);
917 pageStream.colorSpaceStroke(cc[0], cc[1], cc[2]);
918 }
919
920 protected void writePaint(GradientPaint c) throws IOException {
921 writePaint((Paint) c);
922 }
923
924 protected void writePaint(TexturePaint c) throws IOException {
925 writePaint((Paint) c);
926 }
927
928 protected void writePaint(Paint paint) throws IOException {
929 pageStream.colorSpace(os.name("Pattern"));
930 pageStream.colorSpaceStroke(os.name("Pattern"));
931 PDFName shadingName = delayPaintQueue.delayPaint(paint, getTransform(),
932 getProperty(WRITE_IMAGES_AS));
933 pageStream.colorSpace(null, shadingName);
934 pageStream.colorSpaceStroke(new double[] {}, shadingName);
935 }
936
937 protected void setNonStrokeColor(Color c) throws IOException {
938 float[] cc = c.getRGBColorComponents(null);
939 pageStream.colorSpace(cc[0], cc[1], cc[2]);
940 }
941
942 protected void setStrokeColor(Color c) throws IOException {
943 float[] cc = c.getRGBColorComponents(null);
944 pageStream.colorSpaceStroke(cc[0], cc[1], cc[2]);
945 }
946
947 /* 8.3. font */
948 protected void writeFont(Font font) throws IOException {
949 // written when needed
950 }
951
952 /*
953 * ================================================================================ |
954 * 9. Auxiliary
955 * ================================================================================
956 */
957 public GraphicsConfiguration getDeviceConfiguration() {
958 writeWarning(getClass() + ": getDeviceConfiguration() not implemented.");
959 return null;
960 }
961
962 public void writeComment(String comment) throws IOException {
963 // comments are ignored and disabled, because they confuse compressed
964 // streams
965 }
966
967 public String toString() {
968 return "PDFGraphics2D";
969 }
970
971 /*
972 * ================================================================================ |
973 * 10. Private/Utility
974 * ================================================================================
975 */
976 public void showString(Font font, String str) throws IOException {
977 String fontRef = fontTable.fontReference(font, isProperty(EMBED_FONTS),
978 getProperty(EMBED_FONTS_AS));
979 pageStream.font(os.name(fontRef), font.getSize() * FONTSIZE_CORRECTION);
980 pageStream.show(str);
981 }
982
983 /**
984 * See the comment of VectorGraphicsUtitlies1.
985 *
986 * @see FontUtilities#showString(java.awt.Font, String,
987 * org.freehep.graphics2d.font.CharTable,
988 * org.freehep.graphics2d.font.FontUtilities.ShowString)
989 */
990 private void showCharacterCodes(String str) throws IOException {
991 FontUtilities.showString(getFont(), str, Lookup.getInstance().getTable(
992 "PDFLatin"), this);
993 }
994
995 /**
996 * Reads the PAGE_SIZE Property. If A4 .. A0 is found,
997 * PageConstants will determine the size. If CUSTOM_PAGE_SIZE
998 * is found, CUSTOM_PAGE_SIZE is used as a Property key for
999 * a dimension object.
1000 *
1001 * @return Size of page
1002 */
1003 protected Dimension getPageSize() {
1004 // A4 ... A0 or PageConstants.CUSTOM_PAGE_SIZE expected
1005 // if PageConstants.CUSTOM_PAGE_SIZE is found,
1006 // PageConstants.CUSTOM_PAGE_SIZE is used as Key too
1007 String pageSizeProperty = getProperty(PAGE_SIZE);
1008
1009 // determine page size
1010 Dimension result;
1011 if (CUSTOM_PAGE_SIZE.equals(pageSizeProperty)) {
1012 result = getPropertyDimension(CUSTOM_PAGE_SIZE);
1013 } else {
1014 result = PageConstants.getSize(getProperty(PAGE_SIZE),
1015 getProperty(ORIENTATION));
1016 }
1017
1018 // set a default value
1019 if (result == null) {
1020 result = PageConstants.getSize(PageConstants.INTERNATIONAL);
1021 }
1022
1023 return result;
1024 }
1025
1026 private double getWidth() {
1027 Dimension pageSize = getPageSize();
1028 Insets margins = PageConstants.getMargins(
1029 getPropertyInsets(PAGE_MARGINS), getProperty(ORIENTATION));
1030 return pageSize.getWidth() - margins.left - margins.right;
1031 }
1032
1033 private double getHeight() {
1034 Dimension pageSize = getPageSize();
1035 Insets margins = PageConstants.getMargins(
1036 getPropertyInsets(PAGE_MARGINS), getProperty(ORIENTATION));
1037 return pageSize.getHeight() - margins.top - margins.bottom;
1038 }
1039
1040 }