繁体   English   中英

打印bufferedImage的边距为3英寸

[英]Printing a bufferedImage has a margin of 3 inches

我正在尝试将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;
  }
 }

defaultPage() PageFormat通常有一个空白。 您需要使用setImageableArea()方法对其进行更改以删除该边距。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM