即使已将Java策略设置为允许打印,Applet也无法打印

时间:2012-03-06 15:55:41

标签: java php printing applet silent

我有一个使用PHP的Web应用程序。其中一项功能是直接将收据打印到两台或多台打印机,而不会提示打印机对话框。我已经将applet编码如下,它直接打印到代码中指定的任何打印机。

import javax.swing.JApplet;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.print.PrintService;
import com.sun.pdfview.PDFFile;
import javax.swing.JOptionPane;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;

public class PDFApplet extends JApplet {
    private PrinterJob pjob = null;
    //Called when this applet is loaded into the browser.
    public void init() {
        try { 
            FileInputStream fis = new FileInputStream("C:\\app\\receipt.pdf");
            byte[] pdfContent = new byte[fis.available()];
            fis.read(pdfContent, 0, fis.available());
            initialize(pdfContent, "Test Print PDF");

            //PDFApplet printPDFFile = new PDFApplet(fis, "Test Print PDF");
            print();
        } catch (Exception e) {}
    }

    private void initialize(byte[] pdfContent, String jobName) throws IOException, PrinterException {
        ByteBuffer bb = ByteBuffer.wrap(pdfContent);
        // Create PDF Print Page
        PDFFile pdfFile = new PDFFile(bb);
        PDFPrintPage pages = new PDFPrintPage(pdfFile);

        // Create Print Job
        pjob = PrinterJob.getPrinterJob();
        PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
        pjob.setJobName(jobName);
        Book book = new Book();
        book.append(pages, pf, pdfFile.getNumPages());
        pjob.setPageable(book);

        // to remove margins
        Paper paper = new Paper();
        paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
        pf.setPaper(paper);
    }

    public void print() throws PrinterException {
        String argPrintServiceName = "HP LaserJet Professional P1102";

        // Send print job to default printer
        PrintService[] printServices = PrinterJob.lookupPrintServices();
        int i;
        for (i = 0; i < printServices.length; i++) {
                if (printServices[i].getName().equalsIgnoreCase(argPrintServiceName)) {
                pjob.setPrintService(printServices[i]);
                break;
            }
        }
        if (i == printServices.length) {
            //throw new PrinterException("Invalid print service name: " + argPrintServiceName);
            JOptionPane.showMessageDialog(this, "Cannot print to " + argPrintServiceName);
        }

        pjob.print();
    }    
}

然而,当我将它嵌入到html页面中时,applet不再打印了。我已经为java.policy添加了必要的打印权限,但它仍然无法打印。我怎么能解决这个问题,因为它已经花了我一周左右的时间。

谢谢, 萨姆

1 个答案:

答案 0 :(得分:0)

使用由受信任机构(例如Verisign)验证的证书对applet进行数字签名。它将提示用户,他们可以选择“始终信任”,然后小程序将能够自动打印&amp;没有进一步的用户干预(假设代码没有调用打印对话框)。