News Category

Image

Image (7)

Spire.PDF allows extracting images from signatures using ExtractSignatureAsImages method in PdfFormWidget class. This article demonstrates how we can use Spire.PDF to implement this feature.

Code Snippet:

Step 1: Instantiate an object of PdfDocument class and load the PDF document.

PdfDocument document = new PdfDocument("sample.pdf");

Step 2: Get the existing forms of the document.

PdfFormWidget form = document.Form as PdfFormWidget;

Step 3: Extract images from signatures in the existing forms and put them into an Image Array.

Image[] images = form.ExtractSignatureAsImages();

Step 4: Save the images to disk.

int i = 0;
for (int j = 0; j < images.Length; j++)
{
    images[j].Save(String.Format(@"Image/Image-{0}.png", i), ImageFormat.Png);
    i++;
}

Screenshot:

How to Extract Image from Signature in PDF

Full code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Widget;
using System;
using System.Drawing;
using System.Drawing.Imaging;


namespace ExtractImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the PDF document
            PdfDocument document = new PdfDocument("sample.pdf");

            //Get the existing forms of the document
            PdfFormWidget form = document.Form as PdfFormWidget;

            //Extract images from signatures in the existing forms
            Image[] images = form.ExtractSignatureAsImages();

            //Save the images to disk
            int i = 0;
            for (int j = 0; j < images.Length; j++)
            {
                images[j].Save(String.Format(@"Image/Image-{0}.png", i), ImageFormat.Png);
                i++;
            }

            //Close the document
            document.Close();
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Widget
Imports System.Drawing
Imports System.Drawing.Imaging


Namespace ExtractImage
	Class Program
		Private Shared Sub Main(args As String())
			'Load the PDF document
			Dim document As New PdfDocument("sample.pdf")

			'Get the existing forms of the document
			Dim form As PdfFormWidget = TryCast(document.Form, PdfFormWidget)

			'Extract images from signatures in the existing forms
			Dim images As Image() = form.ExtractSignatureAsImages()

			'Save the images to disk
			Dim i As Integer = 0
			For j As Integer = 0 To images.Length - 1
				images(j).Save([String].Format("Image/Image-{0}.png", i), ImageFormat.Png)
				i += 1
			Next

			'Close the document
			document.Close()
		End Sub
	End Class
End Namespace

We have already had an article of showing how to replace the image on the existing PDF file. Starts from Spire.PDF V3.8.45, it newly supports to update the image on button field via the method of field.SetButtonImage(PdfImage.FromFile(@"")). This article will focus on demonstrate how to replace the image on the button field in C#.

Firstly, check the original PDF file with the button field.

How to change the image on button field in C#

Step 1: Create a PDF document and load from file.

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.PDF", FileFormat.PDF);

Step 2: Get the form from the loaded PDF document.

PdfFormWidget form = pdf.Form as PdfFormWidget;

Step 3: Find the button field named "Image" and then set a new image for this button field.

for (int i = 0; i < form.FieldsWidget.Count; i++)
{
    if (form.FieldsWidget[i] is PdfButtonWidgetFieldWidget)
    {
        PdfButtonWidgetFieldWidget field = form.FieldsWidget[i] as PdfButtonWidgetFieldWidget;
        if (field.Name == "Image")
        { field.SetButtonImage(PdfImage.FromFile("logo.png")); }
    }
}

Step 4: Save the document to file.

pdf.SaveToFile("result.pdf");

Effective screenshot after replace the image on the button field.

How to change the image on button field in C#

Full codes:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Widget;


namespace ImageButton
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("Sample.PDF", FileFormat.PDF);

            PdfFormWidget form = pdf.Form as PdfFormWidget;

            for (int i = 0; i < form.FieldsWidget.Count; i++)
            {
                if (form.FieldsWidget[i] is PdfButtonWidgetFieldWidget)
                {
                    PdfButtonWidgetFieldWidget field = form.FieldsWidget[i] as PdfButtonWidgetFieldWidget;
                    if (field.Name == "Image")
                    { field.SetButtonImage(PdfImage.FromFile("logo.png")); }

                }
            }

            pdf.SaveToFile("result.pdf");
        }
    }
}

Universal 3D (U3D) is a compressed file format for 3D computer graphic data. 3D modules in U3D format can be inserted into PDF documents and interactively visualized by Acrobat Reader. This article presents how to embed a pre-created U3D file into a PDF document using Spire.PDF in C#, VB.NET.

Main Steps:

