I used C# to print a file to PDF using Microsoft Print to PDF printer. The file was successfully generated. But I am not able to open that because Adobe Reader says that the file is damaged. This is the code
PrintDocument pd = new PrintDocument
{
PrinterSettings = new PrinterSettings
{
PrinterName = "Microsoft Print to PDF (redirected 2)",
PrintToFile = true,
PrintFileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/test.pdf"
}
};
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
pd.Print();
But if I use the same code, without PrinterSettings, then it prompts for the destination location and filename. If I specify both, then it generates a pdf file. This, I am able to open using Adobe Reader. Code is shown below
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
pd.Print();
Not sure what am I missing in the first approach. Please help. The below part is the implementation for pd_PrintPage
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;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics);
// Iterate over the file, printing each line.
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 more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
PS: I referred to How to programmatically print to PDF file without prompting for filename in C# using the Microsoft Print To PDF printer that comes with Windows 10 for the code.