java 用Java将数据发送到打印机
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11523583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending data to a printer in Java
提问by Andrew Lynch
The code below sends data to a printer however, while it reaches the printer queue it comes back with a Unable to convert PostScript file.
I thought that this would be overcome by specifying the flavor but this is not the case
下面的代码将数据发送到打印机,当它到达打印机队列时,它返回一个Unable to convert PostScript file.
我认为这可以通过指定风味来克服,但事实并非如此
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 javax.print.attribute.PrintServiceAttribute;
import javax.print.attribute.standard.PrinterName;
public class New1 {
public static void main(String[] args) {
try {
String s = "Hello";
// byte[] by = s.getBytes();
DocFlavor flavor = DocFlavor.STRING.TEXT_PLAIN;
PrintService pservice = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = pservice.createPrintJob();
Doc doc = new SimpleDoc(s, flavor, null);
job.print(doc, null);
} catch (PrintException e) {
e.printStackTrace();
}
}
}
回答by Bruno Braga
Using only JPS you will have problems with Mac. My suggestion is use Java 2 Print API + Java Print Service.
仅使用 JPS 会在 Mac 上出现问题。我的建议是使用 Java 2 Print API + Java Print Service。
Java 2 Print API is something like 1990 style. To avoid to create your code using Java 2 Print API you could use PDFBox http://pdfbox.apache.orgas a framework.
Java 2 Print API 有点像 1990 风格。为避免使用 Java 2 Print API 创建代码,您可以使用 PDFBox http://pdfbox.apache.org作为框架。
With PDFBox you could create a PDF document (http://pdfbox.apache.org/1.8/cookbook/documentcreation.html) but instead of save, print it using that code:
使用 PDFBox,您可以创建一个 PDF 文档(http://pdfbox.apache.org/1.8/cookbook/documentcreation.html),但不是保存,而是使用该代码打印它:
PrinterJob printJob = PrinterJob.getPrinterJob();
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
printJob.setPrintService(service);
document.silentPrint(printJob);
It works fine in my Mac.
它在我的 Mac 上运行良好。