To add an image from a Bitmap stored in your application's resources using iTextSharp in a .NET Framework 4.8 project, follow these steps:
✅ Prerequisites
-
Install iTextSharp:
Use NuGet to install the iTextSharp library.
Run the following command in the Package Manager Console:
Install-Package itextsharp -Version 5.5.13.3
-
Add the Bitmap to Resources:
- Right-click your project >
Properties > Resources.
- Add your image (e.g.,
MyImage.png) to the resources. Ensure the Build Action is set to Embedded Resource.
🧠 Key Concepts
System.Drawing.Bitmap: Represents the image from your resources.
iTextSharp.text.Image: Used to create a PDF-compatible image.
- MemoryStream: Converts the
Bitmap to a byte array or stream for use in iText.
📝 Code Example
using System;
using System.Drawing;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
class Program
{
static void Main()
{
try
{
// Step 1: Load the Bitmap from Resources
Bitmap bitmap = Properties.Resources.MyImage;
if (bitmap == null)
{
Console.WriteLine("Error: The image resource 'MyImage' was not found.");
return;
}
// Step 2: Convert Bitmap to a byte array
using (var ms = new MemoryStream())
{
// Save the Bitmap to the stream in PNG format
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] imageBytes = ms.ToArray();
// Step 3: Create an iText Image from the byte array
Image image = Image.GetInstance(imageBytes);
// Step 4: Create a PDF document and add the image
Document document = new Document();
using (var fs = new FileStream("output.pdf", FileMode.Create, FileAccess.Write))
{
PdfWriter.GetInstance(document, fs);
document.Open();
document.Add(image);
document.Close();
}
Console.WriteLine("PDF created successfully with the embedded image.");
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
📌 Notes
- Resource Name: Replace
MyImage with the actual name of your image resource.
- Image Format: Using
ImageFormat.Png ensures transparency is preserved. Use ImageFormat.Jpeg if you need a smaller file size and don't require transparency.
- Memory Management: The
using statement ensures that streams and other disposable resources are properly released.
- iTextSharp Compatibility: This approach works with iTextSharp 5.x, which is compatible with .NET Framework 4.8.
🧪 Testing Tips
- Ensure the image is added to the Resources correctly.
- Check that the file
output.pdf is created in your project directory.
- If the image is not displayed, verify that the
Bitmap is not null and that the Save operation is successful.
This approach provides a clean, robust way to embed a Bitmap from your project's resources into a PDF using iTextSharp in a .NET Framework 4.8 environment.