c# 打印

打印demo地址:https://gitee.com/cainiaoA/csprint/tree/master/TestPrint

运行选择平台86,把copy到bin根目录下

打印分装类

public class OutputImage
    {
        public string ImageType { get; set; }
        public bool use_metadata { get; set; }
        public int PageWidth { get; set; }
        public int PageHeight { get; set; }
        public List<byte[]> Images { get; set; }
    }

pdf打印
添加引用:PdfiumViewer.dll和;pdfium.dll

/// <summary>
        /// Pdfium PNG图打印
        /// </summary>
        private void PrintPDF(OutputImage outputImage, string printer)
        {
            PrinterSettings printerSettings = new PrinterSettings();
            printerSettings.PrinterName = printer;
            PaperSize ps = new PaperSize("custom", outputImage.PageWidth, outputImage.PageHeight);
            printerSettings.DefaultPageSettings.PaperSize = ps;
            foreach (var file in outputImage.Images)
            {
                using (var stream = new MemoryStream(file))
                {
                    var pdfDocument = PdfDocument.Load(stream);
                    for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++)
                    {
                        PrintPage(outputImage.ImageType, printerSettings, (obj, ev) =>
                         {
                             var dpiX = ev.Graphics.DpiX;
                             var dpiY = ev.Graphics.DpiY;
                             var printableArea = ev.PageSettings.PrintableArea; //获取打印区域大小

                             if (outputImage.use_metadata)
                             {
                                 //使用元数据打印
                                 Rectangle PrintableRectangle = new Rectangle(
                                                    0,
                                                    0,
                                                    (int)(dpiX / 100.0 * printableArea.Width),
                                                    (int)(dpiY / 100.0 * printableArea.Height));
                                 pdfDocument.Render(pageIndex, ev.Graphics, dpiX, dpiY, PrintableRectangle, PdfRenderFlags.ForPrinting | PdfRenderFlags.Annotations);
                             }
                             else
                             {
                                 //使用图片打印
                                 var pageSize = pdfDocument.PageSizes[pageIndex];
                                 var num1 = 600 / pageSize.Width;
                                 var num2 = 600 / pageSize.Height;
                                 var sx = (num1 < num2) ? num1 : num2;
                                 int width, height;
                                 if (sx < 1)
                                 {
                                     width = AdjustDpi(pageSize.Width * sx);
                                     height = AdjustDpi(pageSize.Height * sx);
                                 }
                                 else
                                 {
                                     width = AdjustDpi(pageSize.Width);
                                     height = AdjustDpi(pageSize.Height);
                                 }
                                 using (var image = pdfDocument.Render(pageIndex, width, height, dpiX, dpiY, false))
                                 {
                                     RectangleF printableRectangleF = new RectangleF(0F, 0F, printableArea.Width, printableArea.Height);
                                     ev.Graphics.DrawImage(image, printableRectangleF);
                                 }
                             }
                             ev.Graphics.Dispose();
                             //GC.WaitForPendingFinalizers();
                         });
                    }
                }
            }
        }

private static int AdjustDpi(double value)
        {
            return (int)((value / 72f) * 600f);
        }

 EPL或EPL2打印

 private void PrintEPL2(OutputImage outputImage, string printer)
        {
            PrinterSettings printerSettings = new PrinterSettings();
            printerSettings.PrinterName = printer;
            PaperSize ps = new PaperSize("custom", outputImage.PageWidth, outputImage.PageHeight);
            printerSettings.DefaultPageSettings.PaperSize = ps;
            foreach (var file in outputImage.Images)
            {
                PrintPage(outputImage.ImageType, printerSettings, (obj, ev) =>
                {
                    WritePageBytes(file);
                });
            }
        }

EMF打印

