我目前有一個功能,可以使用System.Drawing.Printing.PrintDocument將DataGridView打印到頁面上 - 打印實用程序通過我的打印頁面函數(PrintDoc_PagePrint)直到它用盡行(它將設置HasMorePages爲false)C#PrintDocument:Phantom print來統計總頁數
我試圖計算出打印之前的總頁數,以便我可以將「頁面x的y」放在每個頁面的底部頁。一種方法是計算每頁上有多少行,並根據總共有多少行計算出有多少頁,但這看起來不是很通用,因爲它依賴於每行都是相同的高度,這取決於如何編程,並不總是如此。
我想這樣做的方式是做一個「幻影」打印 - 或基本上打印到一個空的打印機在後臺,而無需用戶知道。當它執行第一次打印時,它可以在每次運行打印功能時增加一個全局變量TotalPages,然後一旦完成幻像打印,停止TotalPages在下次打印時增加(大概只需在幻像打印完成後設置一個bool )。這將更加通用,並且適用於具有不同行高的數據網格,或者我想要打印的任何其他類型的數據。
我的問題是 - 有沒有辦法在後臺運行樣例打印?這是在用戶選擇頁面大小和方向等後完成的,因此我們確實知道這些重要細節,但是在顯示打印預覽對話框之前。
這裏有一些代碼,我有...它的作品,但由於某種原因,它不會一直工作!
// Phantom print to determine number of pages. Writes to TotalPages var.
// The next print won't write to TotalPages when FirstPreviewDone is set to true.
var printEventArgs = new PrintEventArgs();
// Create a graphics object of the page size to "print" to.
int x = 0;
int y = 0;
int width = printDoc.DefaultPageSettings.PaperSize.Width;
int height = printDoc.DefaultPageSettings.PaperSize.Height;
Rectangle marginBoundsRectangle = new Rectangle(x, y, width, height);
Rectangle pageBoundsRectangle = new Rectangle(0, 0, printDoc.DefaultPageSettings.PaperSize.Width, printDoc.DefaultPageSettings.PaperSize.Height);
Bitmap b = new Bitmap(width, height);
// Swap everything if it's in landscape.
if (printDoc.DefaultPageSettings.Landscape)
{
marginBoundsRectangle = new Rectangle(y, x, height, width);
pageBoundsRectangle = new Rectangle(0, 0, printDoc.DefaultPageSettings.PaperSize.Height, printDoc.DefaultPageSettings.PaperSize.Width);
b = new Bitmap(height, width);
}
Graphics graphics = Graphics.FromImage(b);
var printPageEventArgs = new PrintPageEventArgs(graphics, marginBoundsRectangle, pageBoundsRectangle, printDoc.DefaultPageSettings);
printPageEventArgs.HasMorePages = true;
PrintDoc_BeginPrint(null, printEventArgs);
while (printPageEventArgs.HasMorePages && !printPageEventArgs.Cancel)
{
try
{
PrintDoc_PrintPage(null, printPageEventArgs);
}
catch (Exception ex)
{
MessageBoxEx.Show(ex.Message, "Error printing - Check logs", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
我不知道爲什麼我沒有遇到過這個(我曾經搜查過!)工作很好。 – joshhendo