1   /****************************************************************************
2    **
3    ** This file is part of the yFiles extension package yExport-1.3.
4    ** 
5    ** yWorks proprietary/confidential. Use is subject to license terms.
6    **
7    ** Redistribution of this file or of an unauthorized byte-code version
8    ** of this file is strictly forbidden.
9    **
10   ** Copyright (c) 2007-2012 by yWorks GmbH, Vor dem Kreuzberg 28, 
11   ** 72070 Tuebingen, Germany. All rights reserved.
12   **
13   ***************************************************************************/
14  
15  package demo.yext.export;
16  
17  
18  import javax.print.attribute.standard.MediaSize;
19  import java.awt.print.PageFormat;
20  import java.awt.print.Paper;
21  import java.awt.Insets;
22  
23  
24  /**
25   * Utility class that provides convenience methods to set the size and margins
26   * for <code>PageFormat</code> instances.
27   *
28   */
29  public class PageFormatHelper {
30    /**
31     * Sets the paper size of the given <code>PageFormat</code> instance to
32     * match the specified <code>MediaSize</code>.
33     */
34    public static void assignMediaSize(PageFormat pageFormat, MediaSize mediaSize) {
35      float[] size = mediaSize.getSize(MediaSize.INCH);
36      int dpi = 72; //Toolkit.getDefaultToolkit().getScreenResolution();
37      size[0] *= dpi;
38      size[1] *= dpi;
39      Paper paper = new Paper();
40      paper.setSize(size[0], size[1]);
41      paper.setImageableArea(0, 0, size[0], size[1]);
42      pageFormat.setPaper(paper);
43    }
44  
45    /**
46     * Returns the <em>margins</em> for the given <code>PageFormat</code>
47     * instance.
48     */
49    public static Insets getMargin(PageFormat pageFormat) {
50      final int top  = (int)Math.ceil(pageFormat.getImageableY());
51      final int left = (int)Math.ceil(pageFormat.getImageableX());
52      return new Insets(top, left,
53                        (int)Math.ceil(pageFormat.getHeight()
54                                       - pageFormat.getImageableHeight()) - top,
55                        (int)Math.ceil(pageFormat.getWidth()
56                                       - pageFormat.getImageableWidth())  - left);
57    }
58  
59    /**
60     * Sets the specified <code>Insets</code> as <em>margins</em> for the given
61     * <code>PageFormat</code> instance.
62     */
63    public static void setMargin(PageFormat pageFormat, Insets insets) {
64      Paper paper = pageFormat.getPaper();
65      paper.setImageableArea(
66              insets.left,
67              insets.top,
68              paper.getWidth() - insets.left - insets.right,
69              paper.getHeight() - insets.top - insets.bottom
70      );
71      pageFormat.setPaper(paper);
72    }
73  
74    private PageFormatHelper() {
75    }
76  }