Step 1: Initialize a new object of PdfDocuemnt, and add a blank page to the PDF document.

PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();

Step 2: Draw a rectangle on the page to define the canvas area for the 3D file.

Rectangle rt = new Rectangle(0, 80, 200, 200);

Step 3: Initialize a new object of Pdf3DAnnotation, load the .u3d file as 3D annotation.

Pdf3DAnnotation annotation = new Pdf3DAnnotation(rt, "teapot.u3d");
annotation.Activation = new Pdf3DActivation();
annotation.Activation.ActivationMode = Pdf3DActivationMode.PageOpen;

Step 4: Define a 3D view mode.

Pdf3DView View= new Pdf3DView();
View.Background = new Pdf3DBackground(new PdfRGBColor(Color.Purple
));
View.ViewNodeName = "test";
View.RenderMode = new Pdf3DRendermode(Pdf3DRenderStyle.Solid);
View.InternalName = "test";
View.LightingScheme = new Pdf3DLighting();
View.LightingScheme.Style = Pdf3DLightingStyle.Day;

Step 5: Set the 3D view mode for the annotation.

annotation.Views.Add(View);

Step 6: Add the annotation to PDF.

page.AnnotationsWidget.Add(annotation);

Step 7: Save the file.

doc.SaveToFile("Create3DPdf.pdf", FileFormat.PDF);

Output:

How to Embed 3D Interactive Graphics into PDF Document in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace Embed3DInteractiveGraphics
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();

            Rectangle rt = new Rectangle(0, 80, 200, 200); 
            Pdf3DAnnotation annotation = new Pdf3DAnnotation(rt, "teapot.u3d");
            annotation.Activation = new Pdf3DActivation();
            annotation.Activation.ActivationMode = Pdf3DActivationMode.PageOpen; 
            Pdf3DView View= new Pdf3DView();
            View.Background = new Pdf3DBackground(new PdfRGBColor(Color.Purple));
            View.ViewNodeName = "test";
            View.RenderMode = new Pdf3DRendermode(Pdf3DRenderStyle.Solid);
            View.InternalName = "test";
            View.LightingScheme = new Pdf3DLighting();
            View.LightingScheme.Style = Pdf3DLightingStyle.Day;
            annotation.Views.Add(View);

            page.AnnotationsWidget.Add(annotation);
            doc.SaveToFile("Create3DPdf.pdf", FileFormat.PDF);
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Annotations
Imports Spire.Pdf.Graphics
Imports System.Drawing

Namespace Embed3DInteractiveGraphics
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New PdfDocument()
			Dim page As PdfPageBase = doc.Pages.Add()

			Dim rt As New Rectangle(0, 80, 200, 200)
			Dim annotation As New Pdf3DAnnotation(rt, "teapot.u3d")
			annotation.Activation = New Pdf3DActivation()
			annotation.Activation.ActivationMode = Pdf3DActivationMode.PageOpen
			Dim View As New Pdf3DView()
			View.Background = New Pdf3DBackground(New PdfRGBColor(Color.Purple))
			View.ViewNodeName = "test"
			View.RenderMode = New Pdf3DRendermode(Pdf3DRenderStyle.Solid)
			View.InternalName = "test"
			View.LightingScheme = New Pdf3DLighting()
			View.LightingScheme.Style = Pdf3DLightingStyle.Day
			annotation.Views.Add(View)

			page.AnnotationsWidget.Add(annotation)
			doc.SaveToFile("Create3DPdf.pdf", FileFormat.PDF)
		End Sub
	End Class
End Namespace

Spire.PDF for .NET is a PDF component which contains an incredible wealth of features to create, read, edit and manipulate PDF documents on .NET, Silverlight and WPF Platform. As a professional .NET PDF component, it also includes many useful features, for example, functionalities of adding header and footer, drawing table, saving PDF document as tiff and Splitting tiff image and drawing to pdf document without installing Adobe Acrobat or any other third party libraries.

This article would introduce a detail method to split the tiff image and draw to pdf document. The below picture show the effect of splitting tiff image and drawing to pdf document:

Split tiff image and Convert to pdf document

The main steps of the method are:

One: Split multi-page TIFF file to multiple frames

  • Load a multipage Tiff.
  • Use Image.GetFrameCount method to get the number of frames of tiff Image.
  • Initialize a new instance of Guid to save the dimension from tiff image.
  • Using Guid to initialize a new instance of the System.Drawing.Imaging.FrameDimension class.
  • Iterate over the Tiff Frame Collection and save them to Image array.

