PrintServiceLookup.lookupDefaultPrintService() returns null

╄→гoц情女王★ 提交于 2019-12-23 13:59:08

问题


PrintServiceLookup.lookupDefaultPrintService() returns NULL as I have a printer installed and set to default printer.

If I am using this in a simple program it works fine, but when I try to use it in my applet-based program it returns NULL.

Please send me some good solution for this problem.


回答1:


In order to access the printer (or any resource on the host computer for that matter) the jar file in which the applet code resides has to be signed, and the user must accept the signer as a trusted party. To sign the jar file, use the jarsigner program, which is part of he JDK. Jarsigner uses its own keystore, so if you have your own certificate, you must import the certificate to a keystore first. It can generate certificates as well, in the case you don't have any other certificate to sign the jar file with.

Documentation of the jarsigner tool can be found here.

Note that newer Java runtimes do ask the user if (s)he allows the code to access the printer, but I found that regardless of the answer, code in an unsigned jar file is prevented from accessing resources.




回答2:


This code is working in an signed applet in windows with 1.7.0_55:

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;

...

HashDocAttributeSet docAttr=new HashDocAttributeSet();
HashPrintRequestAttributeSet reqAttr=new HashPrintRequestAttributeSet();

try {
    PrintService pserv = PrintServiceLookup.lookupDefaultPrintService();
    if (pserv == null) {
        System.out.println("ERROR-01: no default print service");
    }
    System.out.println("Printer: " + pserv.getName());

    DocPrintJob job = pserv.createPrintJob();
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    String content = makeZplLabel();
    Doc doc = new SimpleDoc(content.getBytes(), flavor, docAttr);

    job.print(doc, reqAttr);

} catch (Exception e) {
    System.out.println("ERROR-02:" + e.getMessage());
}



回答3:


You must change the security settings for java applets first. By default, java applets cannot print.




回答4:


Make sure that printer.conf defines <DefaultPrinter name> instead of <Printer name>. JVM seems to only find a default printer that is defined like this.

This code snippet could help out to quickly verify if it works:

import javax.print.PrintServiceLookup;

public class checkDefaultPrinter {
    public static void main(String[] args) {
        System.out.println(PrintServiceLookup.lookupDefaultPrintService());
    }
}


来源:https://stackoverflow.com/questions/1016372/printservicelookup-lookupdefaultprintservice-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!