我正在创建一个 Java 应用程序,应用程序将在其中打印图片和旁边的一些文本。我在打印时有两台打印机,我会相应地选择。我不会为用户显示打印对话框来选择打印机和其他东西。我的代码如下
PrinterJob job = PrinterJob.getPrinterJob();
boolean ok = job.printDialog();
Run Code Online (Sandbox Code Playgroud)
如果我不跳过该行boolean ok = job.printDialog();,文本将在我的案例 (20,20) 中提到的位置打印,但如果我跳过该行,我的打印可能会在打印机上更远的点完成 (120, 120) 这意味着我需要一个保证金设置。并给我一个设置打印机的代码。
您可以使用job.print()代替来抑制打印对话框job.printDialog()。但是,如果您希望能够更改边距和其他所有内容,那么您需要使用可以在 java.awt.print.Paper 和 java.awt.print.PageFormat 下找到的Paper和PageFormat类。纸张将允许您设置纸张的尺寸并在PageFormat. 然后,您可以使用setPrintable()带有类型Printable和PrintFormat参数的对象的 PrinterJob 类的方法。但最重要的是,Paper如果您担心,该课程将允许您设置边距。
因为这个答案在谷歌上排名第一,所以这里是一个代码示例:
public class printWithoutDialog implements printable
{
public PrintService findPrintService(String printerName)
{
for (PrintService service : PrinterJob.lookupPrintServices())
{
if (service.getName().equalsIgnoreCase(printerName))
return service;
}
return null;
}
@Override
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.setFont(new Font("Roman", 0, 8));
g.drawString("Hello world !", 0, 10);
return PAGE_EXISTS;
}
public printSomething(String printerName)
{
//find the printService of name printerName
PrintService ps = findPrintService(printerName);
//create a printerJob
PrinterJob job = PrinterJob.getPrinterJob();
//set the printService found (should be tested)
job.setPrintService(ps);
//set the printable (an object with the print method that can be called by "job.print")
job.setPrintable(this);
//call je print method of the Printable object
job.print();
}
}
Run Code Online (Sandbox Code Playgroud)
要在没有对话框的情况下使用 Java 打印,您只需向 PrinterJob 指定您要设置的打印服务。printService 类为您想要的打印机提供服务。该类实现了 Java 教程中的可打印类(带有对话框)。唯一的区别在于“printSompething”功能,您可以在其中找到注释。
| 归档时间: |
|
| 查看次数: |
12678 次 |
| 最近记录: |