我不知道这个标题是否真的解释了我的问题。我有一个认知标签打印机,我打印条形码和一些文本。标签是4“x2”标签。问题是图像从标签的左侧打印大约一英寸,距离页面顶部大约半英寸。由于某种原因,页面尺寸似乎已关闭,我无法弄清楚导致这种情况的原因。任何帮助都会很棒。这是我正在编写的PrintService类的完整代码。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.print.*;
import java.awt.image.BufferedImage;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import net.sourceforge.barbecue.*;
public class PrintService implements Printable {
BufferedImage bi;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
PrintService printService = new PrintService(args);
}
PrintService(String[] args) {
switch(new Integer(args[0])) {
case 1: printPackageLabel(args[1]); break;
default:
}
}
private void printPackageLabel(String barcode) {
bi = getBarcode(barcode);
//-- Create a printerJob object
PrinterJob printJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = printJob.defaultPage();
Paper paper = new Paper();
//-- 4" x 2"
paper.setSize(288,144);
//-- x,y,width,height
paper.setImageableArea(0, 0, 200, 110);
pageFormat.setPaper(paper);
//-- Set the printable class to this one since we
//-- pass in the PageFormat object
printJob.setPrintable(this, pageFormat);
//PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();
//attr_set.add(new MediaSize(0,0, 292));
//-- disable print dialog
//if (printJob.printDialog()) {
try {
printJob.print();
} catch (Exception PrintException) {
PrintException.printStackTrace();
}
//}
}
private BufferedImage getBarcode (String data) {
Barcode barcode = null;
BufferedImage bufferedImage = null;
try {
barcode = BarcodeFactory.createCode128(data);
barcode.setBarWidth(1);
barcode.setBarHeight(20);
barcode.setDrawingText(true);
} catch (BarcodeException e) {
throw new RuntimeException(e);
}
try {
bufferedImage = BarcodeImageHandler.getImage(barcode);
} catch (Exception e) {
throw new RuntimeException(e);
}
return bufferedImage;
}
public int print(Graphics g, PageFormat pageFormat, int page) {
if (page == 0) {
g.setColor(Color.black);
//-- Prints a box aroung the imageable area
//-- start(x1,y1),stop(x2,y2)
g.drawLine(0,0,200,0);
g.drawLine(0,0,0,110);
g.drawLine(0,110,200,110);
g.drawLine(200,0,200,110);
//-- image,offset(x,y),dimensions(width,height), imageObserver null
g.drawImage(bi,5,5,150,50,null);
//-- identify top left corner - to be removed
g.drawOval(0, 0, 10, 10);
//-- string, x, y
g.drawString("<Item>",5,65);
g.drawString("<Type>",5,75);
g.drawString("<Weight>",5,85);
g.drawString("Packaged: <DateTime>",5,95);
return (PAGE_EXISTS);
} else
return (NO_SUCH_PAGE);
}
}