WPF打印功能
使用PrintDialog创建自带的打印对话框
打印的文件必须为XPS文件,可以使用Spire.Pdf将PDF文件转换为XPS文件然后进行打印的相关操作
以下为核心代码
//将PDF转换为xps文件
var xpsFilePath = Path.Combine(Globals.gTempFile, $"{Path.GetFileNameWithoutExtension(pdfFilePath)}.xps");
using (Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument())
{
doc.LoadFromFile(pdfFilePath);
doc.SaveToFile(xpsFilePath, FileFormat.XPS);
}
//打印功能使用
//创建打印对话框对象并设置选项
PrintDialog pDialog = new PrintDialog();
//打印范围
pDialog.PageRangeSelection = PageRangeSelection.AllPages;
//获取或设置一个值,该值指示“打印”对话框的用户是否可以使用一个选项指定要打印的页范围。
pDialog.UserPageRangeEnabled = true;
//显示对话框。 如果用户按下打印按钮,则返回 true。
Nullable<Boolean> print = pDialog.ShowDialog();
if (print == true)
{
try
{
using (XpsDocument xpsDocument = new XpsDocument(xpsFilePath, FileAccess.ReadWrite))
{
FixedDocumentSequence fixedDocSeq = xpsDocument.GetFixedDocumentSequence();
pDialog.PrintDocument(fixedDocSeq.DocumentPaginator, "Print job");
}
}
catch (Exception e)
{
Trace.WriteLine("e:" + e.ToString());
}
}