Exemplo n.º 1
0
        /// <summary>
        /// Start/Continue progressive rendering for specified page
        /// </summary>
        /// <param name="page">Pdf page object</param>
        /// <param name="pageRect">Actual page's rectangle. </param>
        /// <param name="pageRotate">Page orientation: 0 (normal), 1 (rotated 90 degrees clockwise), 2 (rotated 180 degrees), 3 (rotated 90 degrees counter-clockwise).</param>
        /// <param name="renderFlags">0 for normal display, or combination of flags defined above.</param>
        /// <param name="useProgressiveRender">True for use progressive render</param>
        /// <returns>Null if page still painting, PdfBitmap object if page successfully rendered.</returns>
        internal bool RenderPage(PdfPage page, Rectangle pageRect, PageRotate pageRotate, RenderFlags renderFlags, bool useProgressiveRender)
        {
            if (!this.ContainsKey(page))
            {
                ProcessNew(page); //Add new page into collection
                if (PaintBackground != null)
                {
                    PaintBackground(this, new EventArgs <Rectangle>(pageRect));
                }
            }

            if ((renderFlags & (RenderFlags.FPDF_THUMBNAIL | RenderFlags.FPDF_HQTHUMBNAIL)) != 0)
            {
                this[page].status = ProgressiveRenderingStatuses.RenderDone + 4;
            }
            else if (!useProgressiveRender)
            {
                this[page].status = ProgressiveRenderingStatuses.RenderDone + 3;
            }

            PdfBitmap bitmap = this[page].Bitmap;
            bool      ret    = ProcessExisting(bitmap ?? CanvasBitmap, page, pageRect, pageRotate, renderFlags);

            if (bitmap != null)
            {
                Pdfium.FPDFBitmap_CompositeBitmap(CanvasBitmap.Handle, pageRect.X, pageRect.Y, pageRect.Width, pageRect.Height, bitmap.Handle, pageRect.X, pageRect.Y, BlendTypes.FXDIB_BLEND_NORMAL);
            }
            return(ret);
        }
Exemplo n.º 2
0
        public void ExportToPDF()
        {
            if (InvokeRequired)
            {
                BeginInvoke(new MethodInvoker(ExportToPng));
            }
            else
            {
                chart1.SaveImage("test.png", ChartImageFormat.Png);
            }

            PdfDocument document = new PdfDocument();

            document.PageSettings.Margins.All = 0;
            MemoryStream ms = new MemoryStream();

            document.Save(ms);
            PdfImage image = new PdfBitmap("test.png");
            PdfPage  page  = document.Pages.Add();

            //Draw chart as image
            page.Graphics.DrawImage(image, new RectangleF(100, 100, 450, 300));
            //Save and close PDF document
            document.Save("test.pdf");
            document.Close(true);
        }
        static void Main(string[] args)
        {
            //Create an object of PdfDocument class and load the PDF from file
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\Input.pdf");

            //Disable incremental update
            doc.FileInfo.IncrementalUpdate = false;

            //Traverse all PDF pages and extract images
            foreach (PdfPageBase page in doc.Pages)
            {
                Image[] images = page.ExtractImages();
                //Traverse all images
                if (images != null && images.Length > 0)
                {
                    for (int j = 0; j < images.Length; j++)
                    {
                        Image     image = images[j];
                        PdfBitmap bp    = new PdfBitmap(image);
                        //Set bp.Quality values to compress images
                        bp.Quality = 20;
                        //Replace the images with newly compressed images
                        page.ReplaceImage(j, bp);
                    }
                }
            }
            //Save to file
            doc.SaveToFile("Output2.pdf");
        }
