c# - 从 TextBox 打印多页

标签 c# list printing printdialog

private void PrintTextBox(object sender, PrintPageEventArgs e)
{
    e.Graphics.DrawString(textBox1.Text, textBox1.Font, Brushes.Black, 50, 20);
}

private void printListButton_Click(object sender, EventArgs e)
{
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += PrintTextBox;
    PrintPreviewDialog ppd = new PrintPreviewDialog();
    ppd.Document = pd;
    ppd.ShowDialog();
}

我尝试在 PrintTextBox 方法中使用 e.HasMorePages == true 但随后它不断开始添加页面。您知道如何解决吗?

最佳答案

这是一个经常出现的问题,e.hasmorepages 没有常见的行为。 e.hasmorepages 将一遍又一遍地触发 printtextbox,直到您拒绝 (e.hasmorepages=false)。

你必须计算行数,然后计算空间,如果它不适合你的论文,你决定文档是否有更多的页面。

我通常使用一个整数来计算我将打印的行数,如果没有足够的空间则 e.hasmorages=true;

检查这个更简单的例子,你必须添加 system.drawing.printing

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private string[] Lines = new string[10];
    private int CurrentRow = 0;

    private void button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 10; i++)
        {
            Lines[i] = i.ToString("N2");
        }
        PrintDocument pd=new PrintDocument();
        PrintDialog pdi = new PrintDialog();
        pdi.ShowDialog();
        pd.PrinterSettings = pdi.PrinterSettings;
        pd.PrintPage += PrintTextBox;
        pd.Print();
    }

    private void PrintTextBox(object sender, PrintPageEventArgs e)
    {
        int y = 0;

        do 
        {
            e.Graphics.DrawString(Lines[CurrentRow],new Font("Calibri",10),Brushes.Black,new PointF(0,y));
            CurrentRow += 1;
            y += 20;
            if (y > 20) // max px per page
            {
                e.HasMorePages = CurrentRow != Lines.Count(); // check if you need more pages
                break;
            }
        } while(CurrentRow < Lines.Count());
    }
}

关于c# - 从 TextBox 打印多页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20149377/

相关文章:

javascript - Asp.net 从代码后面添加表单 onsubmit()

c# - 在测试执行期间确定解决方案路径

python - 如何在 python 和 Robot-framework 中对字典进行切片?

java - 为应用程序类创建双向链表

java - java中如何连接字符串

python - 如何在Python中正确地用\n分割输出?

php - 在 php 中打印到 Zebra 打印机

c# - 模型绑定(bind)字典

c# - 如何获取有关磁盘文件系统的信息?

list - 如何对 Prolog 列表的元素执行算术运算