无法打开使用C#编写的打印到pdf代码生成的PDF [英] Unable to open the PDF, which was generated using print to pdf code written in C#
问题描述
我使用C#使用Microsoft Print to PDF打印机将文件打印为PDF.文件已成功生成.但是我无法打开它,因为Adobe Reader说文件已损坏.这是代码
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();
但是,如果我使用相同的代码,但没有PrinterSettings,则会提示输入目标位置和文件名.如果同时指定两者,则将生成一个pdf文件.这样,我可以使用Adobe Reader打开.代码如下所示
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();
不确定第一种方法中我缺少什么.请帮忙.下一部分是pd_PrintPage的实现
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;
}