Two: Draw image to PDF

  • Initialize a new instance of Spire.Pdf.PdfDocument.
  • Iterate over the image array.
  • Use Spire.Pdf.PdfPageBase.Canvas.DrawImage method to draw image into page with the specified coordinates and image size.

Download and install Spire.Pdf for .NET and use below code to experience this method to split tiff and convert it to pdf document.

The full code of method:

[C#]
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace SplitTiff
{
    class Program
    {
        static void Main(string[] args)
        {
            using (PdfDocument pdfDocument = new PdfDocument())
            {
                Image tiffImage = Image.FromFile(@"..\..\demo.tiff");
                Image[] images = SplitTIFFImage(tiffImage);
                for (int i = 0; i < images.Length; i++)
                {
                    PdfImage pdfImg = PdfImage.FromImage(images[i]);
                    PdfPageBase page = pdfDocument.Pages.Add();
                    float width = pdfImg.Width * 0.5f;
                    float height = pdfImg.Height * 0.5f;
                    float x = (page.Canvas.ClientSize.Width - width) / 2;
                    //set the image of the page 
                    page.Canvas.DrawImage(pdfImg, x, 0, width, height);
                }
                pdfDocument.SaveToFile(@"..\..\result.pdf");
                System.Diagnostics.Process.Start(@"..\..\result.pdf");
            }
        }
        public static Image[] SplitTIFFImage(Image tiffImage)
        {
            int frameCount = tiffImage.GetFrameCount(FrameDimension.Page);
            Image[] images = new Image[frameCount];
            Guid objGuid = tiffImage.FrameDimensionsList[0];
            FrameDimension objDimension = new FrameDimension(objGuid);
            for (int i = 0; i < frameCount; i++)
            {
                tiffImage.SelectActiveFrame(objDimension, i);
                using (MemoryStream ms = new MemoryStream())
                {
                    tiffImage.Save(ms, ImageFormat.Tiff);
                    images[i] = Image.FromStream(ms);
                }
            }
            return images;
        }
    }
}
[VB.NET]
Imports System
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace SplitTiff
    Class Program
        Shared Sub Main(ByVal args() As String)
            Using pdfDocument As New PdfDocument

                Dim tiffImage As Image = Image.FromFile("..\..\demo.tiff")
                Dim images() As Image = SplitTIFFImage(tiffImage)

                Dim i As Integer
                For i = 0 To images.Length - 1 Step i + 1
                    Dim pdfImg As PdfImage = PdfImage.FromImage(images(i))
                    Dim page As PdfPageBase = pdfDocument.Pages.Add()
                    Dim width As Single = pdfImg.Width * 0.5F
                    Dim height As Single = pdfImg.Height * 0.5F
                    Dim x As Single = (page.Canvas.ClientSize.Width - width) / 2
                    'set the image of the page 
                    page.Canvas.DrawImage(pdfImg, x, 0, width, height)
                Next


                pdfDocument.SaveToFile("..\..\result.pdf")
                System.Diagnostics.Process.Start("..\..\result.pdf")
            End Using
        End Sub
        Private Shared Function SplitTIFFImage(ByVal tiffImage As Image)

            Dim frameCount As Integer = tiffImage.GetFrameCount(FrameDimension.Page)
            Dim images() As Image = New Image(frameCount) {}
            Dim objGuid As Guid = tiffImage.FrameDimensionsList(0)
            Dim objDimension As FrameDimension = New FrameDimension(objGuid)
            Dim i As Integer
            For i = 0 To frameCount - 1 Step i + 1
                tiffImage.SelectActiveFrame(objDimension, i) 

                Using ms As New MemoryStream

                    tiffImage.Save(ms, ImageFormat.Tiff)
                    images(i) = Image.FromStream(ms)
                End Using

            Next
            Return images
        End Function
    End Class
End Namespace

If you are interested in the method of converting pdf to tiff image you can refer the Save PDF Document as tiff image article in our website.

This sample demo has demonstrated how to draw nested grid in PDF document and set grid row&cell format. In the following section, we are going to create a simple PDF grid and show you how to insert an image to a specific PDF grid cell in C#. Before we can follow the code snippet below to accomplish the task, we have to prepare the environment first.

Download Spire.PDF and install it on system, create or open a .NET class application in Visual Studio 2005 or above versions, add Spire.PDF.dll to your .NET project assemblies.Then let's code step by step to make a better understanding about the whole procedure.

Step 1: Create a PDF document and add a new page.

PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();

Step 2: Create a 2×2 grid to PDF.

PdfGrid grid = new PdfGrid();
PdfGridRow row = grid.Rows.Add();
           row = grid.Rows.Add();
                 grid.Columns.Add(2);

Step 3: Set the cell padding of the PDF grid.

grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);

