//
Utilisation de l'imprimante en Java
/* XmpImpr.java utilisations directes avec l'imprimante.
Utiliser le bouton "Une page" (méthode reflexe_bout1) et voir
l'impression directe d'un 'Panel' sur une seule page
Utiliser le bouton "Plusieurs pages" (méthode reflexe_bout2) et voir
une impression sur plusieurs pages:
association (par setPrintable) d'une tache d'impression (PrinterJob)
et de l'objet définissant la méthode:
public int print(Graphics g, PageFormat fmtP, int numP)
appelée pour l'impression de chaque page
la définition des paramètres d'impression par utilisation des boîtes
de dialogue (PrinterJob.pageDialog(fmtP), printerJob.printDialog())
Imprimer dans une activité (Thread) séparée
voir la classe XmpImpr_bout3_adaptation
Découper un paragraphe en lignes (classe LineBreakMeasurer)
voir la classe ImprimePara
Dimensions de la fenêtre
final int largF=690, hautF=565;
Dimensions d'une page format A4 (en points):
final int largP=595, hautP=841, mlargP=40, mhautP=60;
Simulation de la classe Courrier
javac XmpImpr.java
java XmpImpr &
Références pour l'impression en Java, et autres
www.javafr.com/gma/imprimer
// composant graphique
www.infres.enst.fr/~charon/coursJava/interSwing/imprimer.html
// composant graphique et pages
perso.club-internet.fr/hironico/swing/projet_swing/printing_api.html
// un cours Java
www.infres.enst.fr/~charon/coursJava/
// Foire aux questions
faqjava.developpez.com/
// Imprimer un texte long
java.sun.com/docs/books/tutorial/2d/textandfonts/linebreakmeasure.html
*/
import java.awt.print.*; //A
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*; // pour afficher un paragraphe
import java.text.*; // sur plusieurs lignes
import java.util.Properties;
/** Utilisations de l'imprimante
*/
public class XmpImpr extends Frame implements Printable {
// Pour imprimer une page
Button bout1 = new Button("Une page");
// Pour imprimer plusieurs pages
Button bout2 = new Button("Plusieurs pages");
// Pour imprimer par une activité détachée
String impreBout3= new String("Impression détachée");
String arretBout3= new String("Arrêtez !!!");
Button bout3 = new Button(impreBout3);
// Pour découper un paragraphe en lignes
Button bout4 = new Button("Un paragraphe");
// Pour dessiner dans la fenêtre
MonDessin des;
Courrier mes;
// largeur, hauteur de la fenêtre
final int largF=690, hautF=565;
// largeur, hauteur, marge en largeur(1.5cm) et en hauteur(1cm) d'une page
// final int largP=595, hautP=841, mlargP=42, mhautP=28;
int maxPage;
Color tcoul[]=new Color[4];
public XmpImpr(Courrier m) {
super("test d'impression");
maxPage=tcoul.length;
tcoul[0]=Color.darkGray; tcoul[1]=Color.blue;
tcoul[2]=Color.red; tcoul[3]=Color.green;
mes = m;
try { jbInit(); }
catch(Exception ex) { ex.printStackTrace(); }
}
/** Construction de l'interface utilisateur */
void jbInit() throws Exception {
// Trois boutons dans un panneau
Button bQuitter = this.pourQuitter("Quitter");
Panel panBouts = new Panel();
panBouts.add(bout1); panBouts.add(bout2); panBouts.add(bout3);
panBouts.add(bout4);
panBouts.add(bQuitter);
// Dessin central
des = new MonDessin(mes);
// Deux panneaux dans la fenêtre principale
this.add(des,BorderLayout.CENTER);
this.add(panBouts,BorderLayout.SOUTH);
// Mise en place des réflexes
bout1.addActionListener(new XmpImpr_bout1_adaptation(this));
bout2.addActionListener(new XmpImpr_bout2_adaptation (this));
bout3.addActionListener(new XmpImpr_bout3_adaptation (this));
bout4.addActionListener(new ImprimePara (this));
}
/** Construit un bouton et met en place deux réflexes (quitter par
* un bouton ou par le gestionnaire de fenêtres) qui appellent
* la méthode quitterFen()
*/
Button pourQuitter(String ch) {
// Pour quitter par le bouton
Button quit = new Button(ch);
quit.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) { quitterFen(); }
});
// Pour quitter par l'encadrement (gestionnaire de fenêtres)
WindowAdapter pf = new WindowAdapter() {
public void windowClosing(WindowEvent e) { quitterFen(); };
};
this.addWindowListener(pf);
return quit;
}
// Fonction qui surveille, si nécessaire, la fermeture de la fenêtre
// à adapter suivant les besoins
void quitterFen() { System.exit(0); }
// // // // // // // // // // // // // // // // // //
// Réflexe sur 'une page' pour imprimer une page
void reflexe_bout1(ActionEvent e) {
XmpImpr.this.setSize(largF,hautF);
XmpImpr.this.repaint();
Properties props = new Properties();
props.put("awt.print.paperSize", "a4");
props.put("awt.print.destination", "printer");
PrintJob pJob = getToolkit().getPrintJob(this,"Printing_Test", props);
if (pJob != null) {
Graphics pg = pJob.getGraphics();
des.printAll(pg);
int xxP=ptCm(21), yyP=ptCm(29.7); // dimension de la page A4
// Un rectangle en gris en bas de page
pg.setColor(Color.gray);
int xR=ptCm(1.5), yR=ptCm(27), xxR=ptCm(18), yyR=ptCm(1.7);
pg.fillRect(xR,yR,xxR,yyR);
// Une chaîne (ses dimensions), tracée en bleau dans le rectangle
pg.setFont(new Font("Arial",Font.BOLD,10));
pg.setColor(Color.blue);
String ch="Essai d'impression";
int xxC = pg.getFontMetrics().stringWidth(ch);
int yyC = pg.getFontMetrics().getHeight();
pg.drawString(ch,(int)(xR+(xxR-xxC)/2),(int)(yR+0.5*(yyR-yyC)));
pg.dispose();
pJob.end();
}
}
/** fournit des 'points' à partir de centimétres */
int ptCm(double cm) { return (int)(cm/2.54*72); }
// // // // // // // // // // // // // // // // // //
// Réflexe sur 'imprimer plusieurs pages'
void reflexe_bout2(ActionEvent e) {
// Tout visible dans la fenêtre
XmpImpr.this.setSize(largF,hautF);
XmpImpr.this.repaint();
// Pour l'imprimante
PrinterJob pj = PrinterJob.getPrinterJob();
// Changement éventuel
PageFormat fmtP = pj.defaultPage();
fmtP = pj.pageDialog(fmtP);
pj.defaultPage(fmtP);
// Objet définissant la méthode print(...) (interface Printable)
pj.setPrintable(XmpImpr.this);
// Boîte de dialogue
pj.printDialog();
// Attention à PrintException
try{ pj.print(); }
catch (Exception ex) { ex.printStackTrace(); }
}
// // // // // // // // // // // // // // // // // //
// Méthode activée par l'objet printerJob
public int print(Graphics g, PageFormat fmtP, int numP)
throws PrinterException {
if(numP >= maxPage) {
System.out.println(">>> Fin de l'impression <<<");
return Printable.NO_SUCH_PAGE;
}
int largP=(int)fmtP.getWidth(), hautP=(int)fmtP.getHeight(),
mlargP=(int)fmtP.getImageableX(), mhautP=(int)fmtP.getImageableY();
g.setColor(tcoul[numP]);
if(numP == 0) {
System.out.println("print ... numP="+numP+" "
+fmtP.PORTRAIT+","+fmtP.getOrientation()+" "
+fmtP.getWidth()+" , "+fmtP.getHeight()+" "
+fmtP.getImageableWidth()+" , "+fmtP.getImageableHeight()+" ");
}
// Paper pp= new Paper();
// largeur, hauteur, marge en largeur et en hauteur
// pp.setSize(largP,hautP); // format a4 en 1/72 pouce
// pp.setImageableArea(mlargP,mhautP,largP-2*mlargP,hautP-2*mhautP);
// fmtP.setPaper(pp);
// Echelles entre dimensions de la page et dim. de la fenêtre
double ecx = (largP-2*mlargP)/(double)largF
,ecy = (hautP-2*mhautP)/(double)hautF;
Graphics2D g2=(Graphics2D)g;
if(numP==0) {
int x,y,bordDroit=(int)fmtP.getImageableWidth();
String ch="Page "+(1+numP);
g.setFont(new Font("Arial",Font.BOLD,15));
int lch = g2.getFontMetrics().stringWidth(ch);
int hch = g2.getFontMetrics().getHeight();
g2.setClip(0,0,largP,hautP);
for(x=0, y=mhautP; x+lch<=bordDroit; y+=hch, x+=lch)
g2.drawString("Page "+(1+numP),x,y);
}
if(numP==1) {
int l, lch, hautF=25, bordDroit=(int)fmtP.getImageableWidth();
String ch;
g2.setFont(new Font("Arial",Font.BOLD,hautF));
g2.setClip(0,0,largP,hautP);
g2.translate(mlargP,mhautP);
for(l=0; l<13; l++) {
ch="Page "+(1+numP)+" ("+(1+l)+")"; // Page 1(n)
lch = g2.getFontMetrics().stringWidth(ch);
g2.drawString( ch, bordDroit-lch, (l-1)*hautF*6/5);
}
// Numéro de page en bas au centre
ch="Page "+(1+numP); // Page 1(n)
lch = g2.getFontMetrics().stringWidth(ch);
int hch = g2.getFontMetrics().getHeight();
g2.drawString(ch,(bordDroit-lch)/2,(int)fmtP.getImageableHeight()-hch);
g2.translate(-mlargP,-mhautP);
}
if(numP==2) {
// Numéro de page en haut
g2.setColor(tcoul[numP]);
g2.setClip(0,0,largP,hautP);
g2.translate(mlargP,mhautP);
g2.scale(ecx,ecy);
// des.printAll(g2);
g2.scale(1/ecx,1/ecy);
g2.drawString("Page "+(1+numP),largP/2-mlargP-20
,-(mhautP-g2.getFontMetrics().getHeight())/2);
}
if(numP==3) {
// Ecriture directe; pas de lien avec des composants
g2.setClip(0,0,largP,hautP);
g2.setColor(tcoul[numP]);
g2.fillRect(10,5,800,mhautP-5);
g2.setColor(Color.black);
g2.drawString("Page "+(1+numP),largP/2-20,mhautP/2);
int y;
for( y=mhautP+20; y= 1) {
System.out.println(">>> Fin de l'impression <<<");
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2=(Graphics2D)g;
// dim.page A4 (en points): largP=595, hautP=841, mlargP=42, mhautP=28;
float larg=520, posX=45; // marge gauche: 45, marge droite:30
float posY=100;
g2.setClip((int)posX,30,(int)larg,751);
AttributedString leParag = new AttributedString(unPara);
AttributedCharacterIterator index = leParag.getIterator();
int ideb = index.getBeginIndex(), ifin=index.getEndIndex();
// Une impression du paragraphe
LineBreakMeasurer chercheLignes = new LineBreakMeasurer(index,
new FontRenderContext(null,false,false));
// Parcours du paragraphe
while(chercheLignes.getPosition() < ifin) {
// texte suivant
TextLayout laLigne= chercheLignes.nextLayout(larg);
posY += laLigne.getAscent();
laLigne.draw(g2,posX,posY);
posY += laLigne.getDescent()+laLigne.getLeading();
}
// Saut de ligne; impression du même texte dans une largeur différente
g2.setFont(new Font("Arial",Font.BOLD,12));
g2.setColor(Color.blue);
posY += 30;
chercheLignes = new LineBreakMeasurer(index,
new FontRenderContext(null,false,false));
while(chercheLignes.getPosition() < ifin) {
// Le même texte plus à droite
TextLayout laLigne= chercheLignes.nextLayout(larg-100);
posY += laLigne.getAscent();
laLigne.draw(g2,posX+100,posY);
posY += laLigne.getDescent()+laLigne.getLeading();
}
return Printable.PAGE_EXISTS;
}
} // fin class ImprimePara
class Courrier {
String getSubject() { return "le sujet"; }
String getTexte() { return "le texte de Courrier"; }
boolean getAdresse( String ad[]) {
ad[0]="Monsieur ABCD efgh";
ad[1]="123 rue des Plantes";
ad[2]="Paris La Coquette";
ad[3]="FRANCE";
ad[4]="";
return true;
}
}