Print a file saved in C # - c#

I'm trying to print in winform, it turns out that when I print the document, I get the blank sheet.
This is the code with which I try to print:
private PrintDocument printDocument1 = new PrintDocument();
private string stringToPrint;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ReadPrint();
printDocument1.Print();
}
private void ReadPrint()
{
string docName = "ejemplo.pdf";
string docPath = #"C:\dir1\";
printDocument1.DocumentName = docName;
using (FileStream stream = new FileStream(docPath + docName, FileMode.Open, FileAccess.Read))
using (StreamReader reader = new StreamReader(stream))
{
stringToPrint = reader.ReadToEnd();
}
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
int charactersOnPage = 0;
int linesPerPage = 0;
e.Graphics.MeasureString(stringToPrint, this.Font,
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out linesPerPage);
e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
stringToPrint = stringToPrint.Substring(charactersOnPage);
e.HasMorePages = (stringToPrint.Length > 0);
}
private void printButton_Click(object sender, EventArgs e)
{
LeerArchivo();
printDocument1.Print();
}
I would like to know if there is a way to correct it or some other way to print the file?Or some example code?
regards
In stringToPrint:

Vb.net has a PrintForm method but C# does not have inbuilt method for printing a Windows Form.
To print a windows form at runtime in C#.net. The base concept involves the capture of the screen image of a Form in jpeg format during runtime and printing the same on a event like Print button click.
print

Are you sure that the stringToPrint is not empty or null ? I'm using the same thing and it works perfectly. You should try to add a print PrintPreviewDialog in case you want to check if the document to be print is not blank. Check your variables first.
e.Graphics.DrawString("SomeString", new Font("Arial", 12, FontStyle.Bold), Brushes.Black, new Point(580, 510));
e.Graphics.DrawString("SomeString1", new Font("Arial", 12, FontStyle.Bold), Brushes.Black, new Point(700, 510));
for the parameter new Point() it is where your text appears via x and y coordinates.

Related

I want to print a document usin c# . But my printer interpeat that i want to print with phografer paper but i want to print A4 normal paper

