【问题标题】:c# printing a windows form applicationc#打印一个windows窗体应用程序
【发布时间】:2014-08-09 12:08:43
【问题描述】:

我找到了要打印的代码

// The PrintDialog will print the document
// by handling the document's PrintPage event.
private void document_PrintPage(object sender, 
System.Drawing.Printing.PrintPageEventArgs e)
{

    // Insert code to render the page here.
    // This code will be called when the control is drawn.

    // The following code will render a simple
    // message on the printed document.
    string text = "In document_PrintPage method.";
    System.Drawing.Font printFont = new System.Drawing.Font
        ("Arial", 35, System.Drawing.FontStyle.Regular);

    // Draw the content.
    e.Graphics.DrawString(text, printFont, 
        System.Drawing.Brushes.Black, 10, 10);
}


// Declare the PrintDocument object.
private System.Drawing.Printing.PrintDocument docToPrint =
    new System.Drawing.Printing.PrintDocument();

private void printButton_Click(object sender, EventArgs e)
{

    PrintDialog PrintDialog1 = new PrintDialog();
    // Allow the user to choose the page range he or she would
    // like to print.
    PrintDialog1.AllowSomePages = true;

    // Show the help button.
    PrintDialog1.ShowHelp = true;

    // Set the Document property to the PrintDocument for 
    // which the PrintPage Event has been handled. To display the
    // dialog, either this property or the PrinterSettings property 
    // must be set 
    PrintDialog1.Document = docToPrint;

    DialogResult result = PrintDialog1.ShowDialog();

    // If the result is OK then print the document.
    if (result == DialogResult.OK)
    {
        docToPrint.Print();
    }
}

我执行它,打印结果是empty page,我的问题是我可以把数据放在哪里打印?以及如何将打印的数据作为行,每行都有标签和值。

【问题讨论】:

  • 您应该已经看到“在 document_PrintPage 方法中”。首先找出问题所在。
  • @HenkHolterman 我看到一个空白页面
  • 我没有看到任何链接 PrintPage 事件的代码。它可能永远不会触发。
  • @HenkHolterman 我认为这是一个在打印开始时触发的功能或其他什么,请问您有什么建议?添加代码 insdie it to code insdie the button event?

标签: c# .net winforms printing windows-forms-designer


【解决方案1】:

您将 PrintDocument 创建为私有成员:

// Declare the PrintDocument object.
private System.Drawing.Printing.PrintDocument docToPrint =
    new System.Drawing.Printing.PrintDocument();

但这使得很难在正确的时刻附加事件处理程序。我建议使用构造函数:

// Declare the PrintDocument object.
private System.Drawing.Printing.PrintDocument docToPrint; 
     //= new System.Drawing.Printing.PrintDocument();

public Form1()   // the Form ctor
{
   InitializeComponents();
   docToPrint = new System.Drawing.Printing.PrintDocument();
   docToPrint.PrintPage += document_PrintPage; // the missing piece
}

【讨论】:

  • 请回答最后一个问题,我试图在最后添加这个`e.Graphics.DrawString("asdfasdf", valueFont, System.Drawing.Brushes.Red, 10, 10);`,但我保持只有In document_PrintPage method.,而新文本asdfasd 不会添加到打印页面。请帮忙
  • 我只是注意到我得到了值,但它超过了前一个 :( :( 请帮忙
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 1970-01-01
  • 2015-07-13
相关资源
最近更新 更多