Exemplo n.º 4
0
        private void crearCredencial(Persona persona)
        {
            using (PdfDocument document = new PdfDocument())
            {
                //Agrego una pagina al doc
                PdfPage page = document.Pages.Add();

                //Se generan los graficos para el PDF
                PdfGraphics graphics = page.Graphics;

                //Defino la fuente
                PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);

                //Escribo las credenciales
                graphics.DrawString("CREDENCIAL DE EMPLEADO", font, PdfBrushes.Black, new PointF(150, 5));
                graphics.DrawString(persona.Cuil.ToString(), font, PdfBrushes.Black, new PointF(150, 30));
                graphics.DrawString("Nombre: " + persona.Nombre, font, PdfBrushes.Black, new PointF(150, 55));
                graphics.DrawString("Apellido: " + persona.Apellido, font, PdfBrushes.Black, new PointF(150, 80));
                graphics.DrawString(persona.Cargo.Area.Nombre + " - " + persona.Cargo.Nombre, font, PdfBrushes.Black, new PointF(150, 105));

                //Genero y escribo el QR
                Zen.Barcode.CodeQrBarcodeDraw qrcode = Zen.Barcode.BarcodeDrawFactory.CodeQr;
                PdfBitmap image = new PdfBitmap(qrcode.Draw(persona.Cuil.ToString(), 60));
                graphics.DrawImage(image, 0, 0);

                //Guardo el PDF
                document.Save("C://SiADi-Credenciales/Credencial " + persona.Apellido + " " + persona.Nombre + ".pdf");
                MessageBox.Show("Credencial guardada en: \nC://SiADi-Credenciales/Credencial " + persona.Apellido + " " + persona.Nombre + ".pdf", "SiADi", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 5
0
        public async Task GeneratePdf()
        {
            using var stream = new FileStream($"{_subfolder}.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            PdfDocument document = new PdfDocument();

            var files = Directory.GetFiles(_subfolder, "*.*").Select(f => f.Split(Path.DirectorySeparatorChar).Last()).ToList();

            foreach (var file in files.OrderBy(z => int.Parse(z.Split(".").First())))
            {
                // Add a page
                PdfPage page = document.Pages.Add();

                // Load the image from the disk
                using var img = new FileStream(Path.Combine(_subfolder, file), FileMode.Open, FileAccess.Read);
                PdfBitmap image = new PdfBitmap(img);

                // Draw the image with image bounds
                SizeF pageSize = page.GetClientSize();
                page.Graphics.DrawImage(image, new RectangleF(0, 0, pageSize.Width, pageSize.Height));
            }

            // Save the document
            document.Save(stream);
            document.Close(true);

            // Mark the file as downloaded & remove the download folder
            await _filesContext.AddDownloadedAsync(_albumName);

            Directory.Delete(_subfolder, true);
        }
Exemplo n.º 6
0
        public void AddImage(string imagePath, int x, int y, int w, int h)
        {
            Stream   pngImageStream = UTILS.ImageToStream(imagePath);
            PdfImage pngImage       = new PdfBitmap(pngImageStream);

            m_grapics.DrawImage(pngImage, x, y, w, h);
        }
Exemplo n.º 7
0
        public static Bitmap PDFRenderBitmap(PdfPage page, decimal dpiX, decimal dpiY)
        {
            try
            {
                int width  = (int)(page.Width / 72 * Decimal.ToDouble(dpiX));
                int height = (int)(page.Height / 72 * Decimal.ToDouble(dpiY));

                using (PdfBitmap pdfBitmap = new PdfBitmap(width, height, true))
                {
                    pdfBitmap.FillRect(0, 0, width, height, Patagames.Pdf.FS_COLOR.White);
                    page.Render(pdfBitmap, 0, 0, width, height, PageRotate.Normal, RenderFlags.FPDF_PRINTING);

                    if (pdfBitmap.Image == null)
                    {
                        AppLogger.Warn("Failed to get image bitmap from PDFium image object.");
                        return(null);
                    }

                    Bitmap newBitmap = new Bitmap(pdfBitmap.Image);
                    newBitmap.SetResolution((float)dpiX, (float)dpiY);
                    return(newBitmap);
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("p:pdfPage", page);
                throw;
            }
        }
Exemplo n.º 8
0
        private void Draw(PdfGraphics g, PdfObjects.Image image)
        {
            using (var stream = new FileStream(image.ImagePath, FileMode.Open))
            {
                using (var bitmap = new PdfBitmap(stream))
                {
                    float x      = (float)image.Layout.X;
                    float y      = (float)image.Layout.Y;
                    float width  = (float)image.Layout.Width;
                    float height = (float)image.Layout.Height;

                    if (image.PreserveRatio)
                    {
                        height = bitmap.Height * (width / bitmap.Width);

                        // If we went the wrong way
                        if (height > image.Layout.Height)
                        {
                            height = (float)image.Layout.Height;
                            width  = bitmap.Width * (height / bitmap.Height);
                        }
                    }

                    g.DrawImage(bitmap, new PointF(x, y), new SizeF(width, height));
                }
            }
        }
Exemplo n.º 9
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Stream            docStream = typeof(StampDocument).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Essential_Studio.pdf");
            PdfLoadedDocument ldoc      = new PdfLoadedDocument(docStream);

            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 36f);

            foreach (PdfPageBase lPage in ldoc.Pages)
            {
                PdfGraphics      g     = lPage.Graphics;
                PdfGraphicsState state = g.Save();
                g.SetTransparency(0.25f);
                g.RotateTransform(-40);
                g.DrawString(stampText.Text, font, PdfPens.Red, PdfBrushes.Red, new PointF(-150, 450));

                if (imagewatermark.IsChecked.Value)
                {
                    Stream   imagestream = typeof(StampDocument).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Ani.gif");
                    PdfImage image       = new PdfBitmap(imagestream);
                    g.Restore(state);
                    g.SetTransparency(0.25f);
                    g.DrawImage(image, 0, 0, lPage.Graphics.ClientSize.Width, lPage.Graphics.ClientSize.Height);
                    imagestream.Dispose();
                }
            }
            MemoryStream stream = new MemoryStream();
            await ldoc.SaveAsync(stream);

            ldoc.Close(true);
            Save(stream, "StampDocument.pdf");

            docStream.Dispose();
        }
Exemplo n.º 10
0
        public void SaveToPDF(string fileName)
        {
            RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
                (int)GraphCanvas.ActualWidth, (int)GraphCanvas.ActualHeight,
                96d, 96d, PixelFormats.Pbgra32);

            GraphCanvas.Measure(new Size((int)GraphCanvas.ActualWidth, (int)GraphCanvas.ActualHeight));
            GraphCanvas.Arrange(new Rect(new Size((int)GraphCanvas.ActualWidth, (int)GraphCanvas.ActualHeight)));

            renderBitmap.Render(GraphCanvas);


            using (PdfDocument document = new PdfDocument())
            {
                PdfPage     page     = document.Pages.Add();
                PdfGraphics graphics = page.Graphics;

                using (var ms = new MemoryStream())
                {
                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                    encoder.Save(ms);
                    PdfBitmap image = new PdfBitmap(ms);
                    graphics.DrawImage(image, 0, 0);

                    document.Save(fileName);
                }
            }
        }
Exemplo n.º 11
0
        private void button2_Click(object sender, EventArgs e)
        {
            //create a pdf document
            string      pdfFile = @"E:\HTTPPost\Example.pdf";
            PdfDocument doc     = new PdfDocument();

            doc.LoadFromFile(pdfFile);

            //add a new page
            PdfPageBase page = doc.Pages[0];

            //create a layer named "red line"
            PdfPageLayer layer = page.PageLayers.Add();

            layer.Graphics.DrawLine(new PdfPen(PdfBrushes.Red, 1), new PointF(50, 50), new PointF(100, 100));
            PdfImage image = new PdfBitmap(@"E:\HTTPPost\name.bmp");

            layer.Graphics.DrawImage(image, new RectangleF(100, 100, 40, 20));

            //save pdf document
            string output = @"E:\HTTPPost\AddLayers.pdf";

            doc.SaveToFile(output);

            System.Diagnostics.Process.Start(output);
        }
Exemplo n.º 12
0
 public byte[] ImageToPDF(Stream file)
 {
     _logger.LogDebug($"Start convert image files");
     byte[] buff;
     try
     {
         using (MemoryStream memoryStream = new MemoryStream())
             using (PdfDocument document = new PdfDocument())
             {
                 PdfPage     page        = document.Pages.Add();
                 PdfGraphics pdfGraphics = page.Graphics;
                 PdfBitmap   image       = new PdfBitmap(file);
                 pdfGraphics.DrawImage(image, 0, 0);
                 document.Save(memoryStream);
                 memoryStream.Position = 0;
                 buff = memoryStream.ToArray();
                 _logger.LogDebug("FileInfoPDFService.ImageToPDF....OK");
                 return(buff);
             }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex.Message);
     }
     return(null);
 }
