在没有预览的情况下打印RDLC报告,并允许用户选择要在“打印”对话框中打印的页面范围

时间:2018-10-05 14:23:15

标签: c# printing rdlc

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

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

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";
    }
 }
}

1 个答案:

答案 0 :(得分:0)

我终于通过大量研究和反复试验解决了我的问题。我添加/更改了以下内容,该内容允许“所有页面和选定页面范围”。

我在课程开始时添加了m_EndPage。

private static int m_EndPage;

在“公共静态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;
        }