푸터 콘텐츠로 바로가기
제품 비교

iTextSharp: Add Image to PDF

IronPDF offers simpler image addition with fewer lines of code and a perpetual license, while iTextSharp provides more granular control but requires more code and has complex licensing under AGPL for commercial use.

When working with PDF files in a .NET environment, adding images to documents is a common requirement for many applications. Whether you're generating invoices with company logos, creating reports with embedded charts, or producing custom documents with watermarks, the ability to embed images into PDFs is essential. Two popular PDF libraries in C# are IronPDF and iTextSharp. This article compares both libraries on their ability to add images to PDFs, considering ease of use, performance, licensing models, and advanced features like image compression and format support.

What Are the Key Differences Between IronPDF and iTextSharp?

What Image Features Does Each Library Offer?

  • IronPDF: IronPDF simplifies adding images to PDFs with built-in support for both local and remote images from URLs. Its API provides control over position, width, and scaling. The library supports JPEG, PNG, GIF, SVG, and WebGL content. The stamping functionality provides methods for watermarking, letterheads, and overlaying images. The Chrome rendering engine ensures accurate rendering of complex graphics and responsive images.

    iTextSharp: iTextSharp offers image embedding through its lower-level API. It provides a flexible interface handling JPG and PNG formats. However, you need more code for customization, especially when positioning images precisely or implementing transparency and rotation. The library requires manual handling of coordinate systems and scaling calculations. You often need to implement your own viewport controls for responsive sizing.

How Do They Handle Large Files and Complex Operations?

What Are the Cost Implications for Commercial Use?

How Do I Add Images to PDFs Using IronPDF?

How Do I Install and Configure IronPDF?

Install IronPDF in your C# or Visual Basic project via NuGet. The library supports multiple installation methods including Windows Installer and Docker deployment:

Install-Package IronPdf

Once installed, you can start adding images using IronPDF's API reference. The library works seamlessly across Windows, Linux, and macOS platforms.

What Does Basic Image Addition Look Like in IronPDF?

Quickstart: Add Image to PDF with IronPDF

Adding images to PDFs with IronPDF requires minimal code using the stamping API.

Nuget Icon지금 바로 NuGet을 사용하여 PDF 만들기를 시작하세요.

  1. NuGet 패키지 관리자를 사용하여 IronPDF를 설치하세요.

    PM > Install-Package IronPdf

  2. 다음 코드 조각을 복사하여 실행하세요.

    using IronPdf;
    using IronPdf.Editing;
    
    class Program
    {
        public static void Main(string[] args)
        {
            // Create a renderer to convert HTML to PDF
            ChromePdfRenderer renderer = new ChromePdfRenderer();
    
            // Render a basic PDF with some HTML content
            PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
    
            // Create an ImageStamper with the image URL
            ImageStamper stamper = new ImageStamper(new Uri("___PROTECTED_URL_61___"));
    
            // Configure image position and size
            stamper.HorizontalAlignment = HorizontalAlignment.Center;
            stamper.VerticalAlignment = VerticalAlignment.Middle;
            stamper.Width = 200;  // Width in pixels
            stamper.Height = 100; // Height in pixels
    
            // Apply the stamp (image) to the PDF document
            pdf.ApplyStamp(stamper);
    
            // Save the modified PDF to a file
            pdf.SaveAs("output.pdf");
        }
    }
  3. 실제 운영 환경에서 테스트할 수 있도록 배포하세요.

    지금 바로 무료 체험판을 통해 프로젝트에서 IronPDF를 사용해 보세요.
    arrow pointer

How Can I Add Watermarks and Background Images?

IronPDF excels at adding watermarks and background images to existing PDFs. The library supports multiple stamping operations and custom positioning:

using IronPdf;
using IronPdf.Editing;

// Load an existing PDF
PdfDocument pdf = PdfDocument.FromFile("invoice.pdf");

// Create a watermark with transparency
ImageStamper watermark = new ImageStamper("watermark.png")
{
    Opacity = 30,  // 30% opacity for subtle watermarking
    Rotation = -45, // Diagonal watermark
    HorizontalAlignment = HorizontalAlignment.Center,
    VerticalAlignment = VerticalAlignment.Middle
};

