How to print Reportviewer without a Preview - c#

Im new to the c#, currently Im making a POS application witch can print a Receipt. I used reportviewer component for create the Receipt. I is working. but I couldn't pass the print command directly. When it is preview I have to press Print Button manually. but I need to print it automatically without a preview. here is my beginning of the code. Is there any way to bind this repotviewr with PrintDocument or how can I print this reportviewer automatically
Open FormReceipt
DateTime thisDay = DateTime.Today;
FormReceipt frmReceipt = new FormReceipt(order, String.Format("{0:n}", totalAmmount), String.Format("{0:n}", paidammount), String.Format("{0:n}",change), thisDay.ToString("g"), discount.ToString());
frmReceipt.ShowDialog();
Set Parameters and Binding Source
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;
using Microsoft.Reporting.WinForms;
namespace Pos
{
public partial class FormReceipt : MetroFramework.Forms.MetroForm
{
List<Receipt> _list;
string _total, _cash, _change, _date, _user, _discount;
public FormReceipt(List<Receipt> datasource, string total,string cash, string change, string date, string discount)
{
InitializeComponent();
_list = datasource;
_total = total;
_cash = cash;
_change = change;
_date = date;
_user = Sessiondata.user;
_discount = discount;
}
private void FormReceipt_Load(object sender, EventArgs e)
{
ReceiptBindingSource.DataSource = _list;
Microsoft.Reporting.WinForms.ReportParameter[] para = new Microsoft.Reporting.WinForms.ReportParameter[]{
new Microsoft.Reporting.WinForms.ReportParameter("pTotal",_total),
new Microsoft.Reporting.WinForms.ReportParameter("pCash",_cash),
new Microsoft.Reporting.WinForms.ReportParameter("pChange",_change),
new Microsoft.Reporting.WinForms.ReportParameter("pDate",_date),
new Microsoft.Reporting.WinForms.ReportParameter("pUser",_user),
new Microsoft.Reporting.WinForms.ReportParameter("pItems",_list.Count.ToString()),
new Microsoft.Reporting.WinForms.ReportParameter("pDiscount",_discount+"%")
};
this.reportViewer1.LocalReport.SetParameters(para);
this.reportViewer1.RefreshReport();
}
private void reportViewer1_Load(object sender, EventArgs e)
{
}
}
}

