Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp pdf image from Resource file

Tags:

c#

pdf

itext

I create a pdf file using iTextSharp in a windows forms with c#, I want to add an image to the file from the Resource folder(image name: LOGO.png). I have a class ExportToPdf.cs and this class is in the App_Class folder. I am using the code below. Can any one please help.

internal static void exportEchoReport(Patient p)
{
    using (var ms = new MemoryStream())
    {
        using (var doc1 = new iTextSharp.text.Document(PageSize.A4, 50, 50, 15, 15))
        {
            try
            {
                PdfWriter writer = PdfWriter.GetInstance(doc1, new FileStream("echo.pdf", FileMode.Create));
                doc1.Open();

                string imagePath = // I want to use this image LOGO.png (Resources.LOGO)
                iTextSharp.text.Image logoImg = iTextSharp.text.Image.GetInstance(imagePath);

                PdfPTable headerTable = createTable(logoImg, p);
                doc1.Add(headerTable);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                doc1.Close();
            }
        }
        System.Diagnostics.Process.Start("echo.pdf");
    }
}
like image 783
Kamiran Avatar asked Jun 24 '17 07:06

Kamiran


1 Answers

Visual Studio makes IMHO the questionable decision to store image files as System.Drawing.Bitmap, (in your code above Resources.LOGO) instead of byte[] like it does with other binary files. So you need to use one of the overloaded Image.GetInstance() methods. Here's a simple example:

using (var stream = new MemoryStream())
{
    using (var document = new Document())
    {
        PdfWriter.GetInstance(document, stream);
        document.Open();
        var image = Image.GetInstance(
            Resources.LOGO, System.Drawing.Imaging.ImageFormat.Png
        );
        document.Add(image);
    }
    File.WriteAllBytes(OUTPUT_FILE, stream.ToArray());
}
like image 153
kuujinbo Avatar answered Nov 19 '22 09:11

kuujinbo