Wednesday 21 August 2013

Printing File by using C#

Printing File by using C#

I am developing C# application. In this C# program, i want to add print
button so users may print any document they want by using this button. I
managed to print a txt file by reading it. But if i choose a pdf file
instead, program prints some error codes in result.
private void printButton_Click(object sender, EventArgs e)
{
try
{
streamToPrint = new StreamReader("C:\\test.txt");
try
{
printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.Print();
}
finally
{
streamToPrint.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
while (count < linesPerPage && ((line = streamToPrint.ReadLine()) !=
null))
{
yPos = topMargin + (count *
printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
Besides these, is there any way to open ctrl-p menu on the
document(printing options)? Then user may choose any printer he/she
desires.
I would appreciate your helps.
My regards...

No comments:

Post a Comment