1

使用这个 java api:http ://docs.oracle.com/javase/6/docs/api/javax/print/package-summary.html

我已尝试根据需要修改此代码,目前我有:

import java.io.FileInputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import java.io.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;

 public class pdfPrinter {

    public static String CompletefileName; // calls from FileUploadController

    public static void main(String args[]) {

        FileInputStream psStream = null;
        try {
            psStream = new FileInputStream(CompletefileName); // this calls a location where the pdf file is stored
        } catch (FileNotFoundException ffne) {
            ffne.printStackTrace();
        }
        if (psStream == null) {
            return;
        }
        DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
        Doc myDoc = new SimpleDoc(psStream, psInFormat, null); // unsure what psStream is, not explained in the api, want to use this to print pdfs, will look at more 
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        PrintService[] services = PrintServiceLookup.lookupPrintServices(psInFormat, aset);
        aset.add(new Copies(5)); //sets copies, will add this as a vairable so users can change this
        aset.add(Sides.DUPLEX); // same as above
        if (myPrinter != null) { // having issues setting myPrinter
            DocPrintJob job = myPrinter.createPrintJob();
            try {
                job.print(myDoc, aset);

            } catch (Exception pe) {
                pe.printStackTrace();
            }
        } else {
            System.out.println("no printer services found"); //error msg
        }
    }
}

目前这无法编译,因为我不知道如何myPrinter在我的机器上设置默认打印机,这也将用于 jsf Web 应用程序,我可以通过在网页上按一下按钮来运行它吗?

这是打印pdf的正确方法吗?任何建议或教程都会非常有帮助

4

2 回答 2

0

我查看了javadoc DocPrintJob,这是一个接口。所以myprinter必须是一个实现该接口的对象。

从那里看来您可以附加打印机:http ://docs.oracle.com/javase/6/docs/api/javax/print/DocPrintJob.html

这可能会有所帮助,因为它提供了一个示例: http ://docs.oracle.com/javase/6/docs/technotes/guides/jps/spec/jpsOverview.fm4.html

于 2013-02-07T14:51:52.203 回答
0

你应该定义为

PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);
PrintService myService = null;
for(PrintService service : services) {
    System.out.println(service.getName());
    if(service.getName().contains(user.getDefaultPrinter())) {
        myService = service;
        break;
    }
}
于 2016-01-18T07:18:13.353 回答