2012-07-01 21 views

回答

2

是的,這可以做到。爲了讓你的方向正確,你首先需要在你的表單上放置一個PrintDocument,並連接它的BeginPrint和PrintPage事件。爲了讓它工作,你可能想打印預覽而不是打印,所以你還需要一個PrintPreviewDialog,它的Document屬性指向PrintDocument。然後,你可以撥打下列看到打印預覽:

printPreviewDialog1.ShowDialog(); 

我挖下面的代碼從現有的應用程序中。

在你需要制定出電網的總寬度,因此您可以在打印時按比例調整它,沿東西線的BeginPrint處理程序:

totalWidth = 0; 
    foreach (DataGridViewColumn col in dataGridView1.Columns) 
     totalWidth += col.Width; 

在的PrintPage處理程序,首先您需要按照下面的代碼打印列標題。您可能希望將此代碼包含在主循環(下面)中以在每個頁面上打印列標題。

 foreach (DataGridViewColumn col in dataGridView1.Columns) 
     { 
     e.Graphics.DrawString(col.HeaderText, 
      col.InheritedStyle.Font, 
      new SolidBrush(col.InheritedStyle.ForeColor), 
      new RectangleF(l, t, w, h), 
      format); 
     } 

然後你就可以打印每行:

while (row <= dataGridView1.Rows.Count - 1) 
    { 
     DataGridViewRow gridRow = dataGridView1.Rows[row]; 
     { 
     foreach (DataGridViewCell cell in gridRow.Cells) 
     { 
      if (cell.Value != null) 
      { 
      if (cell is DataGridViewTextBoxCell) 
       e.Graphics.DrawString(cell.Value.ToString(), 
        cell.InheritedStyle.Font, 
        new SolidBrush(cell.InheritedStyle.ForeColor), 
        new RectangleF(l, t, w, h), 
        format); 
      else if (cell is DataGridViewImageCell) 
       e.Graphics.DrawImage((Image)cell.Value, 
        new RectangleF(l, t, w, h)); 
      } 
     } 
     } 
     row++; 
    } 

有幾件事情需要注意:

  • 事件處理程序被調用的每一頁。您需要決定頁面何時結束,並在適當的情況下返回e.HasMorePages = true。變量'row'用於知道下一頁上要開始的行。 您可能想要打印單元格邊框
  • 您需要跟蹤要打印的矩形(上面我剛纔提到'l,t,w,h'),以便爲每列調整左邊打印並調整每一行打印的頂部。此外,這是您將單元格寬度乘以e.MarginBounds.Width/totalWidth以縮放每個單元格的位置。
  • 我還沒有做任何事情來保持圖像的縱橫比。

希望這會有所幫助。

相關問題