我正在开发一个可打印文件的Java小程序.
小程序是“自签名的”.
打印功能为:
//argFilePath : path to file (http://localhost/Teste/pdf1.pdf)
//argPrintService : something like PrintServiceLookup.lookupDefaultPrintService()
private int print(String argFilePath, PrintService argPrintService){
try
{
DocPrintJob printJob = argPrintService.createPrintJob();
Doc doc;
DocAttributeSet docAttrSet = new HashDocAttributeSet();
PrintRequestAttributeSet printReqAttr = new HashPrintRequestAttributeSet();
URL url = new URL(argFilePath);
doc = new SimpleDoc(url.openStream(), DocFlavor.INPUT_STREAM.AUTOSENSE, docAttrSet);
printJob.print(doc, printReqAttr);
} catch (Exception e) {
System.out.println(e);
return 1;
}
return 0;
}
尝试打开文件时出现此异常:
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:80 connect,resolve)
HTML / JavaScrip
<input onclick="alert(document.getElementById('xpto').print('http://localhost/Teste/pdf1.pdf'));" type="button"/>
<applet width="180" height="120" code="printers.class" id="xpto" archive="printerAPI.jar"></applet>
正确使用:
DocFlavor.INPUT_STREAM.AUTOSENSE
这个想法似乎是要打印尽可能多的文件类型-pdf,docx,jpg等.
您如何解决该异常?
解决方法:
找到了答案(关于*哈哈:D)!
看来问题出在:
“javascript does not have file access permissions”
因此小程序被阻止.我们必须使用
AccessController.doPrivileged()
这是我的实现:
private int print(String argFilePath, PrintService argPrintService){
cPrint cP = new cPrint(argFilePath, argPrintService);
return (Integer) AccessController.doPrivileged(cP);
}
class cPrint implements PrivilegedAction<Object> {
String FilePath;
PrintService PrintService;
public cPrint(String argFilePath, PrintService argPrintService) {
this.FilePath = argFilePath;
this.PrintService = argPrintService;
};
public Object run() {
// privileged code goes here
try
{
DocPrintJob printJob = PrintService.createPrintJob();
Doc doc;
DocAttributeSet docAttrSet = new HashDocAttributeSet();
PrintRequestAttributeSet printReqAttr = new HashPrintRequestAttributeSet();
URL url = new URL(FilePath);
doc = new SimpleDoc(url.openStream(), DocFlavor.INPUT_STREAM.AUTOSENSE, docAttrSet);
printJob.print(doc, printReqAttr);
} catch (Exception e) {
System.out.println(e);
return 1;
}
return 0;
}
}