有人可以帮我写一个简单的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