Exemplo n.º 13
0
        private static void PdfToImages()
        {
            int dpi   = 96;
            var watch = new Stopwatch();

            watch.Start();
            using (var doc = PdfDocument.Load($"{_projectDir}\\Samples\\input.pdf"))
            {
                int pageCount = doc.Pages.Count;
                for (int index = 0; index < pageCount; index++)
                {
                    var page   = doc.Pages[index];
                    int width  = (int)(page.Width / 72.0 * dpi);
                    int height = (int)(page.Height / 72.0 * dpi);
                    using (var bitmap = new PdfBitmap(width, height, true))
                    {
                        bitmap.FillRect(0, 0, width, height, FS_COLOR.White);
                        page.Render(bitmap, 0, 0, width, height, PageRotate.Normal, RenderFlags.FPDF_LCD_TEXT);
                        bitmap.Image.Save($"{_projectDir}\\Samples\\outputs\\output_{index}.jpg", ImageFormat.Jpeg);
                    }
                }
                watch.Stop();
                Console.WriteLine($"Converting {pageCount} pages took {watch.Elapsed.TotalSeconds} seconds");
            }
        }
Exemplo n.º 14
0
        //Convert an image to a PDF file
        public static void ConvertImageToPdf(string inputImageFilePath)
        {
            try
            {
                Console.WriteLine("Converting image to a PDF file...");

                var document = new PdfDocument();
                var page     = document.Pages.Add();
                var graphics = page.Graphics;

                var image = new PdfBitmap(inputImageFilePath);
                graphics.DrawImage(image, 0, 0);

                var inputFileName  = Path.GetFileNameWithoutExtension(inputImageFilePath);
                var targetFilePath = Path.GetDirectoryName(inputImageFilePath) + @"\" + inputFileName + "-ConvertedImage.pdf";
                document.Save(targetFilePath);
                document.Close(true);

                Console.WriteLine("Image converted to PDF and saved");
            }
            catch
            {
                throw;
            }
        }
Exemplo n.º 15
0
        //private void PDF_PreviewMouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        //{
        //    Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
        //    saveFileDialog.Filter = "PDF File|*.pdf";
        //    saveFileDialog.Title = "Save to a PDF file";
        //    saveFileDialog.ShowDialog();
        //    if (!string.IsNullOrEmpty(saveFileDialog.FileName))
        //    {
        //        float docWidth = (float)diagramView.Page.ActualWidth;
        //        float docHeight = (float)diagramView.Page.ActualHeight;
        //        string jpgFileName = "tempjpg.jpg";
        //        string xpsFileName = "tempXpS.xps";
        //        Syncfusion.XPS.XPSToPdfConverter xpsTopdfConverter = new Syncfusion.XPS.XPSToPdfConverter();
        //        Syncfusion.Pdf.Graphics.PdfUnitConvertor converter = new Syncfusion.Pdf.Graphics.PdfUnitConvertor();
        //        float pdfHeight = converter.ConvertUnits(docHeight, Syncfusion.Pdf.Graphics.PdfGraphicsUnit.Inch, Syncfusion.Pdf.Graphics.PdfGraphicsUnit.Point);
        //        float pdfWidth = converter.ConvertUnits(docWidth, Syncfusion.Pdf.Graphics.PdfGraphicsUnit.Inch, Syncfusion.Pdf.Graphics.PdfGraphicsUnit.Point);
        //        System.Drawing.SizeF pageSize = new System.Drawing.SizeF(pdfWidth, pdfHeight);
        //        diagramView.Save(jpgFileName, new Size(docWidth * 1.5, docHeight * 1.5), ImageStretch.Expand);
        //        Syncfusion.Pdf.PdfDocument pdfDocument = new Syncfusion.Pdf.PdfDocument();
        //        pdfDocument.PageSettings.Orientation = PdfPageOrientation.Landscape;
        //        pdfDocument.PageSettings.Margins.All = 0;
        //        PdfImage image = new PdfBitmap(jpgFileName);
        //        pdfDocument.PageSettings.Size = image.PhysicalDimension;
        //        Syncfusion.Pdf.PdfPage page = pdfDocument.Pages.Add();
        //        page.Graphics.DrawImage(image, 0, 0);
        //        pdfDocument.Save(saveFileDialog.FileName);
        //        pdfDocument.Close(true);
        //        UpadteImageformat();
        //    }
        //}

        private void ExportToPDF_Click_1(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog.Filter   = "PDF File|*.pdf";
            saveFileDialog.Title    = "Save to a PDF file";
            saveFileDialog.FileName = "Diagram";
            saveFileDialog.ShowDialog();
            if (!string.IsNullOrEmpty(saveFileDialog.FileName))
            {
                float  docWidth    = (float)diagramView.Page.ActualWidth;
                float  docHeight   = (float)diagramView.Page.ActualHeight;
                string jpgFileName = "tempjpg.jpg";
                string xpsFileName = "tempXpS.xps";
                Syncfusion.XPS.XPSToPdfConverter         xpsTopdfConverter = new Syncfusion.XPS.XPSToPdfConverter();
                Syncfusion.Pdf.Graphics.PdfUnitConvertor converter         = new Syncfusion.Pdf.Graphics.PdfUnitConvertor();
                float pdfHeight = converter.ConvertUnits(docHeight, Syncfusion.Pdf.Graphics.PdfGraphicsUnit.Inch, Syncfusion.Pdf.Graphics.PdfGraphicsUnit.Point);
                float pdfWidth  = converter.ConvertUnits(docWidth, Syncfusion.Pdf.Graphics.PdfGraphicsUnit.Inch, Syncfusion.Pdf.Graphics.PdfGraphicsUnit.Point);
                System.Drawing.SizeF pageSize = new System.Drawing.SizeF(pdfWidth, pdfHeight);
                diagramView.Save(jpgFileName, new Size(docWidth * 1.5, docHeight * 1.5), ImageStretch.Expand);
                Syncfusion.Pdf.PdfDocument pdfDocument = new Syncfusion.Pdf.PdfDocument();
                pdfDocument.PageSettings.Orientation = PdfPageOrientation.Landscape;
                pdfDocument.PageSettings.Margins.All = 0;
                PdfImage image = new PdfBitmap(jpgFileName);
                pdfDocument.PageSettings.Size = image.PhysicalDimension;
                Syncfusion.Pdf.PdfPage page = pdfDocument.Pages.Add();
                page.Graphics.DrawImage(image, 0, 0);
                pdfDocument.Save(saveFileDialog.FileName);
                pdfDocument.Close(true);
                //UpadteImageformat();
            }
        }