I am posting my code which is working fine as you want. Check this code and do the customization in the code as needed.
List<Receipt> _list;
string _total, _cash, _change, _date, _user, _discount;
public FormReceipt(List<Receipt> datasource, string total,string cash, string change, string date, string discount)
{
InitializeComponent();
_list = datasource;
_total = total;
_cash = cash;
_change = change;
_date = date;
_user = Sessiondata.user;
_discount = discount;
}
private void FormReceipt_Load(object sender, EventArgs e)
{
ReceiptBindingSource.DataSource = _list;
Microsoft.Reporting.WinForms.ReportParameter[] para = new Microsoft.Reporting.WinForms.ReportParameter[]{
new Microsoft.Reporting.WinForms.ReportParameter("pTotal",_total),
new Microsoft.Reporting.WinForms.ReportParameter("pCash",_cash),
new Microsoft.Reporting.WinForms.ReportParameter("pChange",_change),
new Microsoft.Reporting.WinForms.ReportParameter("pDate",_date),
new Microsoft.Reporting.WinForms.ReportParameter("pUser",_user),
new Microsoft.Reporting.WinForms.ReportParameter("pItems",_list.Count.ToString()),
new Microsoft.Reporting.WinForms.ReportParameter("pDiscount",_discount+"%")
};
this.reportViewer1.LocalReport.SetParameters(para);
this.reportViewer1.RefreshReport();
Export(ReportViewer1.LocalReport, false);
Print();
Dispose();
}
private int m_currentPageIndex;
private IList<Stream> m_streams;
private Stream CreateStream(string name,
string fileNameExtension, Encoding encoding,
string mimeType, bool willSeek)
{
Stream stream = new MemoryStream();
m_streams.Add(stream);
return stream;
}
private void Export(LocalReport report, bool isLandscape)
{
string deviceInfo = string.Empty;
if (isLandscape)
{
deviceInfo =
#"<DeviceInfo>
<OutputFormat>EMF</OutputFormat>
<PageWidth>11in</PageWidth>
<PageHeight>8.5in</PageHeight>
<MarginTop>0.25in</MarginTop>
<MarginLeft>0.25in</MarginLeft>
<MarginRight>0.25in</MarginRight>
<MarginBottom>0.25in</MarginBottom>
</DeviceInfo>";
}
else
{
deviceInfo =
#"<DeviceInfo>
<OutputFormat>EMF</OutputFormat>
<PageWidth>8.5in</PageWidth>
<PageHeight>11in</PageHeight>
<MarginTop>0.25in</MarginTop>
<MarginLeft>0.25in</MarginLeft>
<MarginRight>0.25in</MarginRight>
<MarginBottom>0.25in</MarginBottom>
</DeviceInfo>";
}
Warning[] warnings;
m_streams = new List<Stream>();
// Create Report DataSource
ReportDataSource rds = new ReportDataSource();
rds.Value = _list;
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
report.Render("Image", deviceInfo, CreateStream,
out warnings);
foreach (Stream stream in m_streams)
stream.Position = 0;
}
private void Print()
{
PrinterSettings settings = new PrinterSettings(); //set printer settings
string printerName = settings.PrinterName; //use default printer name
if (m_streams == null || m_streams.Count == 0)
throw new Exception("Error: no stream to print.");
PrintDocument printDoc = new PrintDocument();
if (!printDoc.PrinterSettings.IsValid)
{
Response.Write("<script>alert('" + printerName + "')</script>");
}
else
{
printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
m_currentPageIndex = 0;
printDoc.Print();
}
}
private void PrintPage(object sender, PrintPageEventArgs ev)
{
Metafile pageImage = new
Metafile(m_streams[m_currentPageIndex]);
ev.Graphics.DrawImage(pageImage, ev.PageBounds);
m_currentPageIndex++;
ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
}
public void Dispose()
{
if (m_streams != null)
{
foreach (Stream stream in m_streams)
stream.Close();
m_streams = null;
}
}

add this code to class and then call function PrintToPrinter and pass reportviewer as parameter then report will print silently
for more details :
https://learn.microsoft.com/en-us/previous-versions/ms252091(v=vs.140)?redirectedfrom=MSDN
private static List<Stream> m_streams;
private static int m_currentPageIndex = 0;
static LocalReport report = new LocalReport();
public static void PrintToPrinter(LocalReport report)
{
Export(report);
}
public static void Export(LocalReport report, bool print = true)
{
string deviceInfo =
#"<DeviceInfo>
<OutputFormat>EMF</OutputFormat>
<PageWidth>{pageSettings.PaperSize.Width * 100}in</PageWidth>
<PageHeight>{pageSettings.PaperSize.Height * 100}in</PageHeight>
<MarginTop>{pageSettings.Margins.Top * 100}in</MarginTop>
<MarginLeft>{pageSettings.Margins.Left * 100}in</MarginLeft>
<MarginRight>{pageSettings.Margins.Right * 100}in</MarginRight>
<MarginBottom>{pageSettings.Margins.Bottom * 100}in</MarginBottom>
</DeviceInfo>";
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();
}
}
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 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 PrintPage(object sender, PrintPageEventArgs ev)
{
Metafile pageImage = new
Metafile(m_streams[m_currentPageIndex]);
// Adjust rectangular area with printer margins.
Rectangle adjustedRect = new Rectangle(
ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
ev.PageBounds.Width,
ev.PageBounds.Height);
// Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect);
// Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect);
// Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex++;
ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
}
public static void DisposePrint()
{
if (m_streams != null)
{
foreach (Stream stream in m_streams)
stream.Close();
m_streams = null;
}
}

Related

Print RDCL report C#

