我想下载 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() });
}
}
}
}