Exemplo n.º 16
0
        async void ValidateSignatureAndUpload()
        {
            Dialog.ShowLoading("");

            if (Contract.SignImageSource != null)
            {
                PdfDocument duplicate = (PdfDocument)Contract.Document.Clone();


                var addPage = duplicate.Pages.Add();

                var width = addPage.GetClientSize().Width;

                PdfGraphics graphics = addPage.Graphics;

                PdfBitmap image = new PdfBitmap(new MemoryStream(contract.SignImageSource));

                graphics.DrawImage(image, new RectangleF(20, 40, width / 2, 60));


                MemoryStream m = new MemoryStream();

                duplicate.Save(m);

                var document = await StoreManager.DocumentStore.GetItemByContractId(Contract.Id, "saleContract");

                if (document == null)
                {
                    var documentItem = new Document()
                    {
                        Path = Contract.Id + '/' + "saleContract.pdf", Name = contract.Id + ".pdf", InternalName = "saleContract", ReferenceKind = "contract", ReferenceId = contract.Id, MimeType = "application/pdf"
                    };

                    var uploaded = await StoreManager.DocumentStore.InsertImage(m.ToArray(), documentItem);
                }
                else
                {
                    await PclStorage.SaveFileLocal(m.ToArray(), document.Id);

                    document.ToUpload = true;

                    await StoreManager.DocumentStore.UpdateAsync(document);

                    await StoreManager.DocumentStore.OfflineUploadSync();
                }

                Contract.ToSend = true;

                var isSent = await StoreManager.ContractStore.UpdateAsync(Contract);

                if (isSent)
                {
                    await CoreMethods.DisplayAlert(AppResources.Alert, AppResources.EmailSent, AppResources.Ok);

                    BackButton.Execute(null);
                }
            }

            Dialog.HideLoading();
        }
Exemplo n.º 17
0
        public async Task <IActionResult> RenderPDF()
        {
            //Create a new PDF document.
            PdfDocument doc = new PdfDocument();
            //Add a page to the document.
            PdfPage page = doc.Pages.Add();
            //Create PDF graphics for the page
            PdfGraphics graphics = page.Graphics;
            //Load the image as stream.
            FileStream imageStream = new FileStream("test.png", FileMode.Open, FileAccess.Read);
            PdfBitmap  image       = new PdfBitmap(imageStream);

            //Draw the image
            graphics.DrawImage(image, 0, 0);
            //Save the PDF document to stream
            MemoryStream stream = new MemoryStream();

            doc.Save(stream);
            //If the position is not set to '0' then the PDF will be empty.
            stream.Position = 0;
            //Close the document.
            doc.Close(true);
            //Defining the ContentType for pdf file.
            string contentType = "application/pdf";
            //Define the file name.
            string fileName = "Output.pdf";

            //Creates a FileContentResult object by using the file contents, content type, and file name.
            return(File(stream, contentType, fileName));
        }
Exemplo n.º 18
0
 public void Dispose()
 {
     if (Bitmap != null)
     {
         Bitmap.Dispose();
     }
     Bitmap = null;
 }
Exemplo n.º 19
0
 public PRItem(ProgressiveRenderingStatuses status, Helpers.Int32Size canvasSize)
 {
     this.status = status;
     if (canvasSize.Width > 0 && canvasSize.Height > 0)
     {
         Bitmap = new PdfBitmap(canvasSize.Width, canvasSize.Height, true);
     }
 }
 protected override void DrawTextHighlight(PdfBitmap bitmap,
                                           List <HighlightInfo> entries,
                                           int pageIndex)
 {
     base.DrawTextHighlight(bitmap,
                            entries,
                            pageIndex);
 }