// Apply watermark to all pages
pdf.ApplyStamp(watermark);

// Add a header logo
ImageStamper logo = new ImageStamper("company-logo.png")
{
    HorizontalOffset = Length.Millimeters(10),
    VerticalOffset = Length.Millimeters(10),
    Width = 150,
    Height = 50
};

pdf.ApplyStamp(logo, PageSelection.FirstPage);
pdf.SaveAs("watermarked-invoice.pdf");
using IronPdf;
using IronPdf.Editing;

// Load an existing PDF
PdfDocument pdf = PdfDocument.FromFile("invoice.pdf");

// Create a watermark with transparency
ImageStamper watermark = new ImageStamper("watermark.png")
{
    Opacity = 30,  // 30% opacity for subtle watermarking
    Rotation = -45, // Diagonal watermark
    HorizontalAlignment = HorizontalAlignment.Center,
    VerticalAlignment = VerticalAlignment.Middle
};

// Apply watermark to all pages
pdf.ApplyStamp(watermark);

// Add a header logo
ImageStamper logo = new ImageStamper("company-logo.png")
{
    HorizontalOffset = Length.Millimeters(10),
    VerticalOffset = Length.Millimeters(10),
    Width = 150,
    Height = 50
};

pdf.ApplyStamp(logo, PageSelection.FirstPage);
pdf.SaveAs("watermarked-invoice.pdf");
$vbLabelText   $csharpLabel

You can also create complex layouts with multiple images:

// Add images from Base64 strings
string base64Image = Convert.ToBase64String(File.ReadAllBytes("signature.png"));
HtmlStamper signatureStamp = new HtmlStamper($"<img src='data:image/png;base64,{base64Image}'/>");
signatureStamp.HorizontalAlignment = HorizontalAlignment.Right;
signatureStamp.VerticalAlignment = VerticalAlignment.Bottom;
pdf.ApplyStamp(signatureStamp);
// Add images from Base64 strings
string base64Image = Convert.ToBase64String(File.ReadAllBytes("signature.png"));
HtmlStamper signatureStamp = new HtmlStamper($"<img src='data:image/png;base64,{base64Image}'/>");
signatureStamp.HorizontalAlignment = HorizontalAlignment.Right;
signatureStamp.VerticalAlignment = VerticalAlignment.Bottom;
pdf.ApplyStamp(signatureStamp);
$vbLabelText   $csharpLabel

PDF viewer showing a simple document with 'Hello World' text and the IronPDF logo watermark centered on the page - demonstrating IronPDF's image stamping feature with precise positioning and opacity control

This example uses the ChromePdfRenderer class to render a new PDF from an HTML string. Using IronPDF's image stamping tool, you create an image from the provided URL and apply it to the PDF. This demonstrates adding images to your PDF page with minimal code. The rendering options provide full control over output quality.

How Can I Control Image Position and Dimensions in IronPDF?

IronPDF provides extensive customization for image placement. You specify page location by setting alignment and offset through the stamping tool's positioning feature. The library supports both absolute positioning with coordinates and relative positioning using alignment options. Advanced features include custom paper sizes and margin control for precise layouts.

How Do I Add Images to PDFs Using iTextSharp?

How Do I Install and Configure iTextSharp?

Install iTextSharp via NuGet. Unlike IronPDF's complete platform support, iTextSharp has limited deployment options:

Install-Package itext7

Once configured, proceed to add images using iTextSharp's document manipulation features. The library requires additional configuration for font management and UTF-8 support.

What Does Basic Image Addition Look Like in iTextSharp?

Here's how to insert an image using iTextSharp:

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.IO.Image;

class Program
{
    public static void Main(string[] args)
    {
        // Initialize PDF writer
        var pdfWriter = new PdfWriter("output.pdf");

        // Initialize PDF document
        var pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfWriter);

        // Initialize document
        var document = new Document(pdfDocument);

        // Create ImageData from image file
        ImageData imageData = ImageDataFactory.Create("iText.png");

        // Create an Image instance
        Image image = new Image(imageData);

        // Set fixed position for the image in the PDF
        image.SetFixedPosition(50, 100);  // x, y coordinates