private void PrintEMF(OutputImage outputImage, string printer)
        {
            PrinterSettings printerSettings = new PrinterSettings();
            printerSettings.PrinterName = printer;
            PaperSize ps = new PaperSize("custom", outputImage.PageWidth, outputImage.PageHeight);
            printerSettings.DefaultPageSettings.PaperSize = ps;

            foreach (var file in outputImage.Images)
            {
                PrintPage(outputImage.ImageType, printerSettings, (obj, ev) =>
                {
                    var bytes = MetaFile.Play(file);
                    using (var stream = new MemoryStream(bytes))
                    {
                        Metafile image = new Metafile(stream);
                        var pageSize = ev.PageSettings.PrintableArea; //获取打印区域大小
                        System.Drawing.Rectangle PrintableRectangle = new System.Drawing.Rectangle(
                            0,
                            0,
                            (int)pageSize.Width,
                            (int)pageSize.Height);
                        ev.Graphics.DrawImage(image, PrintableRectangle);
                        GC.WaitForPendingFinalizers();
                    }
                });
            }
        }

PNG;JPG打印

private void PrintPNG(OutputImage outputImage, string printer)
        {
            PrinterSettings printerSettings = new PrinterSettings();
            printerSettings.PrinterName = printer;
            PaperSize ps = new PaperSize("custom", outputImage.PageWidth, outputImage.PageHeight);
            printerSettings.DefaultPageSettings.PaperSize = ps;
            foreach (var file in outputImage.Images)
            {
                PrintPage(outputImage.ImageType, printerSettings, (obj, ev) =>
                {
                    using (var stream = new MemoryStream(file))
                    {
                        var pageSize = ev.PageSettings.PrintableArea; //获取打印区域大小
                        System.Drawing.Rectangle PrintableRectangle = new System.Drawing.Rectangle(
                        0,
                        0,
                        (int)pageSize.Width,
                        (int)pageSize.Height);
                        ev.Graphics.DrawImage(Image.FromStream(stream), PrintableRectangle);
                        GC.WaitForPendingFinalizers();
                    }
                });
            }
        }

分装的打印

