来自资源文件的iTextSharp pdf图像

时间:2017-06-24 07:30:57

标签: c# pdf itext

我在带有c#的windows窗体中使用iTextSharp创建一个pdf文件,我想从Resource文件夹(图像名称:LOGO.png)向该文件添加一个图像。我有一个类ExportToPdf.cs,这个类在App_Class文件夹中。我正在使用下面的代码。请任何人帮忙。

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");
    }
}

1 个答案:

答案 0 :(得分:5)

Visual Studio使得IMHO成为一个值得怀疑的决定,将图像文件存储为System.Drawing.Bitmap,(在上面的代码Resources.LOGO中),而不是byte[],就像它与其他二进制文件一样。因此,您需要使用其中一个重载的Image.GetInstance()方法。这是一个简单的例子:

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