我想下载PDF并打印。我想完全默默地这样做,没有向用户显示对话框。我目前正在使用自签名小程序(在部署时将使用权限进行签名)。它在Linux和OS X上可以正常工作,但不能在Windows上运行。在Windows上,它向用户显示一个用于保存文件的对话框(类型为.xps)。文件保存后,它会以静默方式发送到打印机,因此我的问题是如何在没有用户看到对话的情况下让文档静默保存。代码如下。我正在使用Apache PDFBox。我已经读过我可能需要使用PrivilegedAction,但我不明白为什么因为问题不是我无法下载文件,而是我不能默默地这样做。
/**
* Print Applet
* Author: kareem
* Date: 12-02-20
* Time: 10:57 AM
*/
import java.applet.Applet;
import java.awt.print.PrinterException;
import java.io.*;
import java.net.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import netscape.javascript.*;
public class PrintApplet extends Applet {
public void init() {
String callbackURL = this.getParameter("callbackurl");
String fileToPrint = this.getParameter("file");
String successCallback = this.getParameter("successcallback");
String failureCallback = this.getParameter("failurecallback");
String published = this.getParameter("published");
JSObject window = JSObject.getWindow(this);
if (fileToPrint == null || callbackURL == null) {
window.call(failureCallback, new String[] { "Missing required parameters." });
} else {
try {
URL printURL;
printURL = new URL(fileToPrint);
PDDocument doc;
doc = PDDocument.load(printURL);
doc.silentPrint();
try {
URL updateOrderUrl = new URL(callbackURL);
HttpURLConnection updateOrderHTTP = (HttpURLConnection) updateOrderUrl.openConnection();
updateOrderHTTP.setDoOutput(true);
updateOrderHTTP.setDoInput(true);
updateOrderHTTP.setRequestMethod("PUT");
String updateOrderData = URLEncoder.encode("printed", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(System.currentTimeMillis()/1000) + "&" + URLEncoder.encode("published", "UTF-8") + "=" + URLEncoder.encode(published, "UTF-8"), "UTF-8");
OutputStreamWriter out = new OutputStreamWriter(updateOrderHTTP.getOutputStream());
out.write(updateOrderData);
updateOrderHTTP.getInputStream();
out.close();
window.call(successCallback, null);
} catch(Exception e) {
window.call(failureCallback, new String[] { "Server callback failed." });
}
} catch (MalformedURLException e) {
System.out.println("Malformed URL Exception: " + e.getMessage());
window.call(failureCallback, new String[] { "Invalid print file URL." });
} catch (IOException e) {
System.out.println("IO Exception: " + e.getMessage());
window.call(failureCallback, new String[] { "Print file could not be loaded." });
} catch(PrinterException e) {
System.out.println("Printer exception: " + e.getMessage());
window.call(failureCallback, new String[] { e.getMessage() });
}
}
}
}
答案 0 :(得分:0)
我遇到了同样的问题,并在评论中找到了上面的答案:我们的默认打印机设置为Microsoft XPS文档编写器。
我在这里提到它,任何人都会对评论表示不满,并认为没有答案。
请1up yms的评论而不是这个答案。