Thursday, November 29, 2018

C# MVC load the PDF without using Acrobat Reader, then send the PDF pages as images to the printer

C# code:

        private RasterImage PDFImage = null;
        private int currentPrintPageNumber;

        private void menuItem1_Click(object sender, EventArgs e)
        {
            using (RasterCodecs codecs = new RasterCodecs())
            {
                codecs.Options.Load.AllPages = true;

               // Load PDF as Image
               PDFImage = codecs.Load(@"Source.pdf");

               // Print
                using(PrintDocument document = new PrintDocument())
                {
                    currentPrintPageNumber = 1;
                    document.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
                    document.Print();
                }
                PDFImage.Dispose();
            }
        }

        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            PrintDocument document = sender as PrintDocument;
            RasterImagePrinter printer = new RasterImagePrinter();
            printer.PrintDocument = document;
            printer.SizeMode = RasterPaintSizeMode.FitAlways;
            printer.HorizontalAlignMode = RasterPaintAlignMode.Center;
            printer.VerticalAlignMode = RasterPaintAlignMode.Center;
            printer.PageRectangle = Rectangle.Empty;
            printer.ImageRectangle = Rectangle.Empty;
            printer.UseMargins = false;
            printer.Print(PDFImage, currentPrintPageNumber, e);
            currentPrintPageNumber++;
           
            if(currentPrintPageNumber <= PDFImage.PageCount)
                e.HasMorePages = true;
            else
                e.HasMorePages = false;
            printer.PrintDocument = null;
        }  

No comments:

Post a Comment