Step 4: Set the width of the columns.

float width = page.Canvas.ClientSize.Width - (grid.Columns.Count + 1);
      grid.Columns[0].Width = width * 0.25f;
      grid.Columns[1].Width = width * 0.25f;

Step 5: Load an image from disk.

PdfGridCellContentList lst = new PdfGridCellContentList();
PdfGridCellContent textAndStyle = new PdfGridCellContent();
textAndStyle.Image = PdfImage.FromFile("..\\..\\image1.jpg");

Step 6: Set the size of image and insert it to the first cell.

textAndStyle.ImageSize = new SizeF(50, 50);
lst.List.Add(textAndStyle);
          
grid.Rows[0].Cells[0].Value = lst;
grid.Rows[1].Height = grid.Rows[0].Height;

Step 7: Draw PDF grid into page at the specific location.

PdfLayoutResult result = grid.Draw(page, new PointF(10, 30));

Step 8: Save to a PDF file and launch the file.

doc.SaveToFile(outputFile, FileFormat.PDF);
System.Diagnostics.Process.Start(outputFile);

Result:

Insert an Image to PDF Grid Cell in C#

Full C# Code:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Grid;
using System.Drawing;

namespace InsertImage
{
    class Program
    {
        static void Main(string[] args)
        {
            string outputFile = @"..\..\output.pdf";
            //Create a pdf document
            PdfDocument doc = new PdfDocument();
            //Add a page for the pdf document
            PdfPageBase page = doc.Pages.Add();
            //Create a pdf grid
            PdfGrid grid = new PdfGrid();
            //Set the cell padding of pdf grid
            grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
            //Add a row for pdf grid
            PdfGridRow row = grid.Rows.Add();
            //Add two columns for pdf grid 
            grid.Columns.Add(2);
            float width = page.Canvas.ClientSize.Width - (grid.Columns.Count + 1);
            //Set the width of the first column
            grid.Columns[0].Width = width * 0.25f;
            grid.Columns[1].Width = width * 0.25f;
            //Add a image
            PdfGridCellContentList lst = new PdfGridCellContentList();
            PdfGridCellContent textAndStyle = new PdfGridCellContent();
            textAndStyle.Image = PdfImage.FromFile("..\\..\\image1.jpg");
            //Set the size of image
            textAndStyle.ImageSize = new SizeF(50, 50);
            lst.List.Add(textAndStyle);
            //Add a image into the first cell. 
            row.Cells[0].Value = lst;
            //Draw pdf grid into page at the specific location
            PdfLayoutResult result = grid.Draw(page, new PointF(10, 30));
            //Save to a pdf file 
            doc.SaveToFile(outputFile, FileFormat.PDF);
            System.Diagnostics.Process.Start(outputFile);
        }
    }
}

This section aims at providing developers a detail solution to set transparency for image in PDF file with C#, VB.NET via this PDF api Spire.PDF for .NET.

Spire.PDF for .NET enables you to set transparency for PDF image directly by utilizing one core method: Spire.Pdf.PdfPageBase.Canvas.SetTransparency(float alphaPen, float alphaBrush, PdfBlendMode blendMode); There are three parameters passed in this method. The first parameter is the alpha value for pen operations; while the second parameter is the alpha value for brush operations; and the last parameter is the blend mode. Now, let us see how to set PDF transparency step by step.

Set Transparency Images in PDF File

Step1: Prepare an image file

In my solution, I need create a new PDF file and insert an existing image file to PDF. Finally set transparency for this PDF image. So I prepare an image as below:

Draw Transparency Images

Step2: Download and Install Spire.PDF for .NET

Spire.PDF for .NET is a PDF component that enables developers to generate, read, edit and handle PDF files without Adobe Acrobat. Here you can download Spire.PDF for .NET and install it on system.

Step3: Start a new project and Add references

We can create a project either in Console Application or in Windows Forms Application, either in C# or in VB.NET. Here I use C# Console Application. Since we will use Spire.PDF for .NET, we need add Spire.Pdf.dll as reference. The default path is “..\Spire.PDF\Bin\NET4.0\ Spire.Pdf.dll”

