2010-04-12 80 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()方法不會在每個頁面上繪製更多!