fa363b9b8ac1173ee29a87e712c0049.png (61.7 KB)
操作系统:Win10
在此处键入或粘贴代码
try
{
// 检查安装打印机
var isPrinterInstalled = IsPrinterInstalled(printInfo.Printer);
if (!isPrinterInstalled)
{
await UpdatePrintStatusAsync(printInfo, $"找不到目标打印机:{printInfo.Printer}", false);
return;
}
PrinterSettings ps = new PrinterSettings();
ps.PrinterName = printInfo.Printer;
ps.Duplex = Duplex.Simplex;
switch (printInfo.SingleDouble)
{
case Constants.DuplexingTwoSidedLongEdge:
ps.Duplex = Duplex.Vertical;
break;
case Constants.DuplexingTwoSidedShortEdge:
ps.Duplex = Duplex.Horizontal;
break;
}
//检查纸张
PaperSize? paperSize = null;
foreach (PaperSize psz in ps.PaperSizes)
{
if (psz.PaperName.Trim().Equals(printInfo.PaperSize.Trim()))
{
paperSize = psz;
break;
}
}
if (paperSize == null)
{
await UpdatePrintStatusAsync(printInfo, $"打印机{printInfo.Printer},找不到打印纸张:{printInfo.PaperSize}", false);
return;
}
//判断打印机是否支持双面打印
var isDuplexPrinting = printInfo.SingleDouble == Constants.DuplexingTwoSidedLongEdge || printInfo.SingleDouble == Constants.DuplexingTwoSidedShortEdge;
if (isDuplexPrinting && !ps.CanDuplex)
{
await UpdatePrintStatusAsync(printInfo, $"打印机{printInfo.Printer},不支持双面打印", false);
return;
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
PdfViewer viewer = new PdfViewer();
viewer.AutoResize = true;
viewer.AutoRotate = true;
viewer.PrintPageDialog = false;
viewer.PrinterJobName = string.IsNullOrWhiteSpace(printInfo.TaskNo) ? printInfo.RecordId : printInfo.TaskNo;
viewer.EndPrint += (sender, args) =>
{
logger.Information($"完成发送打印文件EndPrintHandler, 文件:{printInfo.FileName},FielPath:{printInfo.FilePath}, recordid: {printInfo.RecordId}");
};
PageSettings pgs = new PageSettings();
pgs.PaperSize = paperSize;
pgs.Color = printInfo.PrintColor == PrintColorEnum.Colorful ? true : false;
pgs.Margins = new Margins(0, 0, 0, 0);
using (var printStream = WatermarkHandle(printInfo))
{
logger.Information($"开始发送打印文件, 打印机:{printInfo.Printer}, 文件:{printInfo.FileName},recordid:{printInfo.RecordId}");
viewer.PrintLargePdf(printStream, pgs, ps);
viewer.Close();
}
if (viewer.PrintStatus != null)
{
if (viewer.PrintStatus is Exception ex)
{
throw ex;
}
}
//停止计时
stopWatch.Stop();
logger.Information($"完成发送打印文件, 打印耗时:{stopWatch.ElapsedMilliseconds}ms, 文件:{printInfo.FileName},FielPath:{printInfo.FilePath},成功发送至目标打印机:{printInfo.Printer}, recordid: {printInfo.RecordId}");
// 打印成功更新
await UpdatePrintStatusAsync(printInfo, $"文件打印成功", true);
}
catch (Exception ex)
{
await UpdatePrintStatusAsync(printInfo, ex.Message, false);
// 打印错误日志记录
logger.Error($"文件打印Error, JSON:{JsonConvert.SerializeObject(printInfo)},异常信息:{ex}");
}