Print multiple pages from TextBox

大兔子大兔子 提交于 2019-12-24 00:45:50

问题


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();
}

I tried in PrintTextBox method using the e.HasMorePages == true but then it continously started to add pages. Do you have any idea how to solve it?


回答1:


This is a often problem, e.hasmorepages has not a common behavior. e.hasmorepages will fire printtextbox over and over again until you say not to (e.hasmorepages=false).

you have to count the lines, then calculate the space, and if it does not fit in your paper yo decide if document have more pages or does not.

I normally use an integer that counts the lines I will print, if not enough space then e.hasmorages=true;

Check this easier example, you have to add 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());
    }
}


来源:https://stackoverflow.com/questions/20149377/print-multiple-pages-from-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!