C# 打印多页 [英] C# printing multiple pages

查看:122
本文介绍了C# 打印多页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,当我打印一页时工作正常,但是当我尝试打印不适合一页的内容时,它不会开始新页面,它只是接受偏移更改并开始重写第一页.

This is my code, works fine when I print one page, but when I try to print something that doesn't fit onto one page it doesn't start the new page, it just accepts the offset change and starts writing over the first page.

有人知道该怎么做吗?

private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
    Graphics graphic = e.Graphics;

    Font font = new Font("Courier New", 12);
    float fontHeight = font.GetHeight();
    int startX = 10;
    int startY = 10;
    int offset = 0;

    float pageWidth = e.PageSettings.PrintableArea.Width;
    float pageHeight = e.PageSettings.PrintableArea.Height;

    foreach (string line in textRichTextBox.Lines)
    {
        graphic.DrawString(line, font, new SolidBrush(Color.Black), startX, startY + offset);
        offset += (int)fontHeight;// + 5

        if (offset >= pageHeight - (int)fontHeight)
        {
            e.HasMorePages = true;
            offset = 0;
        }
    }
    e.HasMorePages = false;
}

推荐答案

您使用的 API 错误,文档说:

You are using the API wrong, the doc says:

在 PrintPage 事件处理程序中,使用PrintPageEventArgs 类和文档内容计算行每页的长度和行数.绘制完每一页后,检查是否它是最后一页,并设置 HasMorePages 属性PrintPageEventArgs 相应地.PrintPage 事件被引发,直到HasMorePages 为假.另外,请确保 PrintPage 事件是与其事件处理方法相关联.

In the PrintPage event handler, use the Graphics property of the PrintPageEventArgs class and the document contents to calculate line length and lines per page. After each page is drawn, check to see if it is the last page, and set the HasMorePages property of the PrintPageEventArgs accordingly. The PrintPage event is raised until HasMorePages is false. Also, make sure the PrintPage event is associated with its event-handling method.

您不能在循环中设置 HasMorePages,只能在回调退出时设置.回调将被调用,直到您将 HasMorePages 设置为 false

You can't set HasMorePages in a loop, only on exit of the callback. The callback will be called until you set HasMorePages to false

这篇关于C# 打印多页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