        // Scale image to fit within specified dimensions
        image.ScaleToFit(200, 200);  // Width, Height

        // Add image to document
        document.Add(image);

        // Close the document
        document.Close();
    }
}
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.IO.Image;

class Program
{
    public static void Main(string[] args)
    {
        // Initialize PDF writer
        var pdfWriter = new PdfWriter("output.pdf");

        // Initialize PDF document
        var pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfWriter);

        // Initialize document
        var document = new Document(pdfDocument);

        // Create ImageData from image file
        ImageData imageData = ImageDataFactory.Create("iText.png");

        // Create an Image instance
        Image image = new Image(imageData);

        // Set fixed position for the image in the PDF
        image.SetFixedPosition(50, 100);  // x, y coordinates

        // Scale image to fit within specified dimensions
        image.ScaleToFit(200, 200);  // Width, Height

        // Add image to document
        document.Add(image);

        // Close the document
        document.Close();
    }
}
$vbLabelText   $csharpLabel

How Can I Add Multiple Images and Handle Complex Layouts?

For complex scenarios like creating product catalogs or photo albums, you manage layout manually. IronPDF's table of contents feature and bookmark support can organize multi-page documents:

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.IO.Image;
using iText.Layout.Properties;

// Create a grid of images
var pdfWriter = new PdfWriter("catalog.pdf");
var pdfDocument = new PdfDocument(pdfWriter);
var document = new Document(pdfDocument);

// Add images in a grid layout
float xPosition = 50;
float yPosition = 750;
int imagesPerRow = 3;
int currentImage = 0;

string[] imageFiles = { "product1.jpg", "product2.jpg", "product3.jpg", 
                       "product4.jpg", "product5.jpg", "product6.jpg" };

foreach (string imagePath in imageFiles)
{
    ImageData imageData = ImageDataFactory.Create(imagePath);
    Image image = new Image(imageData);

    // Calculate position
    int column = currentImage % imagesPerRow;
    int row = currentImage / imagesPerRow;

    float x = xPosition + (column * 180);
    float y = yPosition - (row * 250);

    image.SetFixedPosition(x, y);
    image.ScaleToFit(150, 200);

    document.Add(image);
    currentImage++;
}

document.Close();
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.IO.Image;
using iText.Layout.Properties;

// Create a grid of images
var pdfWriter = new PdfWriter("catalog.pdf");
var pdfDocument = new PdfDocument(pdfWriter);
var document = new Document(pdfDocument);

// Add images in a grid layout
float xPosition = 50;
float yPosition = 750;
int imagesPerRow = 3;
int currentImage = 0;

string[] imageFiles = { "product1.jpg", "product2.jpg", "product3.jpg", 
                       "product4.jpg", "product5.jpg", "product6.jpg" };

foreach (string imagePath in imageFiles)
{
    ImageData imageData = ImageDataFactory.Create(imagePath);
    Image image = new Image(imageData);

    // Calculate position
    int column = currentImage % imagesPerRow;
    int row = currentImage / imagesPerRow;

    float x = xPosition + (column * 180);
    float y = yPosition - (row * 250);

    image.SetFixedPosition(x, y);
    image.ScaleToFit(150, 200);

    document.Add(image);
    currentImage++;
}

document.Close();
$vbLabelText   $csharpLabel

PDF viewer showing a centered ITEXT logo with 'CORE' text on an otherwise blank page - example output of iTextSharp's image insertion demonstrating basic positioning and scaling capabilities

The image is added at coordinates (50, 100) and scaled to fit within 200x200 pixels. The PdfWriter creates the output file, enabling PDF writer functionality for handling images. For better organization, consider using page numbers and headers/footers.

How Can I Control Image Position and Dimensions in iTextSharp?

iTextSharp provides control over positioning and size through manual coordinate calculations. You scale images while maintaining aspect ratio or stretch to specific dimensions. The SetFixedPosition method offers precise placement control, and you can manipulate alignment and rotation. However, it lacks IronPDF's viewport controls and responsive sizing options.

How Do IronPDF and iTextSharp Compare in Performance?

