2013-01-10 19 views
1

我下面的MSDN的「如何」上打印多頁文檔:How to: Print a Multi-Page Text File in Windows FormsMSDN的多頁打印例子似乎並沒有正常工作

我打開該網頁上的例子到一個項目(試Visual Studio 2010和2012),並發現它在打印少量頁面時按預期工作,但是當打印大量頁面(大約9頁)時,它會將開始頁面渲染爲空白頁面(第一頁和第二頁爲空)接下來的15個是正確的,等等)。

任何人都可以證實此行爲?我沒有看到可能造成這種情況的原因,也沒有發生任何異常情況。

編輯:我收到了2個downvotes,但我不知道爲什麼。我會試圖更加清楚。這裏是我認爲包含的問題的代碼部分:

private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) 
{ 
    int charactersOnPage = 0; 
    int linesPerPage = 0; 

    // Sets the value of charactersOnPage to the number of characters 
    // of stringToPrint that will fit within the bounds of the page. 
    e.Graphics.MeasureString(stringToPrint, this.Font, 
     e.MarginBounds.Size, StringFormat.GenericTypographic, 
     out charactersOnPage, out linesPerPage); 

    // Draws the string within the bounds of the page 
    e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black, 
     e.MarginBounds, StringFormat.GenericTypographic); 

    // Remove the portion of the string that has been printed. 
    stringToPrint = stringToPrint.Substring(charactersOnPage); 

    // Check to see if more pages are to be printed. 
    e.HasMorePages = (stringToPrint.Length > 0); 
} 

我不相信任何數據類型正在溢出。我試過用不同的打印機,但每個都有相同的結果。請留下評論,如果你downvote讓我知道爲什麼問題有問題。 注意:我試過.NET Framework 4和4.5,結果相同。

+0

注意:我已經在多臺計算機和操作系統上嘗試了這種方法,結果相同。 – Coder6841

+0

注意:我已經嘗試了.NET Framework 4和4.5,結果相同。 – Coder6841

回答

1

似乎MSDN示例不能正常工作。這可能是由於MarginBounds矩形是基於整數而不是基於浮點的。將Y位置跟蹤爲浮動,並在MeasureString和DrawString方法內使用此值可解決問題。我通過檢查different MSDN printing example發現了這一點。

下面是相關代碼:

private void pd_PrintPage(object sender, PrintPageEventArgs ev) 
{ 
    float linesPerPage = 0; 
    float yPos = 0; 
    int count = 0; 
    float leftMargin = ev.MarginBounds.Left; 
    float topMargin = ev.MarginBounds.Top; 
    string line = null; 

    // Calculate the number of lines per page. 
    linesPerPage = ev.MarginBounds.Height/
     printFont.GetHeight(ev.Graphics); 

    // Print each line of the file. 
    while (count < linesPerPage && 
     ((line = streamToPrint.ReadLine()) != null)) 
    { 
     yPos = topMargin + (count * 
      printFont.GetHeight(ev.Graphics)); 
     ev.Graphics.DrawString(line, printFont, Brushes.Black, 
      leftMargin, yPos, new StringFormat()); 
     count++; 
    } 

    // If more lines exist, print another page. 
    if (line != null) 
     ev.HasMorePages = true; 
    else 
     ev.HasMorePages = false; 
} 

此不考慮像前面的例子中自動換行,但可以相對容易地實現。

相關問題