I am using the below code to print RDCL Report directly ,
but the problem in the printed page , it is not same to what i choose in the report properties (A4), i tried to change page width and height in device info but same issue the printed paper huge and printed on 4 papers. please any idea?
private Stream CreateStream(string name,
string fileNameExtension, Encoding encoding,
string mimeType, bool willSeek)
{
Stream stream = new MemoryStream();
m_streams.Add(stream);
return stream;
}
// Export the given report as an EMF (Enhanced Metafile) file.
private void Export(LocalReport report)
{
string deviceInfo =
#"<DeviceInfo>
<OutputFormat>EMF</OutputFormat>
<PageWidth>8.27in</PageWidth>
<PageHeight>11.69in</PageHeight>
<MarginTop>0.25in</MarginTop>
<MarginLeft>0.25in</MarginLeft>
<MarginRight>0.25in</MarginRight>
<MarginBottom>0.25in</MarginBottom>
</DeviceInfo>";
Warning[] warnings;
m_streams = new List<Stream>();
report.Render("Image", deviceInfo, CreateStream,
out warnings);
foreach (Stream stream in m_streams)
stream.Position = 0;
}
// Handler for PrintPageEvents
private void PrintPage(object sender, PrintPageEventArgs ev)
{
Metafile pageImage = new
Metafile(m_streams[m_currentPageIndex]);
// Adjust rectangular area with printer margins.
Rectangle adjustedRect = new Rectangle(
ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
ev.PageBounds.Width,
ev.PageBounds.Height);
// Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect);
// Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect);
// Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex++;
ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
}
private 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();
}
}
// Create a local report for Report.rdlc, load the data,
// export the report to an .emf file, and print it.
private void Run()
{
LocalReport report = new LocalReport();
report.ReportPath = #"Doctor_form.rdlc";
Export(report);
Print();
}
protected void print_Click1(object sender, EventArgs e)
{
LocalReport report = new LocalReport();
report.ReportPath = #"Doctor_form.rdlc";
report.SetParameters(parameters);
Export(report);
Print();}

How to print dynamic paper height without cut using RDLC report c#?

Here is my code i work with:
set Dataset and parameter to RDLC report
private static int m_currentPageIndex;
report.DataSources.Add(new ReportDataSource("dsReceiptInfor", ReceiptInfor));
ReportParameter[] param = new ReportParameter[2];
param[0] = new ReportParameter("imgPath", FilePath);
param[1] = new ReportParameter("BaseCurrencyFormat", BaseCurrencyFormat);
report.SetParameters(param);
Export(report);
Print();
Functions
--Export
private static void Export(LocalReport report)
{
string deviceInfo =
#"<DeviceInfo>
<OutputFormat>EMF</OutputFormat>
<PageWidth>8.5in</PageWidth>
<PageHeight>11in</PageHeight>
<MarginTop>0in</MarginTop>
<MarginLeft>0in</MarginLeft>
<MarginRight>0in</MarginRight>
<MarginBottom>0in</MarginBottom>
</DeviceInfo>";
Warning[] warnings;
m_streams = new List<Stream>();
report.Render("Image", deviceInfo, CreateStream, out warnings);
foreach (Stream stream in m_streams)
stream.Position = 0;
}
--Print
private static void Print()
{
if (m_streams == null || m_streams.Count == 0)
throw new Exception("Error: no stream to print.");
PrintDocument PrintBill = new PrintDocument();
PrintBill.PrintPage += new PrintPageEventHandler(PrintPage);
PrintBill.PrinterSettings.PrinterName = PrinterName;
PrintBill.PrintController = new StandardPrintController();
m_currentPageIndex = 0;
PrintBill.Print();
}
--PrintPage
private static void PrintPage(object sender, PrintPageEventArgs ev)
{
try
{
Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]);
//Adjust rectangular area with printer margins.
Rectangle adjustedRect = new Rectangle(
0,
0,
765,
ev.PageBounds.Height);
//Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect);
// Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect);
// Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex++;
ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
}
catch (Exception ex)
{
}
}
When the data print (PageHeight > 11 inch) it will cut. Could you tell me how to print long as the paper.
thanks for your attention :)
after long time i have searching the answer but still not found. So i have found one solution without coding.
in Printer setting we can change printer preference :
Paper source --> Document (cut). Done

C# WinForms: Data in report is not printing.

