2010-04-12 138 views
2

我试图打印一个带有一些画图形的JPanel(覆盖paintComponent)。图形非常大,不适合放在单个页面上,因此我让它跨越多个页面。使用java打印时,如何获得纸张的边距?

PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); 
PageFormat pf = printJob.pageDialog(aset); 
printJob.setPrintable(canvas, pf); 

当我在我的JPanel类我不能写我的print()方法(实现打印):我的问题通过调用在于这样的事实,如果我让用户选择的PageFormat /纸张类型中似乎获得了利润率?我使用graphics.translate(pageFormat.getImageableX(), pageFormat.getImageableY());使它开始绘制在正确的全角(0; 0),它考虑了边距(即从(80; 100)左右开始)。但是,它会在底部和右侧边距上打印,因为这会否定用户的愿望,所以我不想这样做。

这里是(使用默认代替)在我的print()方法作为参考,当你没有让用户设置纸张的正常工作的代码:

Rectangle[] pageBreaks; 

    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { 
     //Calculate how many pages our print will be 
     if(pageBreaks == null){ 
      double pageWidth = pageFormat.getPaper().getWidth(); 
      double pageHeight = pageFormat.getPaper().getHeight(); 

      //Find out how many pages we need 
      int numberOfPagesHigh = (int) Math.ceil(size.getHeight()/pageHeight); 
      int numberOfPagesWide = (int) Math.ceil(size.getWidth()/pageWidth); 
      pageBreaks = new Rectangle[numberOfPagesHigh*numberOfPagesWide]; 

      double x = 0; 
      double y = 0; 
      int curXPage = 0; 

      //Calculate what we will print on each page 
      for (int i = 0; i < pageBreaks.length; i++){ 
       double xStart = x; 
       double yStart = y; 
       x += pageWidth; 

       pageBreaks[i] = new Rectangle((int)xStart, (int)yStart, (int)pageWidth, (int)pageHeight); 

       curXPage++; 
       if (curXPage > numberOfPagesWide){ 
        curXPage = 0; 
        x = 0; 
        y += pageHeight; 
       } 
      } 


     } 

     if (pageIndex < pageBreaks.length){ 
      //Cast graphics to Graphics2D for richer API 
      Graphics2D g2d = (Graphics2D) graphics; 

      //Translate into position of the paper 
      g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); 

      //Setup our current page 
      Rectangle rect = pageBreaks[pageIndex]; 

      g2d.translate(-rect.x, -rect.y); 
      g2d.setClip(rect.x, rect.y, rect.width, rect.height); 

      //Paint the component on the graphics object 
      Color oldBG = this.getBackground(); 
      this.setBackground(Color.white); 
      util.PrintUtilities.disableDoubleBuffering(this); 
      this.paintComponent(g2d); 
      util.PrintUtilities.enableDoubleBuffering(this); 
      this.setBackground(oldBG); 

      //Return 
      return PAGE_EXISTS; 
     } 
     else { 
      return NO_SUCH_PAGE; 
     } 
    } 

回答

2

张贴了这个问题后,并回到我的IDE中,我很容易找到答案。除了使用

double pageWidth = pageFormat.getPaper().getWidth(); 
double pageHeight = pageFormat.getPaper().getHeight(); 

使用

double pageWidth = pageFormat.getImageableWidth(); 
double pageHeight = pageFormat.getImageableHeight(); 

getImageableWidth()的返回totalPaperWidth-totalMargins而getWidth()刚刚返回totalPaperWidth。这使得print()方法不会在每个页面上绘制更多!