Step 4: Set PDF transparency for PDF image

In this step, first, I initialize a new instance of the class Spire.Pdf.PdfDocument and add a section in the newly created PDF. Then, load the image I have already prepared to the PDF and set the PDF image size. Finally set transparency for this PDF image. When I set transparency, I add a title for the transparency and set position and format for it. After I save the image in PDF by calling this method: PdfPageBase.Canvas.DrawImage(PdfImage image, float x, float y, float width, float height).Then, by using this method: PdfPageBase.Canvas.SetTransparency(float alphaPen, float alphaBrush, PdfBlendMode blendMode); I successfully set transparency for this PDF image. Here we can see the whole code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;

namespace SetTransparencyOfImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initiate a new instance of PdfDocument 
            PdfDocument doc = new PdfDocument();
            //Add one section to the PDF document
            PdfSection section = doc.Sections.Add();
            //Open Image File
            PdfImage image = PdfImage.FromFile(@"..\016.png");
            //Set the Image size in PDF file
            float imageWidth = image.PhysicalDimension.Width / 2;
            float imageHeight = image.PhysicalDimension.Height / 2;

            //Set PDF granphic transparency 
            foreach (PdfBlendMode mode in Enum.GetValues(typeof(PdfBlendMode)))
            {
                PdfPageBase page = section.Pages.Add();
                float pageWidth = page.Canvas.ClientSize.Width;
                float y = 1;
                //Set transparency image title, title position and format
                y = y + 5;
                PdfBrush brush = new PdfSolidBrush(Color.Firebrick);
                PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
                PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
                String text = String.Format("Transparency Blend Mode: {0}", mode);
                page.Canvas.DrawString(text, font, brush, pageWidth / 2, y, format);
                SizeF size = font.MeasureString(text, format);
                y = y + size.Height + 6;
                //write and save the image loaded into PDF
                page.Canvas.DrawImage(image, 0, y, imageWidth, imageHeight);
                page.Canvas.Save();
                //set left and top distance between graphic images
                float d = (page.Canvas.ClientSize.Width - imageWidth) / 5;
                float x = d;
                y = y + d / 2;
                for (int i = 0; i < 5; i++)
                {
                    float alpha = 1.0f / 6 * (5 - i);
                    //set transparency to be alpha
                    page.Canvas.SetTransparency(alpha, alpha, mode);
                    //draw transparency images for the original PDF image
                    page.Canvas.DrawImage(image, x, y, imageWidth, imageHeight);
                    x = x + d;
                    y = y + d / 2;
                }
                page.Canvas.Restore();
            }
            //Save pdf file.
            doc.SaveToFile("Transparency.pdf");
            doc.Close();
            //Launching the Pdf file.
            System.Diagnostics.Process.Start("Transparency.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing

Namespace SetTransparencyOfImage
	Class Program
		Private Shared Sub Main(args As String())
			'Initiate a new instance of PdfDocument 
			Dim doc As New PdfDocument()
			'Add one section to the PDF document
			Dim section As PdfSection = doc.Sections.Add()
			'Open Image File
			Dim image As PdfImage = PdfImage.FromFile("..\016.png")
			'Set the Image size in PDF file
			Dim imageWidth As Single = image.PhysicalDimension.Width / 2
			Dim imageHeight As Single = image.PhysicalDimension.Height / 2

			'Set PDF granphic transparency 
			For Each mode As PdfBlendMode In [Enum].GetValues(GetType(PdfBlendMode))
				Dim page As PdfPageBase = section.Pages.Add()
				Dim pageWidth As Single = page.Canvas.ClientSize.Width
				Dim y As Single = 1
				'Set transparency image title, title position and format
				y = y + 5
				Dim brush As PdfBrush = New PdfSolidBrush(Color.Firebrick)
				Dim font As New PdfTrueTypeFont(New Font("Arial", 16F, FontStyle.Bold))
				Dim format As New PdfStringFormat(PdfTextAlignment.Center)
				Dim text As [String] = [String].Format("Transparency Blend Mode: {0}", mode)
				page.Canvas.DrawString(text, font, brush, pageWidth / 2, y, format)
				Dim size As SizeF = font.MeasureString(text, format)
				y = y + size.Height + 6
				'write and save the image loaded into PDF
				page.Canvas.DrawImage(image, 0, y, imageWidth, imageHeight)
				page.Canvas.Save()
				'set left and top distance between graphic images
				Dim d As Single = (page.Canvas.ClientSize.Width - imageWidth) / 5
				Dim x As Single = d
				y = y + d / 2
				For i As Integer = 0 To 4
					Dim alpha As Single = 1F / 6 * (5 - i)
					'set transparency to be alpha
					page.Canvas.SetTransparency(alpha, alpha, mode)
					'draw transparency images for the original PDF image
					page.Canvas.DrawImage(image, x, y, imageWidth, imageHeight)
					x = x + d
					y = y + d / 2
				Next
				page.Canvas.Restore()
			Next
			'Save pdf file.
			doc.SaveToFile("Transparency.pdf")
			doc.Close()
			'Launching the Pdf file.
			System.Diagnostics.Process.Start("Transparency.pdf")
		End Sub
	End Class
End Namespace

Result Task

After performing above code, we can see the result PDF document as below:

Draw Transparency Images

I have set transparency for PDF image by Spire.PDF for .NET. I sincerely wish it can help you. We e-iceblue team appreciate any kind of queries, comments and advice at E-iceblue Forum. Our professionals are ready to reply you as quick as possible.

Spire.PDF for .NET is a PDF library that meets customers need with fast speed and high efficiency.

Compared with text-only documents, documents containing images are undoubtedly more vivid and engaging to readers. When generating or editing a PDF document, you may sometimes need to insert images to improve its appearance and make it more appealing. In this article, you will learn how to insert, replace or delete images in PDF documents in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Insert an Image into a PDF Document in C# and VB.NET

The following steps demonstrate how to insert an image into an existing PDF document:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the desired page in the PDF document through PdfDocument.Pages[pageIndex] property.
  • Load an image using PdfImage.FromFile() method.
  • Specify the width and height of the image area on the page.
  • Specify the X and Y coordinates to start drawing the image.
  • Draw the image on the page using PdfPageBase.Canvas.DrawImage() method.
  • Save the result document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace InsertImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("Input.pdf");

            //Get the first page in the PDF document
            PdfPageBase page = pdf.Pages[0];

            //Load an image
            PdfImage image = PdfImage.FromFile("image.jpg");

            //Specify the width and height of the image area on the page
            float width = image.Width * 0.50f;
            float height = image.Height * 0.50f;

            //Specify the X and Y coordinates to start drawing the image
            float x = 180f;
            float y = 70f;

            //Draw the image at a specified location on the page
            page.Canvas.DrawImage(image, x, y, width, height);

            //Save the result document
            pdf.SaveToFile("AddImage.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Insert, Replace or Delete Images in PDF

Replace an Image with Another Image in a PDF Document in C# and VB.NET

The following steps demonstrate how to replace an image with another image in a PDF document:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the desired page in the PDF document through PdfDocument.Pages[pageIndex] property.
  • Load an image using PdfImage.FromFile() method.
  • Initialize an instance of the PdfImageHelper class.
  • Get the image information from the page using PdfImageHelper.GetImagesInfo() method.
  • Replace a specific image on the page with the loaded image using PdfImageHelper.ReplaceImage() method.
  • Save the result document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Utilities;

namespace ReplaceImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument doc = new PdfDocument();
            //Load a PDF document
            doc.LoadFromFile("AddImage.pdf");

            //Get the first page
            PdfPageBase page = doc.Pages[0];

            //Load an image
            PdfImage image = PdfImage.FromFile("image1.jpg");

            //Create a PdfImageHelper instance
            PdfImageHelper imageHelper = new PdfImageHelper();
            //Get the image information from the page
            PdfImageInfo[] imageInfo = imageHelper.GetImagesInfo(page);
            //Replace the first image on the page with the loaded image
            imageHelper.ReplaceImage(imageInfo[0], image);

            //Save the result document
            doc.SaveToFile("ReplaceImage.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Insert, Replace or Delete Images in PDF

Delete a Specific Image in a PDF Document in C# and VB.NET

The following steps demonstrate how to delete an image from a PDF document:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the desired page in the PDF document through PdfDocument.Pages[pageIndex] property.
  • Delete a specific image on the page using PdfPageBase.DeleteImage() method.
  • Save the result document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace DeleteImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();
            //Load a PDF document
            pdf.LoadFromFile("AddImage.pdf");

            //Get the first page
            PdfPageBase page = pdf.Pages[0];

            //Delete the first image on the page
            page.DeleteImage(0);

            //Save the result document
            pdf.SaveToFile("DeleteImage.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Insert, Replace or Delete Images in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.