I am new to C# and reports. What am I doing wrong or missing?
I have searched and searched and for the life of me can't figure this out.
I am using C# Windows Forms Application. I have report2.rdlc and everything works great in the report viewer, the text boxes and data in the tablix print as expected. When I print directly to the printer without using the report viewer, the text boxes print, but the data in the tablix does not print. Provided below is a screenshot of the Report Data window along with the coding and explanation.
Report Data Image
StatusCodes.cs form: Contains print button that has DialogResult. If "Yes" is clicked, StatusCodePreview.cs form opens. This has the report viewer (no problems here). If "No" is clicked, this triggers PrintWithoutReportViewer.cs and the report is printed directly to the default printer (problem: only text boxes and column headers are printing, data is not).
private void btn_CodePrint_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)
{
StatusCodePreview scp = new StatusCodePreview();
scp.Show();
}
else if (dg == DialogResult.No)
{
DataTable dt = new StatusCodesPrintDataSet.DataTable1DataTable();
LocalReport report = new LocalReport {ReportEmbeddedResource = "Toolbar.Report2.rdlc"};
report.DataSources.Add(new ReportDataSource("StatCodePrintDataSet1", dt));
report.PrintToPrinter();
}
}
Code for PrintWithoutReportViewer.cs
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;
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();
//PrintDialog startPrint = new PrintDialog();
//startPrint.ShowDialog();
}
}
public static void PrintPage(object sender, PrintPageEventArgs e)
{
Stream pageToPrint = m_Streams[m_CurrentPageIndex];
pageToPrint.Position = 0;
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);
e.Graphics.FillRectangle(Brushes.White, adjustedRect);
e.Graphics.DrawImage(pageMetaFile, adjustedRect);
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";
}
}
I was originally trying to print using PrintDialog (I was wanting this option to allow user to still be able to select a printer), but that doesn't work at all and just led me to getting so frustrated. I am now just trying to use Print();
Like I said at the beginning, I am new at this and I'm lost. It would be greatly appreciated if anyone can help me with this.

how to remove spacing in the richtextbox?