public class PrintManager : IDisposable
    {
        private string _lastImageType;
        private IPagePrinter _PagePrinter;

        public void PrintPage(string imageType, PrinterSettings printerSettings, PrintPageEventHandler pageEventHandler)
        {
            if (_lastImageType != imageType)
            {
                if (_PagePrinter != null)
                    _PagePrinter.Dispose();

                switch (imageType)
                {
                    case "EPL":
                    case "EPL2":
                        _PagePrinter = new RawPagePrinter();
                        break;
                    default:
                        _PagePrinter = new ImagePagePrinter();
                        break;
                }
                _lastImageType = imageType;
            }

            _PagePrinter.PrintPage(printerSettings, pageEventHandler);
        }

        public bool WritePageBytes(byte[] pBytes)
        {
            if (_PagePrinter != null)
                return _PagePrinter.WritePageBytes(pBytes);
            return false;
        }

        public void Dispose()
        {
            if (_PagePrinter != null)
                _PagePrinter.Dispose();

            _lastImageType = null;
        }
    }

    public interface IPagePrinter : IDisposable
    {
        void PrintPage(PrinterSettings printerSettings, PrintPageEventHandler pageEventHandler);
        bool WritePageBytes(byte[] pBytes);
    }

    public class ImagePagePrinter : IPagePrinter
    {
        private readonly Hashtable _htPrints = new Hashtable();

        public void PrintPage(PrinterSettings printerSettings, PrintPageEventHandler pageEventHandler)
        {
            var controller = (ImagePrintController)_htPrints[printerSettings.PrinterName];
            if (controller == null)
            {
                controller = new ImagePrintController();
                _htPrints.Add(printerSettings.PrinterName, controller);
            }

            var printDocument = new PrintDocument();
            printDocument.PrintController = controller;
            AdjustPageSize(printerSettings, printDocument.PrinterSettings);
            printDocument.PrinterSettings = printerSettings;
            printDocument.QueryPageSettings += (sender, e) =>
            {
                e.PageSettings = ((PrintDocument)sender).DefaultPageSettings;
            };
            printDocument.PrintPage += pageEventHandler;
            printDocument.Print();
        }

        private void AdjustPageSize(PrinterSettings expectSettings, PrinterSettings devicerSetting)
        {
            if (expectSettings != null)
            {
                devicerSetting.PrinterName = expectSettings.PrinterName;
                var expectPageSize = expectSettings.DefaultPageSettings.PaperSize;
                if (expectPageSize.Width != 0 || expectPageSize.Height != 0)
                {
                    PaperSize printPaperSize = devicerSetting.DefaultPageSettings.PaperSize;
                    if (printPaperSize.Width < expectPageSize.Width || printPaperSize.Height < expectPageSize.Height)
                    {
                        PaperSize ps = new PaperSize("custom", expectPageSize.Width, expectPageSize.Height);
                        ps.RawKind = 256;
                        devicerSetting.DefaultPageSettings.PaperSize = ps;
                    }
                    else
                        expectSettings.DefaultPageSettings.PaperSize = devicerSetting.DefaultPageSettings.PaperSize;
                }
            }
        }

        public void Dispose()
        {
            try
            {
                foreach (ImagePrintController printController in _htPrints.Values)
                {
                    printController.Dispose();
                }
                _htPrints.Clear();
            }
            catch
            {
            }

        }

        public bool WritePageBytes(byte[] pBytes)
        {
            throw new NotImplementedException();
        }
    }

    public class ImagePrintController : StandardPrintController, IDisposable
    {
        PrintDocument _document;
        PrintEventArgs _printEventArgs;
        public override void OnStartPrint(PrintDocument document, PrintEventArgs e)
        {
            if (_document == null)
            {
                base.OnStartPrint(document, e);
                _document = document;
                _printEventArgs = e;
            }
        }

        public override void OnEndPrint(PrintDocument document, PrintEventArgs e)
        {
        }

        public void Dispose()
        {
            if (_document != null && _printEventArgs != null)
                base.OnEndPrint(_document, _printEventArgs);
        }
    }

    public class RawPagePrinter : IPagePrinter
    {
        private readonly Hashtable _htPrints = new Hashtable();
        IntPtr _hPrinter;

        public void PrintPage(PrinterSettings printerSettings, PrintPageEventHandler pageEventHandler)
        {
            var _printArgs = _htPrints[printerSettings.PrinterName];
            if (_printArgs == null)
            {
                IntPtr hPrinter;
                WinDrvPort.DOCINFOA di = new WinDrvPort.DOCINFOA();
                di.pDocName = "Printer Command";
                di.pDataType = "RAW";
                if (WinDrvPort.OpenPrinter(printerSettings.PrinterName, out hPrinter, IntPtr.Zero))
                {
                    var flag = WinDrvPort.StartDocPrinter(hPrinter, 1, di);
                    flag = WinDrvPort.StartPagePrinter(hPrinter);
                    _htPrints.Add(printerSettings.PrinterName, hPrinter);
                    _hPrinter = hPrinter;
                    Console.WriteLine(flag);
                }
            }

            pageEventHandler(null, null);
        }

        public bool WritePageBytes(byte[] pBytes)
        {
            int errorCode;
            bool flag = false;
            int dwWritten = 0;
            int count = pBytes.Length;
            var destination = Marshal.AllocCoTaskMem(count);
            Marshal.Copy(pBytes, 0, destination, count);
            flag = WinDrvPort.WritePrinter(_hPrinter, destination, count, out dwWritten);
            Marshal.FreeCoTaskMem(destination);

            if (!flag)
            {
                errorCode = Marshal.GetLastWin32Error();
                Console.WriteLine(errorCode);
            }
            return flag;
        }

        public void Dispose()
        {
            try
            {
                foreach (IntPtr hPrinter in _htPrints.Values)
                {
                    WinDrvPort.EndPagePrinter(_hPrinter);
                    WinDrvPort.EndDocPrinter(hPrinter);
                    WinDrvPort.ClosePrinter(hPrinter);
                }
            }
            catch
            {
            }
        }
    }

 

posted @ 2019-10-18 15:35  世人皆萌  阅读(3381)  评论(0编辑  收藏  举报