ITextSharp pdf image from resource file

I am creating a pdf file using iTextSharp in Windows Forms using C #, I want to add an image to the file from the Resource folder (image name: LOGO.png). I have an ExportToPdf.cs class and this class is located in the App_Class folder. I am using the code below. Can anyone 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");
    }
}

      

+3


source to share


1 answer


Visual Studio makes IMHO the dubious decision to store image files as System.Drawing.Bitmap

, (in your code above Resources.LOGO

) instead of byte[]

as it does with other binaries. Therefore, you need to use one of the overloaded methods Image.GetInstance()

. 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());
}

      

+3


source







All Articles