Export the entire interface to PDF

Viewed 607

I created a simple program that contains Labels and TextBoxes. I added a Button to export the entire interface with Labels and Textboxes to PDF but I get this error message:

Unable to cast object of type 'System.Windows.Forms.Panel' to type 'iTextSharp.text.IElement'.,

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim pdfDoc As New Document()
    Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("C:\Users\Win 10\Desktop\simple.pdf", FileMode.Create))

    pdfDoc.open()
    pdfDoc.Add(Panel1)
    pdfDoc.Add(Panel2)
    pdfDoc.Add(TextBox1)
    pdfDoc.Add(TextBox2)
    pdfDoc.Close()
End Sub
1 Answers

You will need to convert the controls to Bitmap images, then drop them into the PDF.

I wrote this function that will take WinForms controls, convert them to Bitmap and then into iTextSharp.text.Image formats that can then be placed inside of a PDF.

Function ControlToPDFImage(ControlToConvert As Windows.Forms.Control)

    Dim Bmp As Bitmap = New Bitmap(ControlToConvert.Width, ControlToConvert.Height)
    ControlToConvert.DrawToBitmap(Bmp, New Drawing.Rectangle(0, 0, Panel1.Width, Panel1.Height))
    Dim PDFImg As Image = iTextSharp.text.Image.GetInstance(Bmp, System.Drawing.Imaging.ImageFormat.Png)

    Return PDFImg

End Function

So if you change your code to this, it should work:

pdfDoc.Add(ControlToPDFImage(Panel1))
pdfDoc.Add(ControlToPDFImage(Panel2))
pdfDoc.Add(ControlToPDFImage(TextBox1))
pdfDoc.Add(ControlToPDFImage(TextBox2))
Related