Mar 072015
 March 7, 2015  Posted by at 11:38 am C# & F#  Add comments

Because the world needs another one hehe. I’m joking, I’m sure there are plenty but the blog is very much a way for me to tuck away things I’ve done, learned or found. And maybe somebody else can benefit from it or tell me I’m horrible wrong (I’ve learned a lot from comments).

Today, more PDF fun. As you can understand I’ve been having fun with PDF’s on a client project. This time annotating invoices. It’s my first time with PDFSharp, a open source PDF manipulation library. So with enough said, here is a little example for adding a rectangle with a border and some text in the upper right corner of the first page. Notice the annotation is added in memory only, you can of course save the PDF with the annotation.

PDFSHarp example

PDFSharp Example2

PDFSharp Example3

[sourcecode language=”csharp”]
private Stream AnnotatePdf(string text, byte[] pdfBytes, int padding)
var annotatedPdfStream = new MemoryStream();

using (var stream = new MemoryStream(pdfBytes))
using (var document = PdfReader.Open(stream))
var page = document.Pages[PAGE_INDEX];

using (var graphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append))
var font = new XFont("Courier New", 12, XFontStyle.Regular);

var textMeasurements = graphics.MeasureString(text, font);

var rectHeight = textMeasurements.Height + padding;
var rectWidth = textMeasurements.Width + padding;

var x = page.Width – rectWidth – padding;
var y = padding;

var rectangle = new XRect(x, y, rectWidth, rectHeight);

var pen = new XPen(XColors.Black, 1) {DashStyle = XDashStyle.Solid};

var brush = new XSolidBrush(XColor.FromArgb(0, 255, 240, 115));

graphics.DrawRectangle(brush, rectangle);
graphics.DrawRectangle(pen, rectangle);
graphics.DrawString(text, font, XBrushes.Black, rectangle, XStringFormats.Center);

document.Save(annotatedPdfStream, false);
return annotatedPdfStream;

Depending on the size of the PDF and amount of drawing going on it might take a while, annotating the first page of a 50MB PDF took 0.7s so keep that in mind and adjust logic and feedback to the user accordingly. I used the DevExpress PDF control, and PDFSharp can be added to the project using Nuget Package Manager.

PDFSharp Example4



  One Response to “A simple annotation example with PDFSharp”

  1. Hi, thanks for the great article and I am glad that you are back. I would like to know what editor you are showing in the screen shot and what theme you using for syntax highlighting?

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



What is 9 + 9 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)