How to add text at position in iTextSharp


Probably you know the library for PDF  iTextSharp.

And you are searched for a solution how to add text at particular XY coordinates to an existing PDF

In this example I will get the coordinates in Foxit Reader

First you set up the Measurement Units to be in Points (File – Preferences – Documents)

Foxit-Reader-Preferences

Then in the document you put the Ruler with Ctrl + R and will see

Foxit-Reader-Coordinates

public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, Point point)
 {
     //variables
 string pathin = inputPdfPath;
 string pathout = outputPdfPath;

 //create PdfReader object to read from the existing document
 using (PdfReader reader = new PdfReader(pathin))
 //create PdfStamper object to write to get the pages from reader
 using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)))
 {
 //select two pages from the original document
 reader.SelectPages("1-2");

 //gettins the page size in order to substract from the iTextSharp coordinates
 var pageSize = reader.GetPageSize(1);

 // PdfContentByte from stamper to add content to the pages over the original content
 PdfContentByte pbover = stamper.GetOverContent(1);

 //add content to the page using ColumnText
 Font font = new Font();
 font.Size = 45;

 //setting up the X and Y coordinates of the document
 int x = point.X;
 int y = point.Y;

 y = (int) (pageSize.Height - y);

 ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
       }
 }

The usage is very simple


string text = "Hello World";
Point textPoint = new Point(480, 1440);
AddTextToExistingPdf("inputPdf.pdf", "outputPdf.pdf", text, textPont);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s