//Button print
printPreviewDialog1.Document = printDocument1;
printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument1_PrintPage);
DialogResult result = printPreviewDialog1.ShowDialog();
if (result==DialogResult.OK)
{
printDocument1.Print ();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
e.Graphics.DrawString("Nome Equipamento: ", new Font("Arial", 12), Brushes.Black, new Point(25, 210));
e.Graphics.DrawString(comboBox1.Text, new Font("Arial", 12), Brushes.Black, new Point(25, 250));
Try something like this. I only hacked this down without testing and I added no error handling code. It assumes your printer supports printing A4. But you should get the idea.
PaperSize search;
foreach (PaperSize item in printDocument1.PrinterSettings.PaperSizes)
{
if (item.Kind == PaperKind.A4)
{
search = item;
break;
}
}
printDocument1.DefaultPageSettings.PaperSize = search;
printDocument1.Print();
Alternatively you can create your own paper size:
printDocument.DefaultPageSettings.PaperSize =
new PaperSize("My A4", A4width, A4height);

Print the entire area of the control with C#

This is not a duplicat question- the diffenece beetween my question an the others one is my Controler contail a scroller, so they are more informations can't be printed.
I have a C# application that contains a main form name MainForms. This MainForms has a control mainDisplay. I want to print the entire information what we found on the mainDisplay to the printer.
The problem is the information on the the control is too big, and I have to scroll to see all information.
Someone have any function that allow me to print this control MainDisplay with entire information in it?
This the printscreen of the area of my MainDisplay at the right you see the scrollbar:
I use this Function (Source : Printing a control)
private static void PrintControl(Control control)
{
var bitmap = new Bitmap(control.Width, control.Height);
control.DrawToBitmap(bitmap, new Rectangle(0, 0, control.Width, control.Height));
var pd = new PrintDocument();
pd.PrintPage += (s, e) => e.Graphics.DrawImage(bitmap, 100, 100);
pd.Print();
}
But my problem still can't print all the informations contain in my control, it's just print a small erea, still need print more informations which are not printed.
I find the solution. This is the steps i do :
1 - We have a mainForm, and this main form contain a control mainDisplay with a specific dimension and area, let's say this dimensions is smaller and we get scroll.
2- What i do is i make this mainDisplay Empty.
3- i create an other Control myControlToDisplay. I draw and i put all fields i want without scroll, so this one myControlToDisplay will have a big dimension.
4- on the star-up of my application, i tell to the mainDisplay to load myControlToDisplay. This time all the content of myControlToDisplay will be display on mainDisplay with a scroll. Because mainDisplay have a small area.
5- I write this functions :
Bitmap MemoryImage;
PrintDocument printDoc = new PrintDocument();
PrintDialog printDialog = new PrintDialog();
PrintPreviewDialog printDialogPreview = new PrintPreviewDialog();
Control panel = null;
public void Print(Control pnl)
{
DateTime saveNow = DateTime.Now;
string datePatt = #"yyyy-M-d_hh-mm-ss tt";
panel = pnl;
GetPrintArea(pnl);
printDialog.AllowSomePages = true;
printDoc.PrintPage += new PrintPageEventHandler(Print_Details);
printDialog.Document = printDoc;
printDialog.Document.DocumentName = "Document Name";
//printDialog.ShowDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
printDoc.Print();
}
}
public void PrintPreview(Control pnl)
{
DateTime saveNow = DateTime.Now;
string datePatt = #"yyyy-M-d_hh-mm-ss tt";
panel = pnl;
GetPrintArea(pnl);
printDoc.PrintPage += new PrintPageEventHandler(Print_Details);
printDialogPreview.Document = printDoc;
printDialogPreview.Document.DocumentName = "Document Name";
//printDialog.ShowDialog();
if (printDialogPreview.ShowDialog() == DialogResult.OK)
{
printDoc.Print();
}
}
private void Print_Details(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
RectangleF marginBounds = e.MarginBounds;
DateTime saveNow = DateTime.Now;
string datePatt = #"M/d/yyyy hh:mm:ss tt";
//String dtString = saveNow.ToString(datePatt);
// create header and footer
string header = "Put all information you need to display on the Header";
string footer = "Print date : " + saveNow.ToString(datePatt);
Font font = new Font("times new roman", 10, System.Drawing.FontStyle.Regular);
Brush brush = new SolidBrush(Color.Black);
// measure them
SizeF headerSize = e.Graphics.MeasureString(header, font);
SizeF footerSize = e.Graphics.MeasureString(footer, font);
// draw header
RectangleF headerBounds = new RectangleF(marginBounds.Left-80, marginBounds.Top-80, marginBounds.Width, headerSize.Height);
e.Graphics.DrawString(header, font, brush, headerBounds);
// draw footer
RectangleF footerBounds = new RectangleF(marginBounds.Left-80, marginBounds.Bottom - footerSize.Height+80, marginBounds.Width, footerSize.Height);
e.Graphics.DrawString(footer, font, brush, footerBounds);
// dispose objects
font.Dispose();
brush.Dispose();
}
public void GetPrintArea(Control pnl)
{
MemoryImage = new Bitmap(pnl.Width, pnl.Height);
Rectangle rect = new Rectangle(0, 0, pnl.Width, pnl.Height);
pnl.DrawToBitmap(MemoryImage, new Rectangle(0, 0, pnl.Width, pnl.Height));
}
protected override void OnPaint(PaintEventArgs e)
{
if (MemoryImage != null)
{
e.Graphics.DrawImage(MemoryImage, 0, 0);
base.OnPaint(e);
}
}
void PrintDoc_PrintPage(object sender, PrintPageEventArgs e)
{
Rectangle pageArea = e.PageBounds;
Rectangle m = e.MarginBounds;
if ((double)MemoryImage.Width / (double)MemoryImage.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)MemoryImage.Height / (double)MemoryImage.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)MemoryImage.Width / (double)MemoryImage.Height * (double)m.Height);
}
e.Graphics.DrawImage(MemoryImage, m);
}
6 -And finally we suppose that we have two buttons, one to Print and the other one to print preview.
You just have to call this function :
private void PrintButton_Click(object sender, EventArgs e)
{
try
{
Print(mainDisplay.getCurentPanel());
}
catch (Exception exp)
{
MessageBox.Show("Error: \n" + exp.Message);
}
}
private void PrintPreviewButton_Click(object sender, EventArgs e)
{
try
{
PrintPreview(mainDisplay.getCurentPanel());
}
catch (Exception exp)
{
MessageBox.Show("Error: \n" + exp.Message);
}
}
Hope it will help someone :)
good luck

How to print using multiple screenshots captured with copyfromscreen

