Example #1
0
        /// <summary>
        /// Raises the System.Drawing.Printing.PrintDocument.PrintPage event. It is called
        /// before a page prints.
        /// </summary>
        /// <param name="e"> A System.Drawing.Printing.PrintPageEventArgs that contains the event data.</param>
        protected override void OnPrintPage(PrintPageEventArgs e)
        {
            base.OnPrintPage(e);

            IntPtr hdc         = IntPtr.Zero;
            IntPtr currentPage = IntPtr.Zero;

            try
            {
                if (e.Cancel)
                {
                    return;
                }

                currentPage = Pdfium.FPDF_LoadPage(_docForPrint, _pageForPrint);
                if (currentPage == IntPtr.Zero)
                {
                    e.Cancel = true;
                    return;
                }

                double dpiX = e.Graphics.DpiX;
                double dpiY = e.Graphics.DpiY;

                double width, height;
                double x, y;
                CalcSize(currentPage, dpiX, dpiY, e.PageSettings.PrintableArea, e.PageSettings.Landscape, out width, out height, out x, out y);
                PageRotate rotation = CalcRotation(currentPage, e.PageSettings.Landscape, ref width, ref height, ref x, ref y);

                using (var page = PdfPage.FromHandle(_pdfDoc, currentPage, _pageForPrint))
                {
                    OnBeforeRenderPage(page, width, height, rotation);
                }

                hdc = e.Graphics.GetHdc();
                Pdfium.SetWorldTransform(hdc, new FS_MATRIX(1, 0, 0, 1, x, y));
                Pdfium.FPDF_RenderPage(
                    hdc,
                    currentPage,
                    (int)0,
                    (int)0,
                    (int)(width),
                    (int)(height),
                    rotation,
                    RenderFlags);

                //Print next page
                if (_pageForPrint < PrinterSettings.ToPage - (_useDP ? PrinterSettings.FromPage : 1))
                {
                    _pageForPrint++;
                    e.HasMorePages = true;
                }
            }
            finally
            {
                if (hdc != IntPtr.Zero)
                {
                    e.Graphics.ReleaseHdc(hdc);
                }
                hdc = IntPtr.Zero;
                if (currentPage != IntPtr.Zero)
                {
                    Pdfium.FPDF_ClosePage(currentPage);
                }
                currentPage = IntPtr.Zero;
            }
        }