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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| package com.ares.arpmsi.client.common.utils;
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;
/**
*
* @author * @version 1.0
*/
public class PrintUtils implements Printable {
/** le composant à imprimer */
private Component componentToBePrinted;
/** constructeur
* @param componentToBePrinted compsant à imprimer
*/
public PrintUtils(Component componentToBePrinted) {
this.componentToBePrinted = componentToBePrinted;
}
/** imprimer composant
* @param c le composant
*/
public static void printComponent(Component c) {
new PrintUtils(c).print();
}
/** print method **/
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
PageFormat pf = printJob.defaultPage();
/* Paper papier = new Paper();
double gauche = (10.0 * 72) / 25.4;
file: //fait une marge de 10 mm (donc 10/25.4 pouces avec un point =1/72 pouces)
papier.setImageableArea(gauche, 0.0, papier.getWidth() - (2 * gauche),
papier.getHeight());
pf.setPaper(papier);
file: */
printJob.setPrintable(this, pf);
if (printJob.printDialog()) {
try {
printJob.print();
} catch (PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
}
/** print method
* @param g graphisme
* @param pageFormat format
* @param pageIndex index
* @return valeur de retour de l'impression
*/
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
System.out.println("nb" + nbPg(componentToBePrinted, pageFormat));
if (pageIndex >= nbPg(componentToBePrinted, pageFormat)) {
return (NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pageFormat.getImageableX(),
pageFormat.getImageableY() +
(pageIndex * pageFormat.getImageableHeight()));
double scale = pageFormat.getImageableWidth() / componentToBePrinted.getWidth();
g2d.scale(scale, scale);
disableDoubleBuffering(componentToBePrinted);
componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return (PAGE_EXISTS);
}
}
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
/**
* @param c composant
*/
public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
public int nbPg(Component comp, PageFormat pgFormat) {
int nbPages = 0;
double heightDoc = (double) comp.getHeight();
double heightPg = pgFormat.getImageableHeight();
double dblNb = heightDoc / heightPg;
nbPages = (int) dblNb;
return nbPages;
}
} |