I'm pretty new to C# but I finally have my first program up and running and I need to make it print. Its a window form with information and calculations on different tab controls, somewhat like Excel. The page that is currently being looked at prints fine with the copyfromscreen method, but I cannot get additional pages to print correctly. I have about 20 tabs I would like to be able to print at one time. I found a way to print the contents of controls into a textfile, but I would much prefer to be able to print what the form looks like. Thanks.
Bitmap memoryImage;
Bitmap memoryImage2;
private void CaptureScreen()
{
Graphics myGraphics = this.CreateGraphics();
Size s = tabControlMain.Size;
s.Width = s.Width + 20;
memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(this.Location.X+15, this.Location.Y+80, 0, 0, s);
tabControlMain.SelectedIndex = 1;
memoryImage2 = new Bitmap(s.Width, s.Height, myGraphics);
Graphics memoryGraphics2 = Graphics.FromImage(memoryImage2);
memoryGraphics2.CopyFromScreen(this.Location.X + 15, this.Location.Y + 80, 0, 0, s);
}
private void printDocumentReal_PrintPage(System.Object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(memoryImage, 0, 0);
e.Graphics.DrawImage(memoryImage2, 0, 550);
}
private void printToolStripButton_Click(object sender, EventArgs e)
{
CaptureScreen();
printDocumentReal.Print();
}
First, you should use PrintDocument and PrintPreviewDialog objects for print related tasks and an event handler for printing.
Second, you need to preform some optimization for your code, here's the solution:
private void printToolStripButton_Click(object sender, EventArgs e)
{
PrintDocument document = new PrintDocument();
document.PrintPage += new PrintPageEventHandler(document_PrintPage);
PrintPreviewDialog preview = new PrintPreviewDialog() { Document = document };
// you will be able to preview all pages before print it ;)
try
{
preview.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\nYou need to install a printer to preform print-related tasks!", "Print Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Boolean firstPage = true;
private void document_PrintPage(object sender, PrintPageEventArgs e)
{
if (firstPage)
{
tabControlMain.SelectTab(0);
firstPage = false;
}
Graphics g = e.Graphics;
TabPage tab = tabControlMain.SelectedTab;
using (Bitmap img = new Bitmap(tab.Width, tab.Height))
{
tab.DrawToBitmap(img, tab.ClientRectangle);
g.DrawImage(img, new Point(e.MarginBounds.X, e.MarginBounds.Y)); // MarginBounds means the margins of the page
}
if (tabControlMain.SelectedIndex + 1 < tabControlMain.TabCount)
{
tabControlMain.SelectedIndex++;
e.HasMorePages = true;//If you set e.HasMorePages to true, the Document object will call this event handler again to print the next page.
}
else
{
e.HasMorePages = false;
firstPage = true;
}
}
I hope it's working fine with you And here's an additional one if you need to save all tabs as set of images on your hard disk:
public void RenderAllTabs()
{
foreach (TabPage tab in tabControlMain.TabPages)
{
tabControlMain.SelectTab(tab);
using (Bitmap img = new Bitmap(tab.Width, tab.Height))
{
tab.DrawToBitmap(img, tab.ClientRectangle);
img.Save(string.Format(#"C:\Tabs\{0}.png", tab.Text));
}
}
}
Try using DrawToBitmap method of TabPage instead:
private void CaptureScreen()
{
memoryImage = new Bitmap(tabControlMain.SelectedTab.Width, tabControlMain.SelectedTab.Height);
tabControlMain.SelectedTab.DrawToBitmap(memoryImage, tabControlMain.SelectedTab.ClientRectangle);
tabControlMain.SelectedIndex = 1;
memoryImage2 = new Bitmap(tabControlMain.SelectedTab.Width, tabControlMain.SelectedTab.Height);
tabControlMain.SelectedTab.DrawToBitmap(memoryImage2, tabControlMain.SelectedTab.ClientRectangle);
}
To get all the images of your TabPages, you can make a loop like this:
List<Bitmap> images = new List<Bitmap>();
private void CaptureScreen(){
foreach(TabPage page in tabControlMain.TabPages){
Bitmap bm = new Bitmap(page.Width, page.Height);
tabControlMain.SelectedTab = page;
page.DrawToBitmap(bm, page.ClientRectangle);
images.Add(bm);
}
}
//Then you can access the images of your TabPages in the list images
//the index of TabPage is corresponding to its image index in the list images

How do I print a string with a printer?

I'm writing an application that need to print some information that would came from a DataGridView, I already have the string I'd like to print, I just don't know how. I found some stuff on the web that said I'd need to use a PrintDocument object and a PrintDialog.
Lets suppose I have 3 strings and I want to print to each one in one line (line 1, 2 and 3),but the first must be in bold and using the Arial font.
The output (on the paper) would be:
string 1 (in bold and using the Arial font)
string 2
string 3
EDIT: (asked by abelenky)
The Code:
private void PrintCoupon()
{
string text = "Coupon\n";
foreach (DataGridViewRow dgvRow in dataGridViewCarrinho.Rows)
{
foreach (DataGridViewCell dgvCell in dgvRow.Cells)
{
text += dgvCell.Value.ToString() + " ";
}
text += "\n";
}
MessageBox.Show(text);
// I should print the coupon here
}
So how do I do that using C#?
Thanks.
for printing strings on a paper you should draw them first on a PrintDocument using GDI+ in c#
in a Winform add PrintDocument tool to your project , and double click on it to access the PrintPage event handler of it ,
assuming you already have s1,s2 and s3 as String Variables ,
in the PrintPage event handler we use :
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Font f1 = new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel);
Font f2 = new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel);
Font f3 = new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel);
e.Graphics.DrawString(s1, f1, Brushes.Black, new Point(10, 10));
e.Graphics.DrawString(s2, f2, Brushes.Black, new Point(10, 40));
e.Graphics.DrawString(s3, f3, Brushes.Black, new Point(10, 60));
}
and whenever you wanted to print the document :
printDocument1.Print();
you may also consider using a PrintPreviewDialog to see what's going on before printing the document
Try this ..
using System.Drawing;
private void printButton_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler
(this.pd_PrintPage);
pd.Print();
}
// The PrintPage event is raised for each page to be printed.
void pd_PrintPage(Object* /*sender*/, PrintPageEventArgs* ev)
{
Font myFont = new Font( "m_svoboda", 14, FontStyle.Underline, GraphicsUnit.Point );
float lineHeight = myFont.GetHeight( e.Graphics ) + 4;
float yLineTop = e.MarginBounds.Top;
string text = "Coupon\n";
foreach (DataGridViewRow dgvRow in dataGridViewCarrinho.Rows)
{
foreach (DataGridViewCell dgvCell in dgvRow.Cells)
{
text += dgvCell.Value.ToString() + " ";
}
text += "\n";
}
//MessageBox.Show(text);
// I should print the coupon here
e.Graphics.DrawString( text, myFont, Brushes.Black,
new PointF( e.MarginBounds.Left, yLineTop ) );
yLineTop += lineHeight;
}

