Click here to Skip to main content
15,867,777 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I created a .rdlc report using VB.NET and now I want to print this report without any preview... please, can anyone help me?
Posted
Updated 23-Aug-17 17:49pm
v2

Maybe the following might be useful:

http://msdn.microsoft.com/en-us/library/ms252091.aspx[]
 
Share this answer
 
Comments
Soft009 8-Jun-10 7:13am    
thanx.....
Adding on to the solution, to print directly to default printer

Usage
C#
PrintRDLCReport.PrintToPrinter



C#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Globalization;
using System.IO;
using System.Text;
using Microsoft.Reporting.WinForms;

namespace AHS_EMRReprint.Controllers
{
    public static class PrintRDLCReport {

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


        // 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";
        }
    }
}
 
Share this answer
 
Comments
Allan Chong 24-Aug-17 3:26am    
Someone may be looking for the answer, I was and i figured it out with his solution

Downvoting me like this when I gave a working answer makes you happy? lol

Kats2512 24-Aug-17 10:37am    
it already has been answered 7 years ago.
Destiny777 5-Jun-19 12:13pm    
Thank you for the additional information.
I had similar problem and solved it by changing the dimensions of the page.
 
Share this answer
 
Comments
CHill60 8-May-14 13:20pm    
Changing the dimensions of the page will not print without preview - which was the original post 4 years ago. If you are trying to respond to a comment use the Reply link next to that comment
C#
class ReportPrintDocument : System.Drawing.Printing.PrintDocument
    {
        private PageSettings m_pageSettings;
        private int m_currentPage;
        private List<stream> m_pages = new List<stream>();

        private static Dictionary<string,> ReportingExtensions;


        public ReportPrintDocument(ServerReport serverReport)
            : this((Report)serverReport)
        {
            RenderAllServerReportPages(serverReport);
        }

        public ReportPrintDocument(LocalReport localReport, string filePath)
            : this((Report)localReport)
        {
            ReportingExtensions = new Dictionary<string,>();
            ReportingExtensions.Add(".XLS", "Excel");
            ReportingExtensions.Add(".XLSX", "Excel");
            ReportingExtensions.Add(".PDF", "PDF");
            ReportingExtensions.Add(".TIF", "Image");

            RenderAllLocalReportPages(localReport, filePath);
        }
        
        private ReportPrintDocument(Report report)
        {
            // Set the page settings to the default defined in the report
            ReportPageSettings reportPageSettings = report.GetDefaultPageSettings();

            // The page settings object will use the default printer unless
            // PageSettings.PrinterSettings is changed.  This assumes there
            // is a default printer.
            m_pageSettings = new PageSettings();
            m_pageSettings.PaperSize = reportPageSettings.PaperSize;
            m_pageSettings.Margins = reportPageSettings.Margins;
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                foreach (Stream s in m_pages)
                {
                    s.Dispose();
                }

                m_pages.Clear();
            }
        }

        protected override void OnBeginPrint(PrintEventArgs e)
        {
            base.OnBeginPrint(e);

            m_currentPage = 0;
        }

        protected override void OnPrintPage(PrintPageEventArgs e)
        {
            base.OnPrintPage(e);

            Stream pageToPrint = m_pages[m_currentPage];
            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_currentPage++;
                e.HasMorePages = m_currentPage < m_pages.Count;
            }
        }
        
        protected override void OnQueryPageSettings(QueryPageSettingsEventArgs e)
        {
            e.PageSettings = (PageSettings)m_pageSettings.Clone();
        }

        private void RenderAllServerReportPages(ServerReport serverReport)
        {
            string deviceInfo = CreateEMFDeviceInfo();

                       NameValueCollection firstPageParameters = new NameValueCollection();
            firstPageParameters.Add("rs:PersistStreams", "True");

            // GetNextStream returns the next page in the sequence from the background process
            // started by PersistStreams.
            NameValueCollection nonFirstPageParameters = new NameValueCollection();
            nonFirstPageParameters.Add("rs:GetNextStream", "True");

            string mimeType;
            string fileExtension;
            Stream pageStream = serverReport.Render("IMAGE", deviceInfo, firstPageParameters, out mimeType, out fileExtension);

            // The server returns an empty stream when moving beyond the last page.
            while (pageStream.Length > 0)
            {
                m_pages.Add(pageStream);

                pageStream = serverReport.Render("IMAGE", deviceInfo, nonFirstPageParameters, out mimeType, out fileExtension);
            }
        }

        private void RenderAllLocalReportPages(LocalReport localReport, string filePath)
        {
            string extension = Path.GetExtension(filePath);
            string format = "";
            if (ReportingExtensions.ContainsKey(extension.ToUpper()))
            {
                format = ReportingExtensions[extension.ToUpper()];
            }
            else
            {
                format = ReportingExtensions[".TIF"];
            }
            string deviceInfo = CreateEMFDeviceInfo();
            string mimeType = null;
            string encoding = null;
            string fileNameExtension = null;
            string[] stream = null;
            Warning[] warnings;
            var list = localReport.ListRenderingExtensions();
            //localReport.Render("IMAGE", deviceInfo, LocalReportCreateStreamCallback, out warnings);
            Byte[] bytes = localReport.Render(format, null, out mimeType, out encoding, out fileNameExtension, out stream, out warnings);
            FileStream fs = new FileStream(filePath, FileMode.Create);
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
        }

        private Stream LocalReportCreateStreamCallback(
            string name,
            string extension,
            Encoding encoding,
            string mimeType,
            bool willSeek)
        {
            MemoryStream stream = new MemoryStream();
            m_pages.Add(stream);

            return stream;
        }

        private string CreateEMFDeviceInfo()
        {
            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.
            return string.Format(
                CultureInfo.InvariantCulture,
                "<deviceinfo><outputformat>emf</outputformat><startpage>0</startpage><endpage>0</endpage><margintop>{0}</margintop><marginleft>{1}</marginleft><marginright>{2}</marginright><marginbottom>{3}</marginbottom><pageheight>{4}</pageheight><pagewidth>{5}</pagewidth></deviceinfo>",
                ToInches(margins.Top),
                ToInches(margins.Left),
                ToInches(margins.Right),
                ToInches(margins.Bottom),
                ToInches(paperSize.Height),
                ToInches(paperSize.Width));
        }

        private static string ToInches(int hundrethsOfInch)
        {
            double inches = hundrethsOfInch / 100.0;
            return inches.ToString(CultureInfo.InvariantCulture) + "in";
        }
    }</stream></stream>
 
Share this answer
 
v2
Comments
Faruk Sikder 27-Jul-13 4:56am    
How do I use second solution.
Naveen Roy 15-Apr-14 10:14am    
I was able to use rdlc report that have three page printable area but its prints extra 2 blank pages between printable page... ..due to this reason now i am using crystal report...Now...any one know how to remove extra pages ?...and its print preview is rough..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900