2013-11-22 23 views
2
private void PrintTextBox(object sender, PrintPageEventArgs e) 
{ 
    e.Graphics.DrawString(textBox1.Text, textBox1.Font, Brushes.Black, 50, 20); 
} 

private void printListButton_Click(object sender, EventArgs e) 
{ 
    PrintDocument pd = new PrintDocument(); 
    pd.PrintPage += PrintTextBox; 
    PrintPreviewDialog ppd = new PrintPreviewDialog(); 
    ppd.Document = pd; 
    ppd.ShowDialog(); 
} 

我嘗試了PrintTextBox方法使用e.HasMorePages == true,但隨後它不斷開始添加頁面。你有什麼想法如何解決它?從文本框中打印多個頁面

回答

1

這是一個經常遇到的問題,e.hasmorepages沒有共同的行爲。 e.hasmorepages會一次又一次地觸發printtextbox,直到你不說(e.hasmorepages = false)。

你必須計算行數,然後計算空間,如果它不適合你的文件喲決定如果文件有更多的頁面或沒有。

我通常使用一個整數來計算我要打印的行數,如果沒有足夠的空間,那麼e.hasmorages = true;

檢查這個簡單的例子,你必須添加system.drawing.printing

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private string[] Lines = new string[10]; 
    private int CurrentRow = 0; 

    private void button1_Click(object sender, EventArgs e) 
    { 
     for (int i = 0; i < 10; i++) 
     { 
      Lines[i] = i.ToString("N2"); 
     } 
     PrintDocument pd=new PrintDocument(); 
     PrintDialog pdi = new PrintDialog(); 
     pdi.ShowDialog(); 
     pd.PrinterSettings = pdi.PrinterSettings; 
     pd.PrintPage += PrintTextBox; 
     pd.Print(); 
    } 

    private void PrintTextBox(object sender, PrintPageEventArgs e) 
    { 
     int y = 0; 

     do 
     { 
      e.Graphics.DrawString(Lines[CurrentRow],new Font("Calibri",10),Brushes.Black,new PointF(0,y)); 
      CurrentRow += 1; 
      y += 20; 
      if (y > 20) // max px per page 
      { 
       e.HasMorePages = CurrentRow != Lines.Count(); // check if you need more pages 
       break; 
      } 
     } while(CurrentRow < Lines.Count()); 
    } 
} 
+0

UpdatemŸ問題一點,你可以檢查什麼的還是錯的? –

+0

問題在於,當您調用e.hasmorapages = true時,您的'i'重新啓動;你必須這樣做:(我更新了你的代碼)。請嘗試它並發表評論 –

+0

它仍然只打印一頁。 –