Iris Classon
Iris Classon - In Love with Code

A simple annotation example with PDFSharp

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.

[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;  

}
[/sourcecode]

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.

 

 

Comments

Leave a comment below, or by email.
Will
8/15/2015 7:34:19 AM
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? 


Last modified on 2015-03-07

comments powered by Disqus