Both libraries handle image addition to PDFs with notable differences:

  • IronPDF improve for performance, handling large documents with multiple images efficiently. It renders PDFs faster, especially for graphically intensive documents. The library supports async operations and parallel processing for improved throughput. Memory stream operations reduce disk I/O for better performance.

  • iTextSharp offers good performance but may struggle with very large PDFs or numerous high-resolution images. While efficient, some developers report slower rendering times compared to IronPDF in complex use cases involving multiple page operations. The library lacks built-in linearization support for web optimization.

What Are the Advanced Image Features Available?

How Do They Handle Different Image Formats?

IronPDF supports complete image formats:

iTextSharp supports standard formats:

  • JPEG/JPG
  • PNG with alpha channel
  • GIF (first frame only)
  • TIFF (single page)
  • BMP and other bitmap formats

What About Image Quality and Compression?

IronPDF provides built-in compression options balancing file size and quality. The library offers sanitization features and flattening capabilities:

// Configure compression when rendering
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.JpegQuality = 85; // 0-100 quality scale

// Compress existing PDFs with images
PdfDocument pdf = PdfDocument.FromFile("large-images.pdf");
pdf.CompressImages(60); // Compress to 60% quality
pdf.SaveAs("compressed.pdf");

// Additional optimization options
renderer.RenderingOptions.GrayScale = true; // Convert to grayscale
renderer.RenderingOptions.DPI = 150; // Reduce DPI for web viewing
// Configure compression when rendering
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.JpegQuality = 85; // 0-100 quality scale

// Compress existing PDFs with images
PdfDocument pdf = PdfDocument.FromFile("large-images.pdf");
pdf.CompressImages(60); // Compress to 60% quality
pdf.SaveAs("compressed.pdf");

// Additional optimization options
renderer.RenderingOptions.GrayScale = true; // Convert to grayscale
renderer.RenderingOptions.DPI = 150; // Reduce DPI for web viewing
$vbLabelText   $csharpLabel

iTextSharp requires manual compression handling through image data manipulation, increasing implementation complexity for quality controls. You must implement your own grayscale conversion and DPI adjustments.

How Can I Extract Images from Existing PDFs?

IronPDF provides reliable image extraction capabilities:

// Extract all images from a PDF
PdfDocument pdf = PdfDocument.FromFile("document.pdf");
var images = pdf.ExtractAllImages();

foreach (var image in images)
{
    // Save extracted images
    image.SaveAs($"extracted_image_{images.IndexOf(image)}.png");
}

// Extract images from specific pages
var pageImages = pdf.ExtractImagesFromPage(0); // First page
// Extract all images from a PDF
PdfDocument pdf = PdfDocument.FromFile("document.pdf");
var images = pdf.ExtractAllImages();

foreach (var image in images)
{
    // Save extracted images
    image.SaveAs($"extracted_image_{images.IndexOf(image)}.png");
}

// Extract images from specific pages
var pageImages = pdf.ExtractImagesFromPage(0); // First page
$vbLabelText   $csharpLabel

What Are the Licensing and Pricing Models?

Which Library Should I Choose for Adding Images to PDFs?

Feature comparison table between IronPDF and iTextSharp PDF libraries showing IronPDF's advantages in ease of use, performance, licensing flexibility, complete image format support, and advanced positioning capabilities for enterprise PDF generation

Both IronPDF and iTextSharp provide effective tools for adding images to PDFs in C#, each with distinct advantages. IronPDF excels with ease of use, performance, and licensing flexibility, making it ideal for handling complex PDFs and images with minimal code. It offers better scalability for large PDFs and provides one-time purchase licensing, avoiding recurring costs or complicated open-source restrictions.

The library's support for modern formats like SVG and WebP, combined with built-in compression capabilities and intuitive positioning APIs, suits enterprise applications requiring high-quality document generation. IronPDF's Chrome rendering engine ensures pixel-perfect output across all platforms.

iTextSharp suits open-source projects, though requiring more code for equivalent results and potentially facing performance issues with larger PDFs. Its lower-level API provides granular control but increases development complexity. The library lacks modern features like responsive CSS support and JavaScript rendering.

For enterprise applications, IronPDF's advantages include Docker support, AWS Lambda compatibility, and Azure Functions integration. The library also provides PDF/A compliance and PDF/UA accessibility for regulatory requirements.

