2
我試圖將一個bufferedImage打印到我的打印機。出於某種原因,打印從標籤的左邊緣開始3英寸,並連續放在第二個標籤上,而不是僅使用一個標籤。 根據我的打印機設置,根本沒有邊距。 我是否錯過了某些東西以便在沒有任何邊距的情況下開始打印? 這裏是我的代碼:打印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;
}
}
@Sandhu:我會嘗試 –
@Sandhu它有幫助。非常感謝!! –