使用此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网络应用程序,我可以通过按下按钮来运行网页?
这是打印pdf的正确方法吗?任何建议或教程都会非常有用
答案 0 :(得分:0)
我查看了DocPrintJob
的javadoc,它是一个接口。所以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
答案 1 :(得分: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;
}
}