[英]Printing String To A Printer Using Java
有人可以帮我编写一个简单的Java程序,该程序可以从打印机中打印出字符串。 我在javaDocs站点上看到了一些示例,但是它们都很长,我什至无法弄清楚将要打印哪个字符串,因为按钮名称,方法名称等都是相同的。 我不介意是否在程序中添加或不添加GUI,自己弄不清楚(也许可以,但是注释会有所帮助)。 PS我的意思是打印纸张的打印机
谢谢。
System.out.println(“帐单打印”);
FileInputStream imagestream=new FileInputStream("C:\\Users\\DELL\\Desktop\\DummyImage.jpg");
DocFlavor doc=DocFlavor.INPUT_STREAM.JPEG;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
//aset.add(MediaSizeName.NA_5X7);
aset.add(Sides.ONE_SIDED);
aset.add(OrientationRequested.PORTRAIT);
Doc document = new SimpleDoc(imagestream, doc, null);
// DocPrintJob job = service.createPrintJob();
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
for (int i = 0; i < services.length; i++) {
System.out.println(services[i].getName());
}
Media[] res1 = (Media[]) services[0].getSupportedAttributeValues(Media.class, null, null);
for (Media media : res1) {
if (media instanceof MediaSizeName) {
MediaSizeName msn = (MediaSizeName) media;
MediaSize ms = MediaSize.getMediaSizeForName(msn);
float width = ms.getX(MediaSize.INCH);
float height = ms.getY(MediaSize.INCH);
System.out.println(media + ": width = " + width + "; height = " + height);
}
}
DocPrintJob job = services[4].createPrintJob();
job.print(document, aset);
我知道这个问题已有4年历史了,但也许有人使用这个简单的解决方案:
String YourString = "first line \n second line \n etc.etc."; //define and set contents of your string - remember about formating with \n if you want to have it split on lines
JTextArea YourTextArea = new JTextArea(); //define new Swing JtextArea
YourTextArea.setLineWrap(true); //set line wrap for YourTextArea - this will prevent too long lines to be cut - they will be wrapaed to next line
YourTextArea.append(YourString); //append YourString to YourTextArea
YourTextArea.print(); //this will display print dialog that will lead you to print contents of YourTextArea so in efect contents of YourString
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.