以下代码段是Kendall Bennett的代码的改编版,该代码使用PdfiumViewer库打印pdf文件。主要区别在于使用的是Stream而不是文件。
public bool PrintPDF(
string printer,
string paperName,
int copies, Stream stream)
{
try
{
var printerSettings = new PrinterSettings
{
PrinterName = printer,
Copies = (short)copies,
};
var pageSettings = new PageSettings(printerSettings)
{
Margins = new Margins(0, 0, 0, 0),
};
foreach (PaperSize paperSize in printerSettings.PaperSizes)
{
if (paperSize.PaperName == paperName)
{
pageSettings.PaperSize = paperSize;
break;
}
}
using (var document = PdfiumViewer.PdfDocument.Load(stream))
{
using (var printDocument = document.CreatePrintDocument())
{
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
return true;
}
catch (System.Exception e)
{
return false;
}
}
就我而言,我正在使用称为PdfSharp的库生成PDF文件,然后将文档保存到Stream中,如下所示:
PdfDocument pdf = PdfGenerator.GeneratePdf(printRequest.html, PageSize.A4);
pdf.AddPage();
MemoryStream stream = new MemoryStream();
pdf.Save(stream);
MemoryStream stream2 = new MemoryStream(stream.ToArray());
我想指出的一件事可能对其他开发人员有所帮助,就是即使我运行的是Windows 10 64位版本,我也必须安装32位版本的pdfuim本机dll才能使打印正常。我在Visual Studio中使用NuGet软件包管理器安装了以下两个NuGet软件包:
- PdfiumViewer
- PdfiumViewer.Native.x86.v8-xfa