71 lines
2.2 KiB
C#
71 lines
2.2 KiB
C#
using Drab.Core.Configuration;
|
|
using Drab.Logic.Interfaces;
|
|
using Drab.Logic.Models;
|
|
using PdfiumViewer;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Drawing.Printing;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Printing;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Drab.Logic.Services;
|
|
|
|
public class PrintService : IPrintService
|
|
{
|
|
private readonly IDrabSettings _drabSettings;
|
|
|
|
public PrintService(IDrabSettings drabSettings)
|
|
{
|
|
_drabSettings = drabSettings;
|
|
}
|
|
|
|
public async Task<PrintDocumentResult> PrintPdf(PrintDocumentRequest request)
|
|
{
|
|
try
|
|
{
|
|
var oldJobs = GetPrintJobs(request.DokId.ToString());
|
|
if (oldJobs.Any(x => !x.IsRetained))
|
|
{
|
|
oldJobs.ForEach(x => x.Cancel());
|
|
await Task.Delay(TimeSpan.FromSeconds(2));
|
|
}
|
|
|
|
var (filePath, dokId) = request;
|
|
using (var document = PdfDocument.Load(filePath))
|
|
{
|
|
using (var printDocument = document.CreatePrintDocument())
|
|
{
|
|
var fileName = Path.GetFileName(filePath);
|
|
|
|
printDocument.PrinterSettings.PrintFileName = fileName;
|
|
printDocument.DocumentName = dokId.ToString();
|
|
printDocument.PrintController = new StandardPrintController();
|
|
printDocument.Print();
|
|
}
|
|
}
|
|
|
|
await Task.Delay(TimeSpan.FromSeconds(_drabSettings.PrinterTimeoutSeconds));
|
|
|
|
var jobs = GetPrintJobs(request.DokId.ToString());
|
|
if (jobs.Count == 0)
|
|
return new PrintDocumentResult(true, "Print success.");
|
|
|
|
jobs.ForEach(x => x.Cancel());
|
|
return new PrintDocumentResult(false, "Print failed - timeout expired.");
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
return new PrintDocumentResult(false, $"Print failed - {e.Message}");
|
|
}
|
|
}
|
|
|
|
private static List<PrintSystemJobInfo> GetPrintJobs(string jobName)
|
|
{
|
|
var printQueue = LocalPrintServer.GetDefaultPrintQueue();
|
|
return printQueue.GetPrintJobInfoCollection()
|
|
.Where(x => x.Name == jobName)
|
|
.ToList();
|
|
}
|
|
} |