Printing a Document
26,767
Solution 1
Try This:
private void MenuItemPrint()
{
if (!FileName.Trim().Equals(""))
{
using(PrintDocument pd = new PrintDocument())
{
using(PrintDialog printDialog=new PrintDialog())
{
if(printDialog.ShowDialog()==DialogResult.Yes)
{
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
pd.Print();
}
}
}
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
ev.Graphics.DrawString(FileName, new Font("Arial", 10), Brushes.Black,
ev.MarginBounds.Left, 0, new StringFormat());
}
Solution 2
You can use following code to print the content of a textbox with the selected printer:
private void PrintTextBoxContent()
{
#region Printer Selection
PrintDialog printDlg = new PrintDialog();
#endregion
#region Create Document
PrintDocument printDoc = new PrintDocument();
printDoc.DocumentName = "Print Document";
printDoc.PrintPage += printDoc_PrintPage;
printDlg.Document = printDoc;
#endregion
if(printDlg.ShowDialog() == DialogResult.OK)
printDoc.Print();
}
void printDoc_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString(this.textBox1.Text, this.textBox1.Font, Brushes.Black, 10, 25);
}
Solution 3
Just try with following code
private void MenuItemPrint()
{
if(!string.IsNullOrEmpty(FileName.Trim())
{
PrintDialog printdg = new PrintDialog();
if (printdg.ShowDialog() == DialogResult.OK)
{
PrintDocument pd = new PrintDocument();
pd.PrinterSettings = printdg.PrinterSettings;
pd.PrintPage += PrintPage;
pd.Print();
pd.Dispose();
}
}
}
private void PrintPage(object o, PrintPageEventArgs e)
{
e.Graphics.DrawString(FileName, new Font("Arial", 20), Brushes.Black, 10, 25);
}
![Melody Hajian](https://i.stack.imgur.com/BBW7a.png?s=256&g=1)
Author by
Melody Hajian
Always eager to learn related subjects of my profession and look forward to have more progress.
Updated on July 09, 2022Comments
-
Melody Hajian almost 2 years
I want to print my
TextBox
and here is my code:private void MenuItemPrint() { if (FileName != "") { PrintDocument document = new PrintDocument(); document.PrinterSettings.PrintFileName = FileName; document.Print(); } }
and it doesn't work. What should I do?
-
Melody Hajian over 10 yearsis there any shorter code for that? i simply want to print the content of my textbox..
-
Sudhakar Tillapudi over 10 yearsi think there is no shorter code than this IMO. because you have to write the statements to initialise printDocument ,register the PrintPage Event and finally printing string using drawstring.
-
Sudhakar Tillapudi over 10 yearsactually Trim() function will remove the leading and trailing spaces in a textbox generally which we can not see.if we don't trim the values before comparing then if(" "=="") evaluates to false.
-
Sudhakar Tillapudi over 10 yearsare you able to print now?
-
Sudhakar Tillapudi over 10 yearsYou are Welcome :) I'm Glad to Help You.