我开始使用以下代码创建一个简单的Java应用程序来打印“Hello World”:
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);
}
}
这不起作用,我收到“未找到打印服务”的警告信息。
我使用的是Ubuntu 12.04,Java版本是1.7.0_25。
如何摆脱这种警报?
答案 0 :(得分:4)
安装cups-pdf,它将安装一个创建PDF文件的虚拟打印机:
sudo apt-get install cups-pdf
答案 1 :(得分:0)
这就是我在Arch Linux上打印到PDF的方式:
sudo pacman -S cups-pdf
sudo systemctl enable org.cups.cupsd.service
sudo systemctl start org.cups.cupsd.service
sudo system-config-printer
添加打印机“ Generic CUPS-PDF”,请参见下面的屏幕截图/var/spool/cups-pdf/$USER
Out
中编辑/etc/cups/cups-pdf.conf
配置键