我正在尝试在 Dymo 打印机上打印由barcode4j 生成的条形码。我的条形码生成器会将条形码作为字节数组提供给我,我将其转换为输入流并将其传递给打印方法。但不知何故,打印机无法正确打印。看起来我需要正确设置 PrintRequestAttributeSet 才能按预期打印。在标签打印机上打印条形码的正确打印属性是什么。这是我的代码。有没有办法在程序中自动检测这个 PrintRequestAttributeSet。
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class HelloWorldPrinter implements Printable, ActionListener {
public static void main(String args[]) throws PrintException, FileNotFoundException {
HelloWorldPrinter hwp = new HelloWorldPrinter();
hwp.printMe();
}
public void printMe() throws PrintException, FileNotFoundException{
Map<String, String> params = new HashMap<String, String>();
params.put("type", "Interleaved2of5");
params.put("msg", "0002221845");
NBPTSBarcodeGenerator nbg = new NBPTSBarcodeGenerator();
InputStream in = new ByteArrayInputStream(nbg.generateBarcode(params).toString().getBytes());
// find the printing service
AttributeSet attributeSet = new HashAttributeSet();
attributeSet.add(new PrinterName("DYMO LabelWriter 450 Turbo", null));
attributeSet.add(new Copies(1));
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(
null, attributeSet);
PrintService pservice = pservices[0];
DocFlavor[] flavors = pservice.getSupportedDocFlavors();
for (int i = 0; i < flavors.length; i++)
{
System.out.println("\t" + flavors);
}
//create document
Doc doc = new SimpleDoc(in, DocFlavor.INPUT_STREAM.PDF, null);
DocPrintJob job = pservice.createPrintJob();
// monitor print job events
PrintJobWatcher watcher = new PrintJobWatcher(job);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(OrientationRequested.PORTRAIT);
aset.add(MediaSizeName.ISO_A6);
System.out.println("Printing...");
job.print(doc, aset);
// wait for the job to be done
watcher.waitForDone();
System.out.println("Job Completed!!");
}
private static void printService(PrintService[] services) {
if (services!=null && services.length>0) {
for (int i = 0; i < services.length; i++) {
System.out.println("t" + services[i]);
}
}
}
class PrintJobWatcher {
boolean done = false;
PrintJobWatcher(DocPrintJob job) {
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
System.out.println("Printing done ...");
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
}