从文本框打印文本到纸张

时间:2017-09-05 17:11:01

标签: c# winforms printing printdocument

我的new Rectangle()收到了一些编译错误 - 我有一个带有几个用户输入文本框的窗体,还有一个用于打印预览的按钮。按下按钮打印预览时,我希望当前的窗体显示在页面上。我正在尝试编写文本框中的值,以显示在页面下半部分打印的图像正上方的左上方。这是我的语法,但是我遇到了多个编译错误。我设置错误了什么?我觉得将文本从表格形式写入打印文档应该相当简单,但我失败了!

private void btnPreview_Click(object sender, EventArgs e)
{
  PrintPreviewDialog PrintPreviewDlg = new PrintPreviewDialog();

  PrintPreviewDlg.ClientSize = new System.Drawing.Size(400, 300);
  PrintPreviewDlg.Location = new System.Drawing.Point(29, 29);
  PrintPreviewDlg.Name = "PrintPreviewDlg";

  PrintPreviewDlg.MinimumSize = new System.Drawing.Size(375, 250);

  PrintPreviewDlg.WindowState = FormWindowState.Maximized;
  PrintPreviewDlg.UseAntiAlias = true;

  dynamic printData = CreatePrintDocument();
  printData.DefaultPageSettings.Landscape = true;
  PrintPreviewDlg.Document = printData;
  PrintPreviewDlg.ShowDialog();
}

printData CreatePrintDocument()
{
  printData document = new printData();
  document.SetParentCtrl(this);
  document.PrintData.txtAssignmentName = MainInstance.txtAssignmentName.Text;
  document.PrintData.txtAssignmentNumber = MainInstance.txtAssignmentNumber.Text;
  document.PrintData.txtPreparedBy = MainInstance.txtPreparedBy.Text;
  document.PrintData.txtAssignmentSection = MainInstance.txtAssignmentSection.Text;
  document.PrintData.DocumentName = "Testing Print Functionality";

  return document;
}


class printData : PrintDocument
{  
  Size m_SubHeaderTextFieldSize;
  int m_NormalRowHeight = 0;
  class DataToPrintData
  {
      public string txtAssignmentName, txtAssignmentNumber, txtPreparedBy, txtAssignmentSection;
  }
  protected override void OnPrintPage(PrintPageEventArgs e)
  {
    //More print specs here
    int LeftSubHeadingWidth = 200;
    m_SubHeaderTextFieldSize = new Size(LeftSubHeadingWidth, m_NormalRowHeight);
    string printData = "Project Name: " + projectNumberTitle + System.Environment.NewLine +
               "Prepared By: " + txtPreparedBy + System.Environment.NewLine +
               "Assignment Section: " + txtAssignmentSection + System.Environment.NewLine;

    e.Graphics.DrawString(e, new Font("Times New Roman", 12), new SolidBrush(Color.Black), new RectangleF(0,0, m_SubHeaderTextFieldSize, StringAlignment.Near);
  }
}

2 个答案:

答案 0 :(得分:1)

试试这段代码:

var format = new StringFormat {Alignment = StringAlignment.Near};
e.Graphics.DrawString(
    printData, 
    new Font("Times New Roman", 12), 
    new SolidBrush(Color.Black), 
    new RectangleF(new PointF(0, 0), m_SubHeaderTextFieldSize), 
    format);

答案 1 :(得分:0)

new RectangleF(0,0, m_SubHeaderTextFieldSize, StringAlignment.Near)看起来你正在为RectangleF的构造函数提供错误的参数。有2个重载 - 首先接受一个PointF和一个你可以这样调用的大小:
new RectangleF(new PointF(0f,0f), m_SubHeaderTextFieldSize)
另外一个4分,称之为:
new RectangleF(0f,0f, m_SubHeaderTextFieldSize.Width, m_SubHeaderTextFieldSize.Height)
StringAlignment.Neare.Graphics.DrawString函数相关的任何方式......