我想知道如何在Java中进行静音打印?

时间:2018-04-22 00:50:22

标签: java printing

我找不到关于静音打印的好信息。我想在不询问用户设置的情况下打印(它们应该在程序中定义)。重要的是我不想使用任何库。只是SDK。请告诉我该怎么做。这是我的代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.print.*;

public class Main 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();
        PageFormat pf = job.pageDialog(job.defaultPage());
        if (true) {
            try {
                job.print();
            } catch (PrinterException ex) {
              System.out.println(ex.getMessage());
            }
        }
    }


    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 Main());
        f.add("Center", printButton);
        f.pack();
        f.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:0)

在最基本的层面上,它可能看起来像......

PrinterJob job = PrinterJob.getPrinterJob();
Printable printable = ...;
job.setPrintable(printable);
job.print();

这将使用打印机的默认属性打印到默认打印机。

您还可以使用PrintRequestAttributeSetPrintService来修改要使用的打印机和/或属性

For exampleexample