有人可以帮忙解决这个问题吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace notepad_demo
{
public partial class Form1 : Form
{
private StringReader myReader;
public Form1()
{
InitializeComponent();
}
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
printDialog1.Document = printDocument1;
string strText = this.richTextBox1.Text;
myReader = new StringReader(strText);
if (printDialog1.ShowDialog() == DialogResult.OK)
{
printDocument1.Print();
}
}
private void printPrieviewToolStripMenuItem_Click(object sender, EventArgs e)
{
string strText = this.richTextBox1.Text;//read text for richtextbox
myReader = new StringReader(strText);
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
string strDisplay = "Header";
System.Drawing.Font fntString = new Font("Times New Roman", 28, FontStyle.Bold);
e.Graphics.DrawString(strDisplay, fntString, Brushes.Black, 100, 100);
string strDisplay1 = "Company name";
System.Drawing.Font fntString1 = new Font("Times New Roman", 28, FontStyle.Bold);
e.Graphics.DrawString(strDisplay1, fntString1, Brushes.Black, 100, 150);
float linesPerPage = 0;
float yPosition = 590;
int count = 0;
float leftMargin = 70;
float topMargin = 590;
string line = null;
Font printFont = new System.Drawing.Font("Times New Roman", 8, FontStyle.Regular);
SolidBrush myBrush = new SolidBrush(Color.Black);
linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);
while (count < linesPerPage && ((line = myReader.ReadLine()) != null))
{
yPosition = topMargin + (count * printFont.GetHeight(e.Graphics));
e.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
count++;
}
if (line != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
myBrush.Dispose();
}
}
}
在附图中,第一页正常,但第2页,第3页和第4页也与第一页相同。 我希望页眉和公司名称只在第一页上,而`RichTextBox.text``则打印在第二页的上边缘。
我的错误在哪里?
答案 0 :(得分:0)
要解决在每个页面上打印标题的问题,请按照Hans Passant
在评论部分中提出的问题here提出问题。
简而言之,它正在创建一个名为pageCount
的类变量,当您开始打印时将其设置为0,并在打印每页时将其递增。
将页眉部分写入页面的部分应该封装在条件语句中,当您在第一页以外的任何页面上打印时,该条件语句将不会被执行。
要解决第二个问题,即使在第二页上,您的文字也会在页面下方打印得很远,这是因为您要在topMargin
事件中将PagePrint
变量始终初始化为590。
您应该做的是将其初始化到页面顶部(打印标题的位置),然后根据您当前打印的页面进行调整。
例如。对于第一页打印顶部边距的标题,并在打印不同的标题和标签时递增topMargin
变量。然后,当您到达第二页时,只需将topMargin
变量与您正在打印的每个标签/行的高度相加(就像您当前在循环中所做的那样)。
您已经对变量yPosition
已经有了这个想法,您只需要为您正在打印的所有内容完全实现它,而不仅仅是标签。