Create PDF File From WPF Window using iTextsharp

 

We can create PDF files easily by using iTextsharp third-party controls in C#. iTextsharp controls are free to use, so you can use these controls if you want to work with PDF files. Today We are going to discuss how to create PDF file from the WPF window. Whenever you want to create PDF file for the WPF window this example helps you. In this example we are going to use iTextsharp controls to create PDF.

 

Open Visual Studio => Create New Project => Select WPF Application and name it as CreatePDFWPFControl. In this example we are going to render WPF content to image and by using iTextsharp control we are going to render image as PDF file.

 

First create the method to generate image from any WPF control as shown below.

 

public static RenderTargetBitmap GetImage(UIElement view)

{

            Size size = new Size(view.RenderSize.Width, view.RenderSize.Height);

            if (size.IsEmpty)

                return null;

 

            RenderTargetBitmap result = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);

 

            DrawingVisual drawingvisual = new DrawingVisual();

            using (DrawingContext context = drawingvisual.RenderOpen())

            {

                context.DrawRectangle(new VisualBrush(view), null, new Rect(0, 0, (int)size.Width, (int)size.Height));

                context.Close();

            }

 

            result.Render(drawingvisual);

            return result;

}

 

Here GetImage() method will take any WPF control and it produces the image with all content within it.

 

Now we will write the method to generate the PDF file from the image as shown below.

 

public static void createPdfFromImage(string imageFile, string pdfFile)

{

            using (var ms = new MemoryStream())

            {

                var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER.Rotate(), 0, 0, 0, 0);

                PdfWriter.GetInstance(document, new FileStream(pdfFile, FileMode.Create));

                iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();

                document.Open();

               

                FileStream fs = new FileStream(imageFile, FileMode.Open);

                var image = iTextSharp.text.Image.GetInstance(fs);

                image.ScaleToFit(document.PageSize.Width, document.PageSize.Height);

                document.Add(image);

                document.Close();

 

                //open pdf file

                Process.Start("explorer.exe",pdfFile);

            }

}

 

The createPdfFromImage() method will create the PDF file from the given image. Here we are using Process class to open the PDF file. The total to create the PDF file from the WPF control is shown below.

 

using System.IO;

using System.Windows;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using iTextSharp.text.pdf;

using System.Diagnostics;

 

namespace CreatePDFWPFControl

{

    ///<summary>

    /// Interaction logic for MainWindow.xaml

    ///</summary>

    public partial class MainWindow : Window

    {

       

        public MainWindow()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            string sPDFFileName = System.IO.Path.GetTempPath() + "PDFFile.pdf";

            string sImagePath = System.IO.Path.GetTempPath() + "window.png";

 

            SaveAsPng(GetImage(GridForm), sImagePath);

            createPdfFromImage(sImagePath, sPDFFileName);

        }

 

        public static RenderTargetBitmap GetImage(UIElement view)

        {

            Size size = new Size(view.RenderSize.Width, view.RenderSize.Height);

            if (size.IsEmpty)

                return null;

 

            RenderTargetBitmap result = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);

 

            DrawingVisual drawingvisual = new DrawingVisual();

            using (DrawingContext context = drawingvisual.RenderOpen())

            {

                context.DrawRectangle(new VisualBrush(view), null, new Rect(0, 0, (int)size.Width, (int)size.Height));

                context.Close();

            }

 

            result.Render(drawingvisual);

            return result;

        }

 

        public static void SaveAsPng(RenderTargetBitmap src, string targetFile)

        {

            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(src));

 

            using (var stm = System.IO.File.Create(targetFile))

            {

                encoder.Save(stm);

            }

        }

 

        public static void createPdfFromImage(string imageFile, string pdfFile)

        {

            using (var ms = new MemoryStream())

            {

                var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER.Rotate(), 0, 0, 0, 0);

                PdfWriter.GetInstance(document, new FileStream(pdfFile, FileMode.Create));

                iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();

                document.Open();

               

                FileStream fs = new FileStream(imageFile, FileMode.Open);

                var image = iTextSharp.text.Image.GetInstance(fs);

                image.ScaleToFit(document.PageSize.Width, document.PageSize.Height);

                document.Add(image);

                document.Close();

 

                //open pdf file

                Process.Start("explorer.exe",pdfFile);

            }

        }

    }

}

 

Execute the application, the output is as shown below.

 

                        

 

Click on "Create PDF", it opens PDF file as shown below.

 

                    

 

                                                                                                                  CreatePDFWPFControl.zip (1.89 mb)