Search code examples
c#pdfitextwindows-forms-designer

Convert a Panel to a PDF Document in C# Windows


I want to print out a panel in my form to a pdf file.

I've tried using iText7 library as show in the code below.

using System;
using System.Data;
using System.Windows.Forms;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.IO.Image;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace PDFGeneratorApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        private void buttonPrintPDF_Click(object sender, EventArgs e)
        {
            Panel myPanel = panel1;
            string filePath = "file.pdf";
            ExportPanelToPdf(panel1, filePath);
        }

        public static void ExportPanelToPdf(Panel panel, string filePath)
        {
            // First, capture the panel to a bitmap
            Bitmap bitmap = new Bitmap(panel.Width, panel.Height);
            panel.DrawToBitmap(bitmap, new Rectangle(0, 0, panel.Width, panel.Height));

            // Save the image to a stream
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Png);
                byte[] imageBytes = stream.ToArray();

                // Create a new PDF document
                PdfWriter writer = new PdfWriter(filePath);
                PdfDocument pdf = new PdfDocument(writer);
                Document document = new Document(pdf);

                // Add the image to the PDF document
                ImageData imageData = ImageDataFactory.Create(imageBytes);
                iText.Layout.Element.Image image = new iText.Layout.Element.Image(imageData);

                document.Add(image);

                // Close the document
                document.Close();
            }
        }
    }
}

This brings up the following exception:

iText.Kernel.Exceptions.PdfException HResult=0x80131500 Message=Unknown PdfException. Source=itext.kernel StackTrace: at iText.Kernel.Pdf.SmartModePdfObjectsSerializer..ctor() at iText.Kernel.Pdf.PdfWriter..ctor(Stream os, WriterProperties properties) at iText.Kernel.Pdf.PdfWriter..ctor(String filename) at PDFGeneratorApp.Form1.ExportPanelToPdf(Panel panel, String filePath) in C:\Users\CONSULTANT 2\source\repos\PDFGeneratorApp\Form1.cs:line 62 at PDFGeneratorApp.Form1.buttonPrintPDF_Click(Object sender, EventArgs e) in C:\Users\CONSULTANT 2\source\repos\PDFGeneratorApp\Form1.cs:line 46 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at PDFGeneratorApp.Program.Main() in C:\Users\CONSULTANT 2\source\repos\PDFGeneratorApp\Program.cs:line 19

This exception was originally thrown at this call stack: iText.Bouncycastleconnector.BouncyCastleDefaultFactory.CreateIDigest(string) iText.Kernel.Pdf.SmartModePdfObjectsSerializer.SmartModePdfObjectsSerializer()

Inner Exception 1:

NotSupportedException: Either com.itextpdf:bouncy-castle-adapter or com.itextpdf:bouncy-castle-fips-adapter dependency must be added in order to use BouncyCastleFactoryCreator

I've tried installing com.itextpdf but it fails installation with hundreds of errors. It seems as if installing iText isn't enough and one needs to install other dependencies seperately.

Are there alternatives for accomplishing this - printing a panel to a pdf?


Solution

  • You need to install iText7 supporting package bouncy castle separately via Nuget package manager. iText7 made several major breaking changes in the way they handle bouncy-castle dependencies. Install itext7.bouncy-castle-adapter via below Nuget Command below.

    Install-Package itext7.bouncy-castle-adapter -Version 8.0.2
    

    Link - https://www.nuget.org/packages/itext7.bouncy-castle-adapter