How can I print the large dataGridView/Form on multiple pages?

Just using Win Forms in C#. Created Data Grid View and added print button. Here is my code for print button.
private void toolStripButton1_Click(object sender, EventArgs e)
{
image = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height);
this.dataGridView1.DrawToBitmap(image, new Rectangle(new Point(), this.dataGridView1.Size));
memStream = new System.IO.MemoryStream();
printPDialog = new PrintPreviewDialog();
try
{
printFont = new Font("Arial", 10);
image.Save(memStream, System.Drawing.Imaging.ImageFormat.Bmp);
image.Save("d:\\Adnan.bmp");
p = new PrintDocument();
p.PrintPage += this.p_PrintPage;
this.printPDialog.Document = p;
printPDialog.Show();
}
catch (System.Runtime.InteropServices.ExternalException ee)
{
}
}
private void p_PrintPage(object sender, PrintPageEventArgs e)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;
int? line = null;
// Calculate the number of lines per page.
linesPerPage = e.MarginBounds.Height /
printFont.GetHeight(e.Graphics);
e.Graphics.DrawImage(Image.FromStream(memStream), leftMargin, topMargin);
}
private void printPDialog_FormClosed(object sender, FormClosedEventArgs e)
{
image.Dispose();
memStream.Dispose();
}
Problem is my DataGridView has a large list. I have DataGridView inside the FlowLayoutPanel. I tried printing FlowLayoutPanel as well as GridView but in either case the data which is obscure by a vertical scrollbar does not get printed. After spending hours online and trying VB powerpacks I am at loss what to do.
Here is how the data looks in GridView.
Here is a link where you can try the downloaded code sample
How To Print a Data Grid in C# and .NET

Categories

Resources