Insert an Image to PDF Grid Cell in C#

Introduction

In this article you can learn various image operations using a PDF document in C# programming. 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#. Images are more attractive for reading the document. Images are related to the contents. Sometimes, an image can describe some content more clearly, like using a chart to show data changes in a period.

Spire.PDF for .NET is a professional .NET PDF component to quickly generate, open, modify and save PDF documents without using Office Automation and enables users to insert an image into PDF and set its size depending on the page using C#. How to draw nested grid in PDF document and set grid row & cell format. This guide introduces an easy method for inserting an image via Spire.PDF for .NET.

Create a ConsoleApplication for the demo. Use the following procedure:

  1. Open Visual Studio
  2. “File” -> “New” -> “Project…”
  3. Select C# Language then select ConsoleApplication and name it “ImageIntoPDF”
  4. Click OK.
  5. Add following code in Program.cs file

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
PdfGridCellTextAndStyleList lst = new PdfGridCellTextAndStyleList();
PdfGridCellTextAndStyle textAndStyle = new PdfGridCellTextAndStyle();
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);
}

Summary

I hope you now understand how to insert images in PDF documents programmatically. If you have any suggestion regarding this article then please contact me.

Contents used from Spire.Doc for more information click here.