Ready to simplify your PDF image handling? IronPDF delivers efficient image addition to PDFs with minimal code. Try IronPDF and experience simplified image integration in your C# projects. The implementation handles the complexity for you, saving time and improve your PDF generation workflow. Explore the complete feature set and join thousands of developers who've simplified their PDF operations.

참고해 주세요iTextSharp is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by iTextSharp. All product names, logos, and brands are property of their respective owners. Comparisons are for informational purposes only and reflect publicly available information at the time of writing.

자주 묻는 질문

.NET 애플리케이션에서 PDF에 이미지를 추가하려면 어떻게 해야 하나요?

배치 및 크기를 정밀하게 제어하여 이미지를 쉽게 삽입할 수 있는 ImageStamper 기능을 활용하여 IronPDF를 사용하여 PDF에 이미지를 추가할 수 있습니다.

대용량 PDF 파일에 IronPDF를 사용하면 어떤 성능상의 이점이 있나요?

IronPDF는 특히 대용량 PDF 파일과 고해상도 이미지의 고성능에 최적화되어 있어 효율적인 처리가 필요한 서버 기반 애플리케이션에 이상적입니다.

IronPDF는 이미지를 PDF에 삽입하는 과정을 어떻게 간소화하나요?

IronPDF는 PDF 문서 내에 이미지를 배치하고 크기를 조정하는 데 최소한의 코드만 필요한 직관적인 API를 제공하여 이미지 임베딩을 간소화하고 개발자의 생산성을 향상시킵니다.

ITextSharp와 비교하여 IronPDF의 라이선스 모델은 무엇인가요?

IronPDF는 일회성 구매로 영구 라이선스를 제공하여 반복적인 구독 비용을 없애고, iTextSharp는 오픈 소스 사용을 위한 AGPL 라이선스와 독점 프로젝트용 상용 옵션을 사용합니다.

IronPDF를 사용하여 PDF에 이미지를 추가하는 코드 예제를 제공할 수 있나요?

물론이죠! 이 글의 예시에서 볼 수 있듯이 IronPDF의 PdfDocumentImageStamper 클래스를 사용하여 몇 줄의 코드만으로 이미지를 PDF에 임베드할 수 있습니다.

이미지 배치 사용자 지정은 IronPDF와 iTextSharp 간에 어떻게 다른가요?

IronPDF는 정렬 및 오프셋 설정을 통해 간단한 이미지 배치 사용자 지정을 제공하는 반면, iTextSharp는 SetFixedPosition와 같은 방법을 사용하여 이미지 위치를 세부적으로 제어할 수 있습니다.

IronPDF와 iTextSharp 중 하나를 선택할 때 고려해야 할 주요 사항은 무엇인가요?

사용 편의성, 대용량 파일에 대한 성능, 라이선스 요구 사항 등의 요소에 따라 IronPDF와 iTextSharp 중 하나를 선택해야 합니다. IronPDF는 사용자 친화적인 접근 방식과 확장성 때문에 선호되는 반면, iTextSharp는 오픈 소스 프로젝트에 적합합니다.

고성능 서버 애플리케이션에 IronPDF가 권장되는 이유는 무엇인가요?

IronPDF의 아키텍처는 대용량 문서와 이미지를 효율적으로 처리하는 고성능을 위해 설계되었으므로 속도와 안정성이 요구되는 서버 애플리케이션에 탁월한 선택이 될 수 있습니다.

PDF에 이미지를 추가할 때 일반적인 문제 해결 단계는 무엇인가요?

PDF의 이미지 삽입 문제를 해결할 때는 이미지 경로가 올바른지 확인하고, 파일 액세스 권한이 있는지 확인하고, 사용 중인 PDF 라이브러리에서 이미지 형식이 지원되는지 확인합니다.

IronPDF 평가판은 개발자에게 어떤 도움이 되나요?

IronPDF 평가판을 통해 개발자는 기능을 살펴보고 PDF 이미지 임베딩 처리 기능을 테스트하여 C# 프로젝트에서 PDF 처리를 간소화할 수 있는 기회를 얻을 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.