question
relevant to this question, I want to remove the spacing in my richtextbox since the display will always include a spacing like:
Hello
Hello
Hello
I want to modify the code that will display this texts as:
Hello
Hello
Hello
How would I do that? Anyone knows? Thanks
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Threading;
using System.Windows.Threading;
using System.Data.SQLite;
using System.Text.RegularExpressions;
namespace SerialTrial
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public class ThreadExample
{
FlowDocument mcFlowDoc = new FlowDocument();
Paragraph para = new Paragraph();
public static void ThreadJob(MainWindow mainWindow)
{
string dBConnectionString = #"Data Source = C:\Users\Documents\Visual Studio 2012\Projects\SerialTrial\SerialTrial\bin\Debug\employee.sqlite;";
SQLiteConnection sqliteCon = new SQLiteConnection(dBConnectionString);
//open connection to database
try
{
sqliteCon.Open();
SQLiteCommand createCommand = new SQLiteCommand("Select empID from EmployeeList", sqliteCon);
SQLiteDataReader reader;
reader = createCommand.ExecuteReader();
//richtextbox2.Document.Blocks.Clear();
while (reader.Read())
{
string Text = (String.Format("{0}", Object.Equals(Variables.buffering, reader.GetValue(0))));
if (Convert.ToBoolean(Text))
{
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run("Hello")))));
string text = "s";
mainWindow.WriteSerial(text);
Console.WriteLine(Text);
//richtextbox2.Document.Blocks.Add(new Paragraph(new Run(Text)));
}
}
sqliteCon.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public partial class MainWindow : Window
{
SerialPort serial = new SerialPort();
//string received_data;
//Thread readThread = new Thread(Read);
FlowDocument mcFlowDoc = new FlowDocument();
Paragraph para = new Paragraph();
public MainWindow()
{
InitializeComponent();
combobox1.Items.Insert(0, "Select Port");
combobox1.SelectedIndex = 0;
string[] ports = null;
ports = SerialPort.GetPortNames();
// Display each port name to the console.
int c = ports.Count();
for (int i = 1; i <= c; i++)
{
if (!combobox1.Items.Contains(ports[i - 1]))
{
combobox1.Items.Add(ports[i - 1]);
}
}
}
string dBConnectionString = #"Data Source = C:\Users\Documents\Visual Studio 2012\Projects\SerialTrial\SerialTrial\bin\Debug\employee.sqlite;";
static int count = 0;
private void Button_Click(object sender, RoutedEventArgs e)
{
count++;
string[] ports = null;
ports = SerialPort.GetPortNames();
// Display each port name to the console.
int c = ports.Count();
for (int i = 1; i <= c; i++)
{
if (!combobox1.Items.Contains(ports[i - 1]))
{
combobox1.Items.Add(ports[i - 1]);
}
}
}
private void combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string myItem = combobox1.SelectedItem.ToString();
textbox1.Text = myItem;
}
private void button2_Click(object sender, RoutedEventArgs e)
{
try
{
if ((string)button2.Content == "Connect")
{
string myItem = combobox1.SelectedItem.ToString();
if (myItem == "Select Port")
{
MessageBox.Show("Select Port");
}
else
{
serial.PortName = myItem;
serial.Open();
textbox2.Text = "Serial Port Opened";
button2.Content = "Disconnect";
serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
}
}
else
{
serial.Close();
button2.Content = "Connect";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#region Receiving
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytes = serial.BytesToRead;
byte[] buffer = new byte[bytes];
serial.Read(buffer, 0, bytes);
foreach (var item in buffer)
{
Console.Write(item.ToString());
}
Variables.buffering = BitConverter.ToInt64(buffer, 0);
Console.WriteLine();
Console.WriteLine(Variables.buffering);
Thread thread = new Thread(new ThreadStart(() => ThreadExample.ThreadJob(this)));
thread.Start();
thread.Join();
}
/*
private delegate void UpdateUiTextDelegate(string text);
private void Receive(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// Collecting the characters received to our 'buffer' (string).
received_data = serial.ReadExisting();
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), received_data);
}
private void WriteData(string text)
{
// Assign the value of the recieved_data to the RichTextBox.
para.Inlines.Add(text);
mcFlowDoc.Blocks.Add(para);
richtextbox2.Document = mcFlowDoc;
richtextbox2.ScrollToEnd();
}
*/
#endregion
private void button3_Click(object sender, RoutedEventArgs e)
{
if (serial.IsOpen)
{
TextRange allTextRange = new TextRange(richtextbox1.Document.ContentStart, richtextbox1.Document.ContentEnd);
string allText = allTextRange.Text;
serial.WriteLine(allText);
}
}
public void WriteSerial(string text)
{
serial.Write(text);
}
}
}
I want to put it somewhere inside this if function:
if (Convert.ToBoolean(Text))
{
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run("Hello")))));
string text = "s";
mainWindow.WriteSerial(text);
Console.WriteLine(Text);
//richtextbox2.Document.Blocks.Add(new Paragraph(new Run(Text)));
}
Try the following Regex
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text, #"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);
string myText = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text;
var resultString = Regex.Replace(myText, #"( |\r?\n)\1+", "$1");

How to export/save web page as an image in asp.net

i am trying to take screenshot of page and save it as image. The page has several div tags and different contents in each div like one div tag has chart and the other might have gridview. So i am trying to take snapshot of the page ans save it as image. Can someone please help me here as i have googled and could not find any good resources about this. thanks.
The following seems to work. I got this from Convert webpage to image from ASP.NET
use:
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
public class WebsiteToImage
{
private Bitmap m_Bitmap;
private string m_Url;
private string m_FileName = string.Empty;
public WebsiteToImage(string url)
{
// Without file
m_Url = url;
}
public WebsiteToImage(string url, string fileName)
{
// With file
m_Url = url;
m_FileName = fileName;
}
public Bitmap Generate()
{
// Thread
var m_thread = new Thread(_Generate);
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
private void _Generate()
{
var browser = new WebBrowser { ScrollBarsEnabled = false };
browser.Navigate(m_Url);
browser.DocumentCompleted += WebBrowser_DocumentCompleted;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Capture
var browser = (WebBrowser)sender;
browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.BringToFront();
browser.DrawToBitmap(m_Bitmap, browser.Bounds);
// Save as file?
if (m_FileName.Length > 0)
{
// Save
m_Bitmap.SaveJPG100(m_FileName);
}
}
}
public static class BitmapExtensions
{
public static void SaveJPG100(this Bitmap bmp, string filename)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static void SaveJPG100(this Bitmap bmp, Stream stream)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static ImageCodecInfo GetEncoder(ImageFormat format)
{
var codecs = ImageCodecInfo.GetImageDecoders();
foreach (var codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
// Return
return null;
}
}
To implement:
WebsiteToImage websiteToImage = new WebsiteToImage( "http://www.cnn.com", #"C:\Some Folder\Test.jpg");
websiteToImage.Generate();

Categories