[英]How i can print a pdf
我想打印pdf,但是我尝试过的所有解决方案均无法正常工作。
我想用弹出窗口打印pdf,您可以在其中选择打印机。
当我尝试其他人的解决方案时,这通常是通过静默打印进行的。
我尝试这个:
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
PrintRequestAttributeSet patts = new HashPrintRequestAttributeSet();
patts.add(Sides.DUPLEX);
PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor, patts);
if (ps.length == 0) {
throw new IllegalStateException("No Printer found");
}
System.out.println("Available printers: " + Arrays.asList(ps));
PrintService myService = null;
for (PrintService printService : ps) {
if (printService.getName().equals("HP Deskjet 3070 B611 series")) {
myService = printService;
break;
}
}
FileInputStream fis = new FileInputStream(path_doss);
Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
DocPrintJob printJob = myService.createPrintJob();
printJob.print(pdfDoc, new HashPrintRequestAttributeSet());
fis.close();
这个
FileInputStream fis = new FileInputStream(path_doss);
Doc pdfDoc = new SimpleDoc(fis, null, null);
DocPrintJob printJob = printService.createPrintJob();
printJob.print(pdfDoc, new HashPrintRequestAttributeSet());
fis.close();
提前致谢 !
您可以利用Scanner与用户进行交互。
System.out.print("Please select one of the printers numbers: 1. Printer1, 2.Printer2 etc");
Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine();
然后使用该输入从您的列表中选择打印机并进行打印。
使用ServiceUI显示打印选择对话框。
如果您已有一个窗口(例如JFrame),则应使用它来确定前三个参数。 第四个和第五个参数来自PrintServiceLookup调用。
因此,典型的调用可能如下所示:
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
if (defaultService == null) {
defaultService = ps[0];
for (PrintService printService : ps) {
if (printService.getName().equals("HP Deskjet 3070 B611 series")) {
defaultService = printService;
break;
}
}
}
PrintService myService = ServiceUI.printDialog(
mainWindow.getGraphicsConfiguration(),
mainWindow.getX() + 40,
mainWindow.getY() + 40,
ps, defaultService, flavor, patts);
if (myService == null) {
System.out.println("User canceled print operation.");
return;
}
如果没有应用程序窗口,则可以为第一个参数传递null。 没有(简单)的方法可以知道打印对话框的大小,因此对于第二和第三个参数,您必须进行猜测。 例如:
Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
PrintService myService = ServiceUI.printDialog(
null, center.x - 200, center.y - 200,
ps, defaultService, flavor, patts);
尝试过此操作后,将打开您要打印的文件,然后您可以选择打印机来选择打印。
Desktop.getDesktop().open(new File("c:/test.pdf"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.