那么您可以通过简单的方式创建一个按钮:
import javax.swing.*;
....
JButton button = new JButton("Print");
然后ActionListener
在按钮上添加一个:
import java.awt.*;
....
button.addActionListener(new ActionListener() {
@override
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
printPDF("path/to/file/.pdf");
}
});
然后要打印 PDF,您可以使用此方法:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
....
public static void printPDF(String file) {
FileInputStream psStream = null;
try {
psStream = new FileInputStream(file);
} catch (FileNotFoundException ffne) {
ffne.printStackTrace();
}
if (psStream == null) {
return;
}
DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc myDoc = new SimpleDoc(psStream, psInFormat, null);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService[] services = PrintServiceLookup.lookupPrintServices(psInFormat, aset);
// this step is necessary because I have several printers configured
PrintService myPrinter = null;
for (int i = 0; i < services.length; i++) {
String svcName = services[i].toString();
System.out.println("service found: " + svcName);
if (svcName.contains("printer closest to me")) {
myPrinter = services[i];
System.out.println("my printer found: " + svcName);
break;
}
}
if (myPrinter != null) {
DocPrintJob job = myPrinter.createPrintJob();
try {
job.print(myDoc, aset);
} catch (Exception pe) {
pe.printStackTrace();
}
} else {
System.out.println("no printer services found");
}
}
附录:
要使其在可能没有“离我最近的打印机”的特定打印机上工作:更改此代码以包含您的打印机名称,或分别使用contains()
or的确切打印机名称equals()
:
String printerName="";
....
if (svcName.contains(printerName)||svcName.equals(printerName)) {
myPrinter = services[i];
System.out.println("my printer found: " + svcName);
break;
}
参考: