How to print a form in C#? [duplicate] - c#

This question already has answers here:
Show Print Dialog before printing
(2 answers)
Closed 8 years ago.
I want to print a form. I have this code but I can't choose what printer to print and it prints with default printer. How can I resolve this?
void PrintImage(object o, PrintPageEventArgs e)
{
int x = SystemInformation.WorkingArea.X;
int y = SystemInformation.WorkingArea.Y;
int width = this.Width;
int height = this.Height;
Rectangle bounds = new Rectangle(x, y, width, height);
Bitmap img = new Bitmap(width, height);
this.DrawToBitmap(img, bounds);
Point p = new Point(100, 100);
e.Graphics.DrawImage(img, p);
}
private void button1_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintImage);
pd.Print();
}

The answer is from HERE
You have to use PrintDialog
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintPage);
PrintDialog pdi = new PrintDialog();
pdi.Document = pd;
if (pdi.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
else
{
MessageBox.Show("Print Cancelled");
}
On 64-bit Windows and with some versions of .NET you may have to set pdi.UseExDialog = true; for the dialog window to appear.

Related

How to print a text file using PrintDialog in C#

I am new to C# windows forms.
I am trying to print the content of a Text file using the PrintDialog as shown in screenshot.
Screenshot
The following code is working correctly and it is printing but the printing process occurs immediately without opening the PrintDialog. I want to open the PrintDialog because I have 3 printers and I want to select a specific printer and when I click OK I want to print it.
Anyone knows how to modify this code so it can display the PrintDialog box so I can select a printer and continue printing?.
private void Print_Click(object sender, EventArgs e)
{
string filename = #"D:\\File1.txt";
//Create a StreamReader object
reader = new StreamReader(filename);
//Create a Verdana font with size 10
verdana10Font = new Font("Verdana", 10);
//Create a PrintDocument object
PrintDocument pd = new PrintDocument();
//Add PrintPage event handler
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
//Call Print Method
pd.Print();
//Close the reader
if (reader != null)
reader.Close();
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs ppeArgs)
{
//Get the Graphics object
Graphics g = ppeArgs.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = 0;
float topMargin = 50;
string line = null;
//Calculate the lines per page on the basis of the height of the page and the height of the font
linesPerPage = ppeArgs.MarginBounds.Height / verdana10Font.GetHeight(g);
//Now read lines one by one, using StreamReader
while (count < linesPerPage && ((line = reader.ReadLine()) != null))
{
//Calculate the starting position
yPos = topMargin + (count * verdana10Font.GetHeight(g));
//Draw text
g.DrawString(line, verdana10Font, Brushes.Black, leftMargin, yPos, new StringFormat());
//Move to next line
count++;
}
//If PrintPageEventArgs has more pages to print
if (line != null)
{
ppeArgs.HasMorePages = true;
}
else
{
ppeArgs.HasMorePages = false;
}
}
You can do so using PrintDialog.
PrintDialog pdialog = new PrintDialog();
pdialog.Document = pd;
if (pdialog.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
Complete Code
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
PrintDialog pdialog = new PrintDialog();
pdialog.Document = pd;
if (pdialog.ShowDialog() == DialogResult.OK)
{
pd.Print();
}

PrintDocument just prints some part of my JPG file

I created an application that allows users to print multiple jpg files. So I send my print request directly, like this:
if (existfile == true)
{
PrinterSettings a=new PrinterSettings();
PrintDocument pd = new PrintDocument();
IEnumerable<PaperSize> size = a.PaperSizes.Cast<PaperSize>();
PaperSize a4 = size.First<PaperSize>(i => i.Kind == PaperKind.A4);
pd.DefaultPageSettings.Landscape = true;
pd.DefaultPageSettings.PaperSize = a4;
pd.PrintPage += PrintPage;
pd.Print();
}
And the print function :
private void PrintPage(object o, PrintPageEventArgs e)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(CurrentAddress);
Point loc = new Point(100, 100);
e.Graphics.DrawImage(img, loc);
}
But this code just prints some part of my image, not all of it .I want to print them scale to fit. How can I do that?
This might fix the issue.
e.Graphics.DrawImage(img, e.MarginBounds);
or
e.Graphics.DrawImage(img, e.PageBounds);
or
ev.Graphics.DrawImage(Image.FromFile("C:\\My Folder\\MyFile.bmp"), ev.Graphics.VisibleClipBounds);

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

Show Print Dialog before printing

I want to show the print dialog box before printing the document, so the user can choose another printer before printing. The code for printing is:
private void button1_Click(object sender, EventArgs e)
{
try
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintImage);
pd.Print();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ToString());
}
}
void PrintImage(object o, PrintPageEventArgs e)
{
int x = SystemInformation.WorkingArea.X;
int y = SystemInformation.WorkingArea.Y;
int width = this.Width;
int height = this.Height;
Rectangle bounds = new Rectangle(x, y, width, height);
Bitmap img = new Bitmap(width, height);
this.DrawToBitmap(img, bounds);
Point p = new Point(100, 100);
e.Graphics.DrawImage(img, p);
}
will this code be able to print the current form?
You have to use PrintDialog
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintPage);
PrintDialog pdi = new PrintDialog();
pdi.Document = pd;
if (pdi.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
else
{
MessageBox.Show("Print Cancelled");
}
Edited(from Comment)
On 64-bit Windows and with some versions of .NET you may have to set pdi.UseExDialog = true; for the dialog window to appear.
For the sake of completeness, the code should include a using directive
using System.Drawing.Printing;
for further reference please goto
PrintDocument Class

How to print a full size image in c#

I am trying to print an image in C#. It is a full 8.5x11 size tiff created by Adobe Acrobat from a PDF. When I print it with C# using the code below, it prints correct vertically, but not horizontally, where it is pushed over about a half inch. I set the origin of the image to 0,0. Am I missing something?
private FileInfo _sourceFile;
public void Print(FileInfo doc, string printer, int tray)
{
_sourceFile = doc;
PrintDocument pd = new PrintDocument();
pd.PrinterSettings.PrinterName = printer;
pd.DocumentName = _sourceFile.FullName;
using (Image img = Image.FromFile(_sourceFile.FullName)) {
if (img.Width > img.Height) {
pd.DefaultPageSettings.Landscape = true;
}
}
pd.PrintPage += PrintPage;
foreach (PaperSource ps in pd.PrinterSettings.PaperSources) {
if (ps.RawKind == tray) {
pd.DefaultPageSettings.PaperSource = ps;
}
}
pd.Print();
}
private void PrintPage(object o, PrintPageEventArgs e)
{
using (System.Drawing.Image img = System.Drawing.Image.FromFile(_sourceFile.FullName)) {
Point loc = new Point(0, 0);
e.Graphics.DrawImage(img, loc);
}
}
look at the code from this below for a good example this code is from this link below
Print Image in C#
private void PrintImage()
{
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.OriginAtMargins = false;
pd.DefaultPageSettings.Landscape = true;
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
printPreviewDialog1.Document = pd;
printPreviewDialog1.ShowDialog();
//pd.Print();
}
void pd_PrintPage(object sender, PrintPageEventArgs e)
{
double cmToUnits = 100 / 2.54;
e.Graphics.DrawImage(bmIm, 100, 1000, (float)(15 * cmToUnits), (float)(10 * cmToUnits));
}
private void button5_Click(object sender, EventArgs e)
{
PrintImage();
}

Categories

Resources