e.PageNumber 报错
时间: 2023-07-22 21:06:59 浏览: 46
非常抱歉,我之前的回答中有一个错误。在PrintPage事件处理程序中,`e.PageNumber`是无效的。请改用`e.HasMorePages`属性来判断是否还有更多的页面需要打印。以下是修改后的示例代码:
```csharp
using System.Drawing.Printing;
using PdfSharpCore.Pdf;
using PdfSharpCore.Pdf.IO;
class Program
{
static void Main(string[] args)
{
string pdfFilePath = "path/to/your/pdf/file.pdf";
string printerName = "Your Printer Name";
PrintDocument printDoc = new PrintDocument();
printDoc.PrinterSettings.PrinterName = printerName;
int currentPage = 0;
printDoc.PrintPage += (sender, e) =>
{
PdfDocument pdfDoc = PdfReader.Open(pdfFilePath, PdfDocumentOpenMode.Import);
if (currentPage < pdfDoc.PageCount)
{
PdfPage page = pdfDoc.Pages[currentPage];
// 使用e.Graphics绘制页面内容
// ...
currentPage++;
e.HasMorePages = currentPage < pdfDoc.PageCount;
}
else
{
e.HasMorePages = false;
}
};
printDoc.Print();
}
}
```
在上面的代码中,我们使用一个`currentPage`变量来跟踪当前要打印的页面索引。在每次PrintPage事件触发时,我们检查是否还有更多的页面需要打印。如果有,我们取出对应索引的PdfPage,并使用`e.Graphics`绘制页面内容。然后,我们更新`currentPage`变量,并设置`e.HasMorePages`属性来指示是否还有更多的页面需要打印。
请注意,在实际使用时,您需要将`pdfFilePath`替换为要打印的PDF文件的路径,并将`printerName`替换为要使用的打印机的名称。确保已正确安装和配置所需的打印机驱动程序。