在不预览的情况下打印 RDLC 报告并允许用户 Select 打印对话框中的页面范围

Printing RDLC Report Without Preview and Allowing User to Select a Page Range to Print in Print Dialog

我有一份 rdlc 报告,我为用户提供了在报告查看器中预览报告或打印报告而不预览的选项。在报表查看器中,用户可以在查看器中打印时选择要打印的页面范围。在没有查看器的情况下打印时,即使用户 select 在打印对话框中设置了一个页面范围,也会打印整个报表。在没有 reportviewer 的情况下打印时,是否可以 select 在打印对话框中打印一个页面范围?

在 window 表单中,我有一个带有点击事件的打印按钮:

private void button1_Click(object sender, EventArgs e)
{
   var message = "Do you wish to preview the report before printing?";
   var title = "Preview Report";
   DialogResult dg = MessageBox.Show(message, title, 
   MessageBoxButtons.YesNo);
        if (dg == DialogResult.Yes)
        {

            MainBatchListPreview mbp = new MainBatchListPreview();

            mbp.Show();
        }
        else if (dg == DialogResult.No)
        {
            LocalReport report = new LocalReport();
            report.ReportEmbeddedResource = 
            "Toolbar.Reports.MainBatchList.rdlc";
            report.DataSources.Add(new ReportDataSource("DataSet1", 
            dataGridView1.DataSource));

            report.PrintToPrinter();
        }
    }

然后我使用以下 Class 在没有报表查看器的情况下打印:

namespace Toolbar
{
public static class PrintWithoutReportViewer
{
    private static int m_CurrentPageIndex;
    private static IList<Stream> m_Streams;
    private static PageSettings m_PageSettings;



    public static Stream CreateStream(string name, string fileNameExtension, 
    Encoding encoding, string mimeType, bool willSeek)
    {
        Stream stream = new MemoryStream();
        m_Streams.Add(stream);
        return stream;
    }



    public static void Export(LocalReport report, bool print = true)
    {
        PaperSize paperSize = m_PageSettings.PaperSize;
        Margins margins = m_PageSettings.Margins;

        // The device info string defines the page range to print as well as the size of the page.
        // A start and end page of 0 means generate all pages.
        string deviceInfo = string.Format(
            CultureInfo.InvariantCulture,
            "<DeviceInfo>" +
            "<OutputFormat>EMF</OutputFormat>" +
            "<PageWidth>{5}</PageWidth>" +
            "<PageHeight>{4}</PageHeight>" +
            "<MarginTop>{0}</MarginTop>" +
            "<MarginLeft>{1}</MarginLeft>" +
            "<MarginRight>{2}</MarginRight>" +
            "<MarginBottom>{3}</MarginBottom>" +
            "</DeviceInfo>",
            ToInches(margins.Top),
            ToInches(margins.Left),
            ToInches(margins.Right),
            ToInches(margins.Bottom),
            ToInches(paperSize.Height),
            ToInches(paperSize.Width));

        Warning[] warnings;
        m_Streams = new List<Stream>();
        report.Render("Image", deviceInfo, CreateStream,
            out warnings);
        foreach (Stream stream in m_Streams)
            stream.Position = 0;

        if (print)
        {
            PrintDialog printDlg = new PrintDialog();
            PrintDocument printDoc = new PrintDocument();
            printDoc.DocumentName = "Report";
            printDlg.Document = printDoc;
            printDlg.AllowSelection = true;
            printDlg.AllowSomePages = true;

            //Call ShowDialog

            if (printDlg.ShowDialog() == DialogResult.OK)

                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            m_CurrentPageIndex = 0;
            printDoc.Print();

        }
    }

    public static void RenderingCompleteEventHandler(object sender, RenderingCompleteEventArgs e)
    {

        PrintDialog startPrint = new PrintDialog();
        startPrint.ShowDialog();

    }

    // Handler for PrintPageEvents
    public static void PrintPage(object sender, PrintPageEventArgs e)
    {
        Stream pageToPrint = m_Streams[m_CurrentPageIndex];
        pageToPrint.Position = 0;

        // Load each page into a Metafile to draw it.
        using (Metafile pageMetaFile = new Metafile(pageToPrint))
        {
            Rectangle adjustedRect = new Rectangle(
                    e.PageBounds.Left - (int)e.PageSettings.HardMarginX,
                    e.PageBounds.Top - (int)e.PageSettings.HardMarginY,
                    e.PageBounds.Width,
                    e.PageBounds.Height);

            // Draw a white background for the report
            e.Graphics.FillRectangle(Brushes.White, adjustedRect);

            // Draw the report content
            e.Graphics.DrawImage(pageMetaFile, adjustedRect);

            // Prepare for next page.  Make sure we haven't hit the end.
            m_CurrentPageIndex++;
            e.HasMorePages = m_CurrentPageIndex < m_Streams.Count;
        }
    }

    public static void Print()
    {
        if (m_Streams == null || m_Streams.Count == 0)
            throw new Exception("Error: no stream to print.");
        PrintDocument printDoc = new PrintDocument();
        if (!printDoc.PrinterSettings.IsValid)
        {
            throw new Exception("Error: cannot find the default printer.");
        }
        else
        {
            printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            m_CurrentPageIndex = 0;
            printDoc.Print();
        }
    }

    public static void PrintToPrinter(this LocalReport report)
    {
        m_PageSettings = new PageSettings();
        ReportPageSettings reportPageSettings = report.GetDefaultPageSettings();

        m_PageSettings.PaperSize = reportPageSettings.PaperSize;
        m_PageSettings.Margins = reportPageSettings.Margins;

        Export(report);
    }


    public static void DisposePrint()
    {
        if (m_Streams != null)
        {
            foreach (Stream stream in m_Streams)
                stream.Close();
            m_Streams = null;
        }
    }

    private static string ToInches(int hundrethsOfInch)
    {
        double inches = hundrethsOfInch / 100.0;
        return inches.ToString(CultureInfo.InvariantCulture) + "in";
    }
 }
}

通过大量研究和反复试验,我终于解决了我的问题。我 added/changed 以下允许 "all pages and selected page range".

我在class的开头添加了m_EndPage。

private static int m_EndPage;

在"public static void Export()"

if (result == DialogResult.OK)
            {

                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);

                m_CurrentPageIndex = 0;

                page = printDoc.PrinterSettings.FromPage-1;
                m_EndPage = printDoc.PrinterSettings.ToPage - 1;
                m_CurrentPageIndex = page;

                printDoc.Print();
            }

下面我在最后添加了if语句。

public static void PrintPage(object sender, PrintPageEventArgs e)
    {
        Stream pageToPrint = m_Streams[m_CurrentPageIndex];
        pageToPrint.Position = 0;

        // Load each page into a Metafile to draw it.
        using (Metafile pageMetaFile = new Metafile(pageToPrint))
        {
            Rectangle adjustedRect = new Rectangle(
                    e.PageBounds.Left - (int)e.PageSettings.HardMarginX,
                    e.PageBounds.Top - (int)e.PageSettings.HardMarginY,
                    e.PageBounds.Width,
                    e.PageBounds.Height);

            // Draw a white background for the report
            e.Graphics.FillRectangle(Brushes.White, adjustedRect);

            // Draw the report content
            e.Graphics.DrawImage(pageMetaFile, adjustedRect);

            // Prepare for next page.  Make sure we haven't hit the end.

            m_CurrentPageIndex++;

            e.HasMorePages = m_CurrentPageIndex < m_Streams.Count;

            if (m_CurrentPageIndex > m_EndPage) e.HasMorePages = false;
        }