我正在尝试将bufferedImage打印到我的打印机。由于某种原因,打印从标签的左边缘开始3英寸,并在第二个标签上连续,而不是仅使用一个标签。 根据我的打印机设置,根本没有边距。 我是否会错过一些东西以便开始打印而没有任何余量? 这是我的代码:
private BufferedImage image;
public void print(int bufWidth, int bufHeight, BufferedImage bufImage, int printerId, String printerName)
{
_log.debugDetailPrefixed("printerHandler", "print()", "ImageWidth", bufImage.getWidth(), "ImageHeight", bufImage.getHeight());
try
{
image = bufImage;
PrinterJob printerJob = getPrinterJob(printerName);
int width = bufImage.getWidth();
int height = bufImage.getHeight();
PageFormat pf = printerJob.defaultPage();
Paper paper = pf.getPaper();
paper.setSize(width, height);
double imageableX = fromCMToPPI(0.1);
double imageableY = fromCMToPPI(0.1);
double imageableWidth = width - fromCMToPPI(0.1);
double imageableHeight = height - fromCMToPPI(0.1);
paper.setImageableArea(imageableX, imageableY, imageableWidth, imageableHeight);
pf.setOrientation(PageFormat.LANDSCAPE);
pf.setPaper(paper);
PageFormat validatePage = printerJob.validatePage(pf);
printerJob.setPrintable(new MyPrintable(), validatePage);
printerJob.print();
}
catch (Exception ex)
{
_log.errorPrefixed("printerTask", "print", "Exception", ex.getMessage());
ex.printStackTrace();
}
}
public static final float DPI = 300;
protected double fromPPItoCM(double dpi) {
return dpi / DPI / 0.393700787;
}
protected double fromCMToPPI(double cm) {
return toPPI(cm * 0.393700787);
}
protected double toPPI(double inch) {
return inch * DPI;
}
public class MyPrintable implements Printable {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int result = NO_SUCH_PAGE;
if (pageIndex < 1) {
Graphics2D g2d = (Graphics2D) graphics;
double width = pageFormat.getImageableWidth();
double height = pageFormat.getImageableHeight();
g2d.translate((int) pageFormat.getImageableX(), (int) pageFormat.getImageableY());
//Get the relation between the label width and image width:
double sx = width /image.getWidth();
//Get the relation between the label height and image height:
double sy = height/image.getHeight();
//Use the relation to scale the image to the printer
g2d.scale(sx,sy);
g2d.drawImage(image, 0, 0, null);
result = PAGE_EXISTS;
}
return result;
}
}
答案 0 :(得分:0)
defaultPage()
PageFormat
通常有保证金。您需要更改它以使用setImageableArea()
方法删除该边距。
所以我想,添加paper.setImageableArea(0, 0, width, height);
将解决问题。