如何使用javax打印打印pdf?

时间:2016-11-29 12:38:01

标签: java printing

为什么以下代码没有打印任何内容?请帮忙。我尝试更改doc flavor,打印请求属性。它是一个打印pdf文件的简单java文件。如果你想看pdf,这里是link to the repo。我已经安装了所有驱动程序,可以使用其他程序(如reader和firefox)打印相同的pdf文件。

import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import java.io.*;
import java.util.*;

class PrintPdf {

  static String label = "HP DeskJet 5810 series"; // change this to your printer name

  public static void main (String [] args) throws Exception
  {
    // DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF; // not working
    // DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; // not working
    // DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE; // not working
    DocFlavor flavor = new DocFlavor.INPUT_STREAM("application/octet-stream");
    PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
    // attr.add(Sides.DUPLEX); // not working
    // attr.add(MediaSize.ISO.A4); // not working
    PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor, attr);
    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(label)) {
          myService = printService;
        break;
      }
    }

    if (myService == null) {
        throw new IllegalStateException("Printer not found");
    }

    FileInputStream fis = new FileInputStream("./example.pdf");
    Doc pdfDoc = new SimpleDoc(fis, flavor, null);
    DocPrintJob printJob = myService.createPrintJob();
    printJob.print(pdfDoc, new HashPrintRequestAttributeSet());
    fis.close();
  }
}

这是会发生什么,等待几秒钟后Java Printing作业从队列中消失而不打印任何内容

enter image description here

0 个答案:

没有答案