java 如何在java独立应用程序中将格式化输出打印到打印机
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17132425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to print formatted output to printer in java standalone application
提问by jonny depp
Basically i m creating a java standalone application where a student first gives his entire details.
基本上,我创建了一个 Java 独立应用程序,学生首先在其中提供他的全部详细信息。
when the print button is clicked i want to print some of the data given by the student in a specified format
单击打印按钮时,我想以指定格式打印学生提供的一些数据
like:
喜欢:
//logo goes here
regn no:
regn date:
name:
phnno:
mail:
how to do it??
怎么做??
回答by Thorbj?rn Ravn Andersen
If you want to do printing with Java with any kind of formatting instead of plain text, you need to use javax.print
. It is quite similar to the 2D graphics.
如果要使用任何类型的格式而不是纯文本使用 Java 进行打印,则需要使用javax.print
. 它与 2D 图形非常相似。
Have a look at the official tutorial at http://docs.oracle.com/javase/tutorial/2d/printing/to learn how to do it.
查看http://docs.oracle.com/javase/tutorial/2d/printing/上的官方教程,了解如何操作。
From http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/2d/printing/examples/HelloWorldPrinter.java(untested):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.print.*;
public class HelloWorldPrinter implements Printable, ActionListener {
public int print(Graphics g, PageFormat pf, int page) throws
PrinterException {
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Now we perform our rendering */
g.drawString("Hello world!", 100, 100);
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
/* The job did not successfully complete */
}
}
}
public static void main(String args[]) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame f = new JFrame("Hello World Printer");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
JButton printButton = new JButton("Print Hello World");
printButton.addActionListener(new HelloWorldPrinter());
f.add("Center", printButton);
f.pack();
f.setVisible(true);
}
}