简体   繁体   中英

Printing PDF from java

I've looked at a few posts and put together some code to print a .pdf file. However, something is wrong. The program ends without any errors, but it doesn't print anything:

public static void print(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.equals("Win32 Printer : Microsoft XPS Document Writer")){
            myPrinter = services[i];
            System.out.println("Destination 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");
    }
}

I am trying to send the document to Microsoft XPS document writer for testing purposes, but I don't see how that could cause the failure in printing the file.

I would be shocked if this would work. The Java print driver implementations generally just stream the document at the printer. If the printer happens to have native PDF handling capabilities, then it'll print the PDF, but that's a pretty limited subset of all printers (and I can't imagine that the XPS Document Writer print driver has the ability - but who knows, maybe I'm wrong on that).

FWIW, one of our products is a big batch print management system, and we wound up having to drop to native code to reliably print PDF files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM