-
Notifications
You must be signed in to change notification settings - Fork 0
/
PrintUtilities.java
86 lines (69 loc) · 2.06 KB
/
PrintUtilities.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
public class PrintUtilities implements Printable
{
private Component componentToBePrinted;
public static void printComponent(Component c)
{
new PrintUtilities(c).print();
}
public PrintUtilities(Component componentToBePrinted)
{
this.componentToBePrinted = componentToBePrinted;
}
public void print()
{
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
{
try
{
printJob.print();
JOptionPane.showMessageDialog(null, "Form Printed");
}
catch (PrinterException pe)
{
JOptionPane.showMessageDialog(null, "Error printing form");
}
}
}
public int print(Graphics g, PageFormat pf, int pageIndex)
{
int response = NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) g;
disableDoubleBuffering(componentToBePrinted);
Dimension d = componentToBePrinted.getSize();
double panelWidth = d.width;
double panelHeight = d.height;
double pageHeight = pf.getImageableHeight();
double pageWidth = pf.getImageableWidth();
double scale = (pageWidth / panelWidth) * 0.88;
int totalNumPages = (int) Math.ceil(scale * panelHeight / pageHeight);
if (pageIndex >= totalNumPages)
{
response = NO_SUCH_PAGE;
}
else
{
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.translate(0f, -pageIndex * pageHeight);
g2.scale(scale, scale);
componentToBePrinted.paint(g2);
enableDoubleBuffering(componentToBePrinted);
response = Printable.PAGE_EXISTS;
}
return response;
}
public static void disableDoubleBuffering(Component c)
{
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
public static void enableDoubleBuffering(Component c)
{
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
}