C# PDF Sharp position in document

josephj1989 picture josephj1989 · Nov 7, 2012 · Viewed 23.4k times · Source

Hi I am using PDF sharp to print user input onto positions in a template document.

The data (fields) are collected from user (web page) and written at appropriate positions on the document using drawstring method.

Currently I am finding the Pixel position of each templated field in each page by trial and error .It would be much easier if there is a way to determine pixel position of each field in pdf page.

Any suggestion would be most helpful.

thanks

Answer

Kevin Lee Garner picture Kevin Lee Garner · Sep 3, 2014

I had the same issue as you, josephj1989, and I found what I believe to be our answer.

According to this page in the PDFSharp documentation,

The current implementation of PDFsharp has only one layout of the graphics context. The origin (0, 0) is top left and coordinates grow right and down. The unit of measure is always point (1/72 inch).

So, say I want to draw an image 3 inches from the left and 7.5 inches from the top of an 8.5 x 11 page, then I would do something like this:

PdfDocument document = GetBlankPdfDocument();
PdfPage myPage = document.AddPage();
myPage.Orientation = PdfSharp.PageOrientation.Portrait;
myPage.Width = XUnit.FromInch(8.5);
myPage.Height = XUnit.FromInch(11);
XImage myImage = GetSampleImage();

double myX = 3 * 72;
double myY = 7.5 * 72;
double someWidth = 126;
double someHeight = 36;

XGraphics gfx = XGraphics.FromPdfPage(myPage);
gfx.DrawImage(myBarcode, myX, myY, someWidth, someHeight);

I tested this out myself with a barcode image, and I found that when you use their formula for measuring positioning, you can get a level of precision at, well, 1/72 of an inch. That's not bad.

So, at this point, it'd be good to create some kind of encapsulation for such measurements so that we're focused mostly on the task at hand and not the details of conversion.

public static double GetCoordinateFromInch(double inches)
{
  return inches * 72;
}

We could go on to make other helpers in this way...

public static double GetCoordinateFromCentimeter(double centimeters)
{
  return centimeters * 0.39370 * 72;
}

With such helper methods, we could do this with the previous sample code:

double myX = GetCoordinateFromInch(3);
double myY = GetCoordinateFromInch(7.5);
double someWidth = 126;
double someHeight = 36;

XGraphics gfx = XGraphics.FromPdfPage(myPage);
gfx.DrawImage(myBarcode, myX, myY, someWidth, someHeight);

I hope this is helpful. I'm sure you will write cleaner code than what is in my example. Additionally, there are probably much smarter ways to streamline this process, but I just wanted to put something here that would make immediate use of what we saw in the documentation.

Happy PDF Rendering!