2012-10-04 27 views
6

Używam Visual Studio 2010 C# Windows Forms Application + MySql Mam Report Viewer, który działa w 100%. Reportviewer jest wypełniony danymi z mojej bazy danych, pokazuje, że klikam przycisk, aby wydrukować i drukuje ... ALE, mój klient nie chce kliknąć tego przycisku, chce drukować automatycznie. Kiedy zadzwonię do ReportViewer, wydrukuje sam, bez konieczności klikania przycisku, aby to zrobić. Czy ktoś mógłby mi powiedzieć, jak to robię?Drukowanie ReportViewer bez podglądu

Próbowałem reportviewer1.print i PrintDocument z przybornika. Ale nie wiem, jak poprawnie ich używać.

Dzięki uwadze!

+0

Czy używasz CrystalReports? To jedyny przeglądarka raportów, którą znam, ale to nie znaczy, że jest jedyną. – Bobson

+0

Nie, jego ReportViewer (tylko "Report" z ToolBox) Czy możesz dać szansę i powiedzieć mi, jak to zrobić? Może to nie jest tak różne =) –

Odpowiedz

0

Tak właśnie robimy dzięki Crystal Reports.

  ReportDocument rd = new ReportDocument(); 
      // Insert code to run the report here 

      // This gets the user's default printer to print to. 
      PrintDialog prt = new PrintDialog(); 
      rd.PrintOptions.PrinterName = prt.PrinterSettings.PrinterName; 
      // This does the printing. 
      rd.PrintToPrinter(copies, true, 1, 1000); 

myślę odpowiednik PrintOptions.PrinterName dla ciebie byłoby ReportViewer.PrinterSettings, ale podejrzewam, że to, co naprawdę potrzebne jest równoważne PrintToPrinter(), których nie widzę w moim krótkim spojrzeniem.

+0

Naprawdę dziękuję za odpowiedź na mnie Bobson =) Spróbuję teraz, nie chcę automatycznie PrintDialog tylko wydruku, Spróbuję teraz i dać informację zwrotną tak szybko, jak to możliwe. Nie mam "ReportDocument"; s tylko ReportDataSource, który nie ma opcji .options o "print"; s –

+0

@alannaidon - Dla Ciebie, byłby 'ReportViewer' zamiast' ReportDocument', ale pomysł byłby taki sam . Jeśli to nie zadziała, spróbuj mojej drugiej odpowiedzi. Podejrzewam, że jest bardziej dokładny dla twojego problemu. – Bobson

1

Jeśli moja odpowiedź Crystal Report nie działa dla ciebie, możesz również spróbować this page. Ponownie, nie przetestowałem tego i nie mogę być pewien, że to działa, ale wygląda na zupełnie inne podejście, które może działać. Jeśli nie, to niestety nie będę potrzebował pomocy.

+0

To jest Ok Bobson. Próbowałem coś z SendKey, KeyPressing do przycisku "Drukuj", który jest tworzony automatycznie za pomocą ReportViewer. Czy wiesz coś o tym? –

+0

@alannaidon - Nie sądzę, żebym kiedykolwiek użył SendKey. To brzmi jak proste, proste rozwiązanie. Możesz dodać ją jako nową odpowiedź i zaakceptować, jeśli działa. – Bobson

+0

Podany tutaj link działa bardzo dobrze i jest całkowicie zamknięty w klasie, więc nie musisz dodawać żadnych metod do kodu, wystarczy połączenie z tą klasą. – MrWuf

7

Miałem ten sam problem, to kod, którego używam i działa jak czar!

using System; 
using System.IO; 
using System.Text; 
using System.Globalization; 
using System.Drawing; 
using System.Drawing.Imaging; 
using System.Drawing.Printing; 
using Microsoft.Reporting.WinForms; 
using System.Collections.Generic; 
using System.Collections.Specialized; 
using System.Diagnostics; 
using System.ComponentModel; 
using System.Data; 
using System.Linq; 
using System.Threading.Tasks; 
using System.Windows.Forms; 


namespace NewLabelPrinter 
{ 
/// <summary> 
/// The ReportPrintDocument will print all of the pages of a ServerReport or LocalReport. 
/// The pages are rendered when the print document is constructed. Once constructed, 
/// call Print() on this class to begin printing. 
/// </summary> 
class AutoPrintCls : PrintDocument 
{ 
    private PageSettings m_pageSettings; 
    private int m_currentPage; 
    private List<Stream> m_pages = new List<Stream>(); 

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

    public AutoPrintCls(LocalReport localReport) 
     : this((Report)localReport) 
    { 
     RenderAllLocalReportPages(localReport); 
    } 

    private AutoPrintCls(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) 
    { 
     try 
     { 
      string deviceInfo = CreateEMFDeviceInfo(); 

      // Generating Image renderer pages one at a time can be expensive. In order 
      // to generate page 2, the server would need to recalculate page 1 and throw it 
      // away. Using PersistStreams causes the server to generate all the pages in 
      // the background but return as soon as page 1 is complete. 
      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); 
      } 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show("possible missing information :: " + e); 
     } 
    } 

    private void RenderAllLocalReportPages(LocalReport localReport) 
    { 
     try 
     { 
      string deviceInfo = CreateEMFDeviceInfo(); 

      Warning[] warnings; 

      localReport.Render("IMAGE", deviceInfo, LocalReportCreateStreamCallback, out warnings); 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show("error :: " + e); 
     } 
    } 

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

}

Ta klasa ma skonfigurować idealne na co trzeba to wszystko co musisz zrobić, to:

private void AutoPrint() 
    { 
     AutoPrintCls autoprintme = new AutoPrintCls(reportViewer1.LocalReport); 
     autoprintme.Print(); 
    } 

i hej presto drukuje. Po prostu dołącz to do metody A w swoim kodzie (może po raporcie Ładunki.) I ładnie!

opcja: (nie badane)

Jak nanosi ten drukuje na drukarce domyślnej, aby zmienić drukarkę można wykonać następujące czynności:

if (printDialog.ShowDialog() == DialogResult.OK) 
{ 
    m_pageSettings .PrinterSettings.PrinterName = printDialog.PrinterSettings.PrinterName; 
} 

nie testowano choć jak mam już żadnej kod źródłowy do przetestowania tego

+0

Witam, możliwe jest wybranie drukarki w kodzie z printdialog? – Kate

+0

Tak, wierzę, że używanie printdialog pasowałoby do twoich potrzeb, spójrz na http://msdn.microsoft.com/en-us/library/cfkddyc2(v=vs.110).aspx – lemunk

+0

Tak, ale nie wiem jak mogłem podaj printdialog do twojego kodu ... Próbuję m_pageSettings.PrinterSettings.PrinterName = PrintDialog1.PrinterSettings.PrinterName; ... ale nadal domyślna drukarka ... – Kate

Powiązane problemy