2013-11-22 119 views
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; 
    } 
} 
+0

@Sandhu:我会尝试 –

+0

@Sandhu它有帮助。非常感谢!! –

回答

0

defaultPage()PageFormat通常有一个幅度。您需要使用setImageableArea()方法将其更改为删除边距。

所以我想,加入paper.setImageableArea(0, 0, width, height);将解决这个问题。