Exemplo n.º 21
0
 public PRItem(ProgressiveStatus status, Size canvasSize)
 {
     this.status = status;
     if (canvasSize.Width > 0 && canvasSize.Height > 0)
     {
         Bitmap = new PdfBitmap(canvasSize.Width, canvasSize.Height, true);
     }
 }
        private void AddHeader(PdfDocument doc, string title, string description)
        {
            RectangleF rect      = new RectangleF(0, 0, doc.Pages[0].GetClientSize().Width, 50);
            PdfColor   blueColor = new PdfColor(System.Drawing.Color.FromArgb(255, 0, 0, 255));
            PdfColor   GrayColor = new PdfColor(System.Drawing.Color.FromArgb(255, 128, 128, 128));

            //Create page template
            PdfPageTemplateElement header = new PdfPageTemplateElement(rect);
            PdfFont font         = new PdfStandardFont(PdfFontFamily.Helvetica, 24);
            float   doubleHeight = font.Height * 2;

            System.Drawing.Color activeColor = System.Drawing.Color.FromArgb(255, 44, 71, 120);
            SizeF imageSize = new SizeF(110f, 35f);
            //Locating the logo on the right corner of the Drawing Surface
            PointF imageLocation = new PointF(doc.Pages[0].GetClientSize().Width - imageSize.Width - 20, 5);

            Stream   imgStream = typeof(HeadersAndFooters).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.logo.png");
            PdfImage img       = new PdfBitmap(imgStream);

            //Draw the image in the Header.
            header.Graphics.DrawImage(img, imageLocation, imageSize);

            PdfSolidBrush brush = new PdfSolidBrush(activeColor);

            PdfPen pen = new PdfPen(blueColor, 3f);

            font = new PdfStandardFont(PdfFontFamily.Helvetica, 16, PdfFontStyle.Bold);

            //Set formattings for the text
            PdfStringFormat format = new PdfStringFormat();

            format.Alignment     = PdfTextAlignment.Center;
            format.LineAlignment = PdfVerticalAlignment.Middle;

            //Draw title
            header.Graphics.DrawString(title, font, brush, new RectangleF(0, 0, header.Width, header.Height), format);
            brush = new PdfSolidBrush(GrayColor);
            font  = new PdfStandardFont(PdfFontFamily.Helvetica, 6, PdfFontStyle.Bold);

            format               = new PdfStringFormat();
            format.Alignment     = PdfTextAlignment.Left;
            format.LineAlignment = PdfVerticalAlignment.Bottom;

            //Draw description
            header.Graphics.DrawString(description, font, brush, new RectangleF(0, 0, header.Width, header.Height - 8), format);

            //Draw some lines in the header
            pen = new PdfPen(blueColor, 0.7f);
            header.Graphics.DrawLine(pen, 0, 0, header.Width, 0);
            pen = new PdfPen(blueColor, 2f);
            header.Graphics.DrawLine(pen, 0, 03, header.Width + 3, 03);
            pen = new PdfPen(blueColor, 2f);
            header.Graphics.DrawLine(pen, 0, header.Height - 3, header.Width, header.Height - 3);
            header.Graphics.DrawLine(pen, 0, header.Height, header.Width, header.Height);

            //Add header template at the top.
            doc.Template.Top = header;
        }
        private void AddMulticolumnHeader(PdfDocument doc, string title, string description)
        {
            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;

            dataPath = basePath + @"/PDF/";
            RectangleF rect = new RectangleF(0, 0, doc.Pages[0].GetClientSize().Width, 50);

            //Create page template
            PdfPageTemplateElement header = new PdfPageTemplateElement(rect);
            PdfFont font         = new PdfStandardFont(PdfFontFamily.Helvetica, 24);
            float   doubleHeight = font.Height * 2;
            Color   activeColor  = Color.FromArgb(44, 71, 120);
            SizeF   imageSize    = new SizeF(110f, 35f);
            //Locating the logo on the right corner of the Drawing Surface
            PointF     imageLocation = new PointF(doc.Pages[0].GetClientSize().Width - imageSize.Width - 20, 5);
            FileStream pngStream     = new FileStream(dataPath + "logo.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            PdfImage   img           = new PdfBitmap(pngStream);

            //Draw the image in the Header.
            header.Graphics.DrawImage(img, imageLocation, imageSize);

            PdfSolidBrush brush = new PdfSolidBrush(activeColor);

            PdfPen pen = new PdfPen(Color.DarkBlue, 3f);

            font = new PdfStandardFont(PdfFontFamily.Helvetica, 16, PdfFontStyle.Bold);

            //Set formattings for the text
            PdfStringFormat format = new PdfStringFormat();

            format.Alignment     = PdfTextAlignment.Center;
            format.LineAlignment = PdfVerticalAlignment.Middle;

            //Draw title
            header.Graphics.DrawString(title, font, brush, new RectangleF(0, 0, header.Width, header.Height), format);
            brush = new PdfSolidBrush(Color.Gray);
            font  = new PdfStandardFont(PdfFontFamily.Helvetica, 6, PdfFontStyle.Bold);

            format               = new PdfStringFormat();
            format.Alignment     = PdfTextAlignment.Left;
            format.LineAlignment = PdfVerticalAlignment.Bottom;

            //Draw description
            header.Graphics.DrawString(description, font, brush, new RectangleF(0, 0, header.Width, header.Height - 8), format);

            //Draw some lines in the header
            pen = new PdfPen(Color.DarkBlue, 0.7f);
            header.Graphics.DrawLine(pen, 0, 0, header.Width, 0);
            pen = new PdfPen(Color.DarkBlue, 2f);
            header.Graphics.DrawLine(pen, 0, 03, header.Width + 3, 03);
            pen = new PdfPen(Color.DarkBlue, 2f);
            header.Graphics.DrawLine(pen, 0, header.Height - 3, header.Width, header.Height - 3);
            header.Graphics.DrawLine(pen, 0, header.Height, header.Width, header.Height);

            //Add header template at the top.
            doc.Template.Top = header;
        }
        /// <summary>
        /// Create a simple PDF document
        /// </summary>
        /// <returns>Return the created PDF document as stream</returns>
        public MemoryStream DigitalSignaturePDF(string RadioButtonList2, string NewPDF, string Cryptographic, string Digest_Algorithm)
        {
            MemoryStream stream_Empty = new MemoryStream();

            //Read the PFX file
            FileStream pfxFile = new FileStream(ResolveApplicationPath("PDF.pfx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            PdfDocument    doc       = new PdfDocument();
            PdfPage        page      = doc.Pages.Add();
            PdfSolidBrush  brush     = new PdfSolidBrush(Color.Black);
            PdfPen         pen       = new PdfPen(brush, 0.2f);
            PdfFont        font      = new PdfStandardFont(PdfFontFamily.Courier, 12, PdfFontStyle.Regular);
            PdfCertificate pdfCert   = new PdfCertificate(pfxFile, "password123");
            PdfSignature   signature = new PdfSignature(page, pdfCert, "Signature");
            FileStream     jpgFile   = new FileStream(ResolveApplicationPath("logo.png"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            PdfBitmap      bmp       = new PdfBitmap(jpgFile);

            signature.Bounds       = new RectangleF(new PointF(5, 5), page.GetClientSize());
            signature.ContactInfo  = "*****@*****.**";
            signature.LocationInfo = "Honolulu, Hawaii";
            signature.Reason       = "I am author of this document.";
            SetCryptographicStandard(Cryptographic, signature);
            SetDigest_Algorithm(Digest_Algorithm, signature);
            if (RadioButtonList2 == "Standard")
            {
                signature.Certificated = true;
            }
            else
            {
                signature.Certificated = false;
            }
            PdfGraphics graphics = signature.Appearence.Normal.Graphics;

            string validto   = "Valid To: " + signature.Certificate.ValidTo.ToString();
            string validfrom = "Valid From: " + signature.Certificate.ValidFrom.ToString();

            graphics.DrawImage(bmp, 0, 0);

            doc.Pages[0].Graphics.DrawString(validfrom, font, pen, brush, 0, 90);
            doc.Pages[0].Graphics.DrawString(validto, font, pen, brush, 0, 110);

            doc.Pages[0].Graphics.DrawString(" Protected Document. Digitally signed Document.", font, pen, brush, 0, 130);
            doc.Pages[0].Graphics.DrawString("* To validate Signature click on the signature on this page \n * To check Document Status \n click document status icon on the bottom left of the acrobat reader.", font, pen, brush, 0, 150);

            // Save the pdf document to the Stream.
            MemoryStream stream = new MemoryStream();

            doc.Save(stream);

            //Close document
            doc.Close();

            stream.Position = 0;
            return(stream);

            return(stream_Empty);
        }
        private void AddHeader(PdfDocument doc, string title, string description)
        {
            RectangleF rect = new RectangleF(0, 0, doc.Pages[0].GetClientSize().Width, 50);

            //Create page template
            PdfPageTemplateElement header = new PdfPageTemplateElement(rect);
            PdfFont font         = new PdfStandardFont(PdfFontFamily.Helvetica, 24);
            float   doubleHeight = font.Height * 2;
            Color   activeColor  = Color.FromArgb(44, 71, 120);
            SizeF   imageSize    = new SizeF(110f, 35f);
            //Locating the logo on the right corner of the Drawing Surface
            PointF imageLocation = new PointF(doc.Pages[0].GetClientSize().Width - imageSize.Width - 20, 5);

#if NETCORE
            PdfImage img = new PdfBitmap(@"..\..\..\..\..\..\..\Common\Images\PDF\logo.png");
#else
            PdfImage img = new PdfBitmap(@"..\..\..\..\..\..\Common\Images\PDF\logo.png");
#endif

            //Draw the image in the Header.
            header.Graphics.DrawImage(img, imageLocation, imageSize);

            PdfSolidBrush brush = new PdfSolidBrush(activeColor);

            PdfPen pen = new PdfPen(Color.DarkBlue, 3f);
            font = new PdfStandardFont(PdfFontFamily.Helvetica, 16, PdfFontStyle.Bold);

            //Set formattings for the text
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment     = PdfTextAlignment.Center;
            format.LineAlignment = PdfVerticalAlignment.Middle;

            //Draw title
            header.Graphics.DrawString(title, font, brush, new RectangleF(0, 0, header.Width, header.Height), format);
            brush = new PdfSolidBrush(Color.Gray);
            font  = new PdfStandardFont(PdfFontFamily.Helvetica, 6, PdfFontStyle.Bold);

            format               = new PdfStringFormat();
            format.Alignment     = PdfTextAlignment.Left;
            format.LineAlignment = PdfVerticalAlignment.Bottom;

            //Draw description
            header.Graphics.DrawString(description, font, brush, new RectangleF(0, 0, header.Width, header.Height - 8), format);

            //Draw some lines in the header
            pen = new PdfPen(Color.DarkBlue, 0.7f);
            header.Graphics.DrawLine(pen, 0, 0, header.Width, 0);
            pen = new PdfPen(Color.DarkBlue, 2f);
            header.Graphics.DrawLine(pen, 0, 03, header.Width + 3, 03);
            pen = new PdfPen(Color.DarkBlue, 2f);
            header.Graphics.DrawLine(pen, 0, header.Height - 3, header.Width, header.Height - 3);
            header.Graphics.DrawLine(pen, 0, header.Height, header.Width, header.Height);

            //Add header template at the top.
            doc.Template.Top = header;
        }
Exemplo n.º 26
0
        //Transfer image
        async void OnTransferImageClicked(object sender, EventArgs e)
        {
            //scroll to the top of the page
            await ChildScrollView.ScrollToAsync(0, 0, false).ConfigureAwait(false);

            child = (Child)BindingContext;
            //Create a new PDF document
            PdfDocument document = new PdfDocument();
            //Add page to the PDF document
            PdfPage page = document.Pages.Add();
            //Create graphics instance
            PdfGraphics graphics    = page.Graphics;
            Stream      imageStream = null;

            //Captures the XAML page as image and returns the image in memory stream
            imageStream = new MemoryStream(DependencyService.Get <IScreenshotService>().Capture());

            //Load the image in PdfBitmap
            PdfBitmap image = new PdfBitmap(imageStream);


            //scroll to the second page
            await ChildScrollView.ScrollToAsync(0, 940, false).ConfigureAwait(true);


            //Add page to the PDF document
            PdfPage page2 = document.Pages.Add();
            //Create graphics instance
            PdfGraphics graphics2 = page2.Graphics;

            imageStream = new MemoryStream(DependencyService.Get <IScreenshotService>().Capture());
            PdfBitmap image2 = new PdfBitmap(imageStream);


            //Set layout property to make the element break across the pages

            PdfLayoutFormat format = new PdfLayoutFormat();

            format.Break = PdfLayoutBreakType.FitPage;

            format.Layout = PdfLayoutType.Paginate;

            //Draw the image to the page
            graphics.DrawImage(image, 0, 0, page.GetClientSize().Width, page.GetClientSize().Height);
            graphics2.DrawImage(image2, 0, 0, page.GetClientSize().Width, page.GetClientSize().Height);


            //Save the document into memory stream
            MemoryStream stream = new MemoryStream();

            document.Save(stream);

            stream.Position = 0;
            //Save the stream as a file in the device and invoke it for viewing
            DependencyService.Get <ISave>().Save("TuitionFees.pdf", "application/pdf", stream);
        }
        private static async Task <PdfBitmap> GetPdfBitmap(string filename)
        {
            var storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///images/watch.jpg"));

            var imageStream = await storageFile.OpenAsync(FileAccessMode.Read);

            PdfBitmap image = new PdfBitmap(imageStream.AsStream());

            return(image);
        }
Exemplo n.º 28
0
        public static void AssinarDocumento()
        {
            var    arquivoEnt = $"d:\\temp\\modelo.pdf";
            var    pdf        = DSHelper.ReadContent(arquivoEnt);
            var    arquivo    = $"d:\\temp\\modeloOut.pdf";
            float  x;
            float  y;
            Stream pfxStream = File.OpenRead("MRV ENGENHARIA E PARTICIPAÇÕES S.A..pfx");
            //Creates a certificate instance from PFX file with private key.
            PdfCertificate pdfCert = new PdfCertificate(pfxStream, "zzzzz");

            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(pdf);

            var lista = new Dictionary <int, List <Syncfusion.Drawing.RectangleF> >();

            loadedDocument.FindText("Assinado:", out lista);

            foreach (var item in lista)
            {
                x = item.Value[0].X + 100;
                y = item.Value[0].Y;
                var page = loadedDocument.Pages[item.Key] as PdfLoadedPage;

                //aplica logo da assinatura em todas as paginas
                if (page != null)
                {
                    Stream      seloStream     = File.OpenRead("SeloMrv.jpg");
                    PdfBitmap   signatureImage = new PdfBitmap(seloStream);
                    PdfGraphics gfx            = page.Graphics;
                    gfx.DrawImage(signatureImage, x, y, 90, 80);
                }

                //Applica o certificado somente na ultima pagina
                if (item.Value == lista[lista.Keys.Count - 1])
                {
                    //Creates a signature field.
                    PdfSignatureField signatureField = new PdfSignatureField(page, "AssinaturaMRV");
                    signatureField.Bounds    = new Syncfusion.Drawing.RectangleF(x, item.Value[0].Y, 50, 50);
                    signatureField.Signature = new PdfSignature(page, "MRV Engenharia");
                    //Adds certificate to the signature field.
                    signatureField.Signature.Certificate = pdfCert;
                    signatureField.Signature.Reason      = "Assinado pela MRV Engenharia";

                    //Adds the field.
                    loadedDocument.Form.Fields.Add(signatureField);
                }
            }
            //Saves the certified PDF document.
            using (FileStream fileOut = new FileStream(arquivo, FileMode.Create))
            {
                loadedDocument.Save(fileOut);
                loadedDocument.Close(true);
            }
            //return arquivo;
        }
Exemplo n.º 29
0
        private void btnImport_Click(object sender, System.EventArgs e)
        {
            PdfLoadedDocument lDoc = new PdfLoadedDocument(txtUrl.Tag.ToString());
            PdfFont           font = new PdfStandardFont(PdfFontFamily.Helvetica, 36f);

            foreach (PdfPageBase lPage in lDoc.Pages)
            {
                PdfGraphics      g     = lPage.Graphics;
                PdfGraphicsState state = g.Save();
                g.SetTransparency(0.25f);
                g.RotateTransform(-40);
                g.DrawString(txtStamp.Text, font, PdfPens.Red, PdfBrushes.Red, new PointF(-150, 450));
                g.Restore(state);

                if (chbWatermark.Checked)
                {
                    g.Save();
#if NETCORE
                    PdfImage image = new PdfBitmap(@"..\..\..\..\..\..\..\..\Common\Images\PDF\Ani.gif");
#else
                    PdfImage image = new PdfBitmap(@"..\..\..\..\..\..\..\Common\Images\PDF\Ani.gif");
#endif
                    g.SetTransparency(0.25f);
                    g.DrawImage(image, 0, 0, lPage.Graphics.ClientSize.Width, lPage.Graphics.ClientSize.Height);
                    g.Restore();
                }
            }


            lDoc.Save("Sample.pdf");

            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.pdf")
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                System.Diagnostics.Process.Start("Sample.pdf");
#endif
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
        }
Exemplo n.º 30
0
        public IActionResult generatePDF()
        {
            PdfDocument doc = new PdfDocument();
            //Add a page.
            PdfPage page = doc.Pages.Add();
            //Create a PdfGrid.
            PdfGrid     pdfGrid  = new PdfGrid();
            PdfGraphics graphics = page.Graphics;
            //Load the image as stream.
            FileStream imageStream = new FileStream("wwwroot/images/logo2.png", FileMode.Open, FileAccess.Read);
            PdfBitmap  image       = new PdfBitmap(imageStream);

            graphics.DrawImage(image, 0, 0);
            PdfGridCellStyle headerStyle = new PdfGridCellStyle();

            headerStyle.Borders.All     = new PdfPen(new PdfColor(126, 151, 173));
            headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173));
            headerStyle.TextBrush       = PdfBrushes.White;
            headerStyle.Font            = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Regular);
            //Add values to list
            //List<object> data = new List<object>();
            var list_all = _context.Shop_items.ToList();
            //Object row1 = new { ID = "E01", Name = "Clay" };
            //Object row2 = new { ID = "E02", Name = "Thomas" };
            //Object row3 = new { ID = "E03", Name = "Andrew" };
            //Object row4 = new { ID = "E04", Name = "Paul" };
            //Object row5 = new { ID = "E05", Name = "Gray" };
            //data.Add(row1);
            //data.Add(row2);
            //data.Add(row3);
            //data.Add(row4);
            //data.Add(row5);
            //Add list to IEnumerable
            IEnumerable <object> dataTable = list_all;

            //Assign data source.
            pdfGrid.DataSource = dataTable;
            //Draw grid to the page of PDF document.
            pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(10, 10));
            //Save the PDF document to stream
            MemoryStream stream = new MemoryStream();

            doc.Save(stream);
            //If the position is not set to '0' then the PDF will be empty.
            stream.Position = 0;
            //Close the document.
            doc.Close(true);
            //Defining the ContentType for pdf file.
            string contentType = "application/pdf";
            //Define the file name.
            string fileName = "Output.pdf";

            //Creates a FileContentResult object by using the file contents, content type, and file name.
            return(File(stream, contentType, fileName));
        }
Exemplo n.º 31
0
        protected bool GenerateTransferPDF(BankTransfer transfer)
        {
            lock (this)
            {
                PdfDocument transferDetails = new PdfDocument();
                //transferDetails.
                Font pdfFont = new Font("Arial", 18f);
                PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(pdfFont, true);

                PdfPageBase TransferPage = transferDetails.Pages.Add();
                PdfBitmap logo = new PdfBitmap(SieradzBankFilesPathHolder.TransferFilesPath + @"..\mBank\logo.jpg");
                TransferPage.Canvas.DrawImage(logo, new RectangleF(new PointF(25.0f, 25.0f), new SizeF(140f, 85f)));
                TransferPage.Canvas.DrawString("\tPotwierdzenie przelewu:", new PdfFont(PdfFontFamily.Helvetica, 20f), new PdfSolidBrush(new PdfRGBColor(0, 0, 0)), 10, 150f);
                TransferPage.Canvas.DrawString(TransferDetailsString(transfer), trueTypeFont, new PdfSolidBrush(new PdfRGBColor(0, 0, 0)), 50, 180f);
                SavePDF(transferDetails);
            }

            return true;
        }
Exemplo n.º 32
0
		/// <summary>
		/// Draw fill forms
		/// </summary>
		/// <param name="bmp"><see cref="PdfBitmap"/> object</param>
		/// <param name="page">Page to be drawn</param>
		/// <param name="actualRect">Page bounds in control coordinates</param>
		/// <remarks>
		/// Full page rendering is performed in the following order:
		/// <list type="bullet">
		/// <item><see cref="DrawPageBackColor"/></item>
		/// <item><see cref="DrawPage"/> / <see cref="DrawLoadingIcon"/></item>
		/// <item><see cref="DrawFillForms"/></item>
		/// <item><see cref="DrawPageBorder"/></item>
		/// <item><see cref="DrawFillFormsSelection"/></item>
		/// <item><see cref="DrawTextHighlight"/></item>
		/// <item><see cref="DrawTextSelection"/></item>
		/// <item><see cref="DrawCurrentPageHighlight"/></item>
		/// <item><see cref="DrawPageSeparators"/></item>
		/// </list>
		/// </remarks>
		protected virtual void DrawFillForms(PdfBitmap bmp, PdfPage page, Rect actualRect)
		{
			int x = Helpers.PointsToPixels(actualRect.X);
			int y = Helpers.PointsToPixels(actualRect.Y);
			int width = Helpers.PointsToPixels(actualRect.Width);
			int height = Helpers.PointsToPixels(actualRect.Height);

			//Draw fillforms to bitmap
			page.RenderForms(bmp, x, y, width, height, PageRotation(page), RenderFlags);
		}
Exemplo n.º 33
0
		private BitmapSource CreateImageSource(PdfBitmap bmp)
		{
			_mem = new MemoryStream();
			bmp.Image.Save(_mem, System.Drawing.Imaging.ImageFormat.Png);

			BitmapImage bi = new BitmapImage();
			bi.BeginInit();
			bi.CacheOption = BitmapCacheOption.None;
			bi.StreamSource = _mem;
			bi.EndInit();
			bi.Freeze();
			//BitmapSource prgbaSource = new FormatConvertedBitmap(bi, PixelFormats.Pbgra32, null, 0);
			//WriteableBitmap bmp = new WriteableBitmap(prgbaSource);
			//int w = bmp.PixelWidth;
			//int h = bmp.PixelHeight;
			//int[] pixelData = new int[w * h];
			////int widthInBytes = 4 * w;
			//int widthInBytes = bmp.PixelWidth * (bmp.Format.BitsPerPixel / 8); //equals 4*w
			//bmp.CopyPixels(pixelData, widthInBytes, 0);
			//bmp.WritePixels(new Int32Rect(0, 0, w, h), pixelData, widthInBytes, 0);
			//bi = null;
			return bi;
		}
Exemplo n.º 34
0
		private void RenderPage(int pageNumber, DrawingVisual visual)
		{
			int dpiX = PrinterTicket.PageResolution.X ?? 96;
			int dpiY = PrinterTicket.PageResolution.Y ?? 96;

			//Calculate the size of the printable area in inches
			//The printable area represents a DIPs (Device independed points) (DIPs = pixels/(DPI/96) )
			var fitSize = new Size()
			{
				Width = PageSize.Width / 96.0,
				Height = PageSize.Height / 96.0
			};

			//Get page's size in inches
			//The page size represents a points (1pt = 1/72 inch)
			var pdfSize = new Size()
			{
				Width = _doc.Pages[pageNumber].Width / 72.0f,
				Height = _doc.Pages[pageNumber].Height / 72.0f
			};

			//If page was rotated in original file, then we need to "rotate the paper in printer". 
			//For that just swap the width and height of the paper.
			if (_doc.Pages[pageNumber].OriginalRotation == PageRotate.Rotate270
				|| _doc.Pages[pageNumber].OriginalRotation == PageRotate.Rotate90)
				fitSize = new Size(fitSize.Height, fitSize.Width);

			//Calculate the render size (in inches) fitted to the paper's size. 
			var rSize = GetRenderSize(pdfSize, fitSize);

			int pixelWidth = (int)(rSize.Width * dpiX);
			int pixelHeight =(int)(rSize.Height * dpiY);

			using (PdfBitmap bmp = new PdfBitmap(pixelWidth, pixelHeight, true))
			{
				//Render to PdfBitmap using page's Render method with FPDF_PRINTING flag.
				_doc.Pages[pageNumber].RenderEx(
					bmp,
					0,
					0,
					pixelWidth,
					pixelHeight,
					PageRotate.Normal,
					RenderFlags.FPDF_PRINTING | RenderFlags.FPDF_ANNOT);


				//Rotates the PdfBitmap image depending on the orientation of the page
				PdfBitmap b2 = null;
				if (PageRotation(_doc.Pages[pageNumber]) == PageRotate.Rotate270)
					b2 = bmp.SwapXY(false, true);
				else if (PageRotation(_doc.Pages[pageNumber]) == PageRotate.Rotate180)
					b2 = bmp.FlipXY(true, true);
				else if (PageRotation(_doc.Pages[pageNumber]) == PageRotate.Rotate90)
					b2 = bmp.SwapXY(true, false);

				int stride = b2 == null ? bmp.Stride : b2.Stride;
				int width = b2 == null ? bmp.Width : b2.Width;
				int height = b2 == null ? bmp.Height : b2.Height;
				IntPtr buffer = b2 == null ? bmp.Buffer : b2.Buffer;
				var imgsrc = CreateImageSource(b2 ?? bmp);
				if (b2 != null)
					b2.Dispose();

				var dc = visual.RenderOpen();
				dc.DrawImage(imgsrc, new Rect(0, 0, imgsrc.PixelWidth / (dpiX / 96.0), imgsrc.Height / (dpiY / 90.0)));
				dc.Close();
				imgsrc = null;
			}
		}