Sera que alguem teria um exemplo prático de impressao em java, pois tenho um exemplo só que não imprimi. Ele se comunica com a impressora, ele puxa o papel tudo, só que nao imprimi nada, a folha passa direto. Sera que alguem poderia me ajudar com algum exemplo funcionando???
impressão em java
7 Respostas
Oi, se você puder poderia por favor mandar esse exemplo por email para mim. Caso você encontre algum que funcione me manda também. Se eu achar alguma coisa te envio.
Cara, ja consegui fazer funcionar a impressao, agora só preciso poder alterar fontes e tamanhos, vc sabe?? tentei o setfont mais nao deu certo.
Eu tenho esse código que rolou na lista do soujava.
Verifique se tem alguma utilidade.
Edilson S. Souza
Provecta Informática
www.javalinux.com.br
import java.awt.event.<em>;
import javax.swing.</em>;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.<em>;
import java.awt.geom.</em>;
import java.awt.print.*;
public class SimpleBook extends JPanel implements ActionListener{
final static Color bg = Color.white;
final static Color fg = Color.black;
final static Color red = Color.red;
final static Color white = Color.white;
final static BasicStroke stroke = new BasicStroke(2.0f);
final static BasicStroke wideStroke = new BasicStroke(8.0f);
final static float dash1[] = {10.0f};
final static BasicStroke dashed = new BasicStroke(1.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
final static JButton button = new JButton("Print");
public SimpleBook() {
setBackground(bg);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
// Get a PrinterJob
PrinterJob job = PrinterJob.getPrinterJob();
// Create a landscape page format
PageFormat landscape = job.defaultPage();
landscape.setOrientation(PageFormat.LANDSCAPE);
// Set up a book
Book bk = new Book();
bk.append(new PaintCover(), job.defaultPage());
bk.append(new PaintContent(), landscape);
// Pass the book to the PrinterJob
job.setPageable(bk);
// Put up the dialog box
if (job.printDialog()) {
// Print the job if the user didn't cancel printing
try { job.print(); }
catch (Exception exc) { /* Handle Exception */ }
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
drawShapes(g2);
}
static void drawShapes(Graphics2D g2){
int gridWidth = 600 / 6;
int gridHeight = 250 / 2;
int rowspacing = 5;
int columnspacing = 7;
int rectWidth = gridWidth - columnspacing;
int rectHeight = gridHeight - rowspacing;
Color fg3D = Color.lightGray;
g2.setPaint(fg3D);
g2.drawRect(80, 80, 605 - 1, 265);
g2.setPaint(fg);
int x = 85;
int y = 87;
// draw Line2D.Double
g2.draw(new Line2D.Double(x, y+rectHeight-1, x + rectWidth, y));
x += gridWidth;
Graphics2D temp = g2;
// draw Rectangle2D.Double
g2.setStroke(stroke);
g2.draw(new Rectangle2D.Double(x, y, rectWidth, rectHeight));
x += gridWidth;
// draw RoundRectangle2D.Double
g2.setStroke(dashed);
g2.draw(new RoundRectangle2D.Double(x, y, rectWidth,
rectHeight, 10, 10));
x += gridWidth;
// draw Arc2D.Double
g2.setStroke(wideStroke);
g2.draw(new Arc2D.Double(x, y, rectWidth, rectHeight, 90,
135, Arc2D.OPEN));
x += gridWidth;
// draw Ellipse2D.Double
g2.setStroke(stroke);
g2.draw(new Ellipse2D.Double(x, y, rectWidth, rectHeight));
x += gridWidth;
// draw GeneralPath (polygon)
int x1Points[] = {x, x+rectWidth, x, x+rectWidth};
int y1Points[] = {y, y+rectHeight, y+rectHeight, y};
GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,
x1Points.length);
polygon.moveTo(x1Points[0], y1Points[0]);
for ( int index = 1; index < x1Points.length; index++ ) {
polygon.lineTo(x1Points[index], y1Points[index]);
};
polygon.closePath();
g2.draw(polygon);
// NEW ROW
x = 85;
y += gridHeight;
// draw GeneralPath (polyline)
int x2Points[] = {x, x+rectWidth, x, x+rectWidth};
int y2Points[] = {y, y+rectHeight, y+rectHeight, y};
GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD,
x2Points.length);
polyline.moveTo (x2Points[0], y2Points[0]);
for ( int index = 1; index < x2Points.length; index++ ) {
polyline.lineTo(x2Points[index], y2Points[index]);
};
g2.draw(polyline);
x += gridWidth;
// fill Rectangle2D.Double (red)
g2.setPaint(red);
g2.fill(new Rectangle2D.Double(x, y, rectWidth, rectHeight));
g2.setPaint(fg);
x += gridWidth;
// fill RoundRectangle2D.Double
GradientPaint redtowhite = new GradientPaint(x,y,red,x+rectWidth,y,white);
g2.setPaint(redtowhite);
g2.fill(new RoundRectangle2D.Double(x, y, rectWidth,
rectHeight, 10, 10));
g2.setPaint(fg);
x += gridWidth;
// fill Arc2D
g2.setPaint(red);
g2.fill(new Arc2D.Double(x, y, rectWidth, rectHeight, 90,
135, Arc2D.OPEN));
g2.setPaint(fg);
x += gridWidth;
// fill Ellipse2D.Double
redtowhite = new GradientPaint(x,y,red,x+rectWidth, y,white);
g2.setPaint(redtowhite);
g2.fill (new Ellipse2D.Double(x, y, rectWidth, rectHeight));
g2.setPaint(fg);
x += gridWidth;
// fill and stroke GeneralPath
int x3Points[] = {x, x+rectWidth, x, x+rectWidth};
int y3Points[] = {y, y+rectHeight, y+rectHeight, y};
GeneralPath filledPolygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,
x3Points.length);
filledPolygon.moveTo(x3Points[0], y3Points[0]);
for ( int index = 1; index < x3Points.length; index++ ) {
filledPolygon.lineTo(x3Points[index], y3Points[index]);
};
filledPolygon.closePath();
g2.setPaint(red);
g2.fill(filledPolygon);
g2.setPaint(fg);
g2.draw(filledPolygon);
g2.setStroke(temp.getStroke());
}
public static void main(String[] args) {
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
public void windowClosed(WindowEvent e) {System.exit(0);}
};
JFrame f = new JFrame();
f.addWindowListener(l);
JPanel panel = new JPanel();
panel.add(button);
f.getContentPane().add(BorderLayout.SOUTH, panel);
f.getContentPane().add(BorderLayout.CENTER, new SimpleBook());
f.setSize(775, 450);
f.show();
}
}
class PaintCover implements Printable {
Font fnt = new Font(“Helvetica-Bold”, Font.PLAIN, 48);
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
g.setFont(fnt);
g.setColor(Color.black);
g.drawString(“Sample Shapes”, 100, 200);
return Printable.PAGE_EXISTS;
}
}
class PaintContent implements Printable {
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
SimpleBook.drawShapes((Graphics2D) g);
return Printable.PAGE_EXISTS;
}
}
tenta passar new Font(“Nome da Fonte”, Font.PLAIN )
este código funciona para mim… basta passar como agumento o ficheiro a imprimir…
public class printer {
JFrame frame;
JButton btn;
private boolean PrintJobDone = false;
printer(String FileToPrint, String pMode) {
try {
// Open the image file
InputStream is = new BufferedInputStream(new FileInputStream(FileToPrint));
// Find the default service
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
if (pMode != null && pMode.equalsIgnoreCase("TXT"))
;
else if (pMode != null && pMode.equalsIgnoreCase("PS"))
flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
else if (pMode != null && pMode.equalsIgnoreCase("PDF"))
flavor = DocFlavor.INPUT_STREAM.PDF;
else if (pMode != null && pMode.equalsIgnoreCase("JPG"))
flavor = DocFlavor.INPUT_STREAM.JPEG;
else if (pMode != null && pMode.equalsIgnoreCase("GIF"))
flavor = DocFlavor.INPUT_STREAM.GIF;
else if (pMode != null && pMode.equalsIgnoreCase("PNG"))
flavor = DocFlavor.INPUT_STREAM.PNG;
else if (pMode != null && pMode.equalsIgnoreCase("PCL"))
flavor = DocFlavor.INPUT_STREAM.PCL;
else if (pMode != null && pMode.equalsIgnoreCase("RAW"))
flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintService dservice = PrintServiceLookup.lookupDefaultPrintService();
PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);
if (services == null || services.length < 1)
services = PrintServiceLookup.lookupPrintServices(null, null);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
aset.add(OrientationRequested.PORTRAIT);
aset.add(Sides.ONE_SIDED);
aset.add(MediaSizeName.ISO_A4);
PrintService service = ServiceUI.printDialog(
(GraphicsConfiguration) null,
60, 60,
services,
(PrintService) dservice,
(DocFlavor) flavor,
aset);
if (service != null) {
// Create the print job
final DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(is, flavor, null);
// Monitor print job events; for the implementation of PrintJobWatcher,
PrintJobWatcher pjDone = new PrintJobWatcher(job);
try {
// Print it
job.print(doc, (PrintRequestAttributeSet) aset);
} catch (PrintException e) {
e.printStackTrace();
}
// Wait for the print job to be done
pjDone.waitForDone();
}
// It is now safe to close the input stream
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
synchronized (printer.this) {
PrintJobDone = true;
printer.this.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public synchronized void waitForDone() {
try {
while (!PrintJobDone) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class PrintJobWatcher {
// true iff it is safe to close the print job's input stream
boolean done = false;
int lastEvent = 0;
PrintJobWatcher(DocPrintJob job) {
// Add a listener to the print job
job.addPrintJobListener(
new PrintJobAdapter() {
public void printJobRequiresAttention(PrintJobEvent pje) {
lastEvent = pje.getPrintEventType();
System.err.println("* Erro na Impressora:" + pje);
}
public void printDataTransferCompleted(PrintJobEvent pje) {
lastEvent = pje.getPrintEventType();
System.err.println("* Ficheiro enviado para a Impressora ");
}
public void printJobCanceled(PrintJobEvent pje) {
lastEvent = pje.getPrintEventType();
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
lastEvent = pje.getPrintEventType();
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
lastEvent = pje.getPrintEventType();
System.err.println("* ERRO de impressão" + pje);
// allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
lastEvent = pje.getPrintEventType();
System.err.println("* Todos os Ficheiros foram enviados para a impressora ");
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Pessoal, alguem sabe se da para usar o PageFormat e PrinterJob para imprimir uma página web gerada pela aplicação ?
Abraço!
edilsonsanches e txibo vamos usar o [‘code’][’/code’] para facilitar nossas vidas!