我使用c#在Windows窗体中使用iTextSharp创建pdf文件,我想从Resource文件夹(图像名称:LOGO.png)向该文件添加图像。我有一个ExportExPdf.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");
}
}
Run Code Online (Sandbox Code Playgroud)
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());
}
Run Code Online (Sandbox Code Playgroud)