Reader Q&A – PDFs in iOS

I got a question from a reader last night who was looking at some code from one of my Xamarin seminars.

Ryan asked about how to extract the content from a pdf file, draw on it, and email it in iOS.

One way to do this is using Core Graphics, as shown in the following snippet:

var pdf = CGPDFDocument.FromFile (Path.Combine (NSBundle.MainBundle.BundlePath, "input.pdf"));
var data = new NSMutableData ();
var rect = new CGRect (0, 0, 400, 400);

UIGraphics.BeginPDFContext (data, rect, null);
UIGraphics.BeginPDFPage ();

var g = UIGraphics.GetCurrentContext (); 
g.ScaleCTM (1, -1);
g.TranslateCTM (0, -400);

var p = pdf.GetPage (1); 

var txf = p.GetDrawingTransform (CGPDFBox.Crop, rect, 0, true);
g.ConcatCTM (txf);
g.DrawPDFPage (p);

g.SetLineWidth (2);
UIColor.Red.SetFill ();
UIColor.Blue.SetStroke ();

var path = new CGPath ();

path.AddLines (new [] {
	new CGPoint (100, 200),
	new CGPoint (160, 100), 
	new CGPoint (220, 200)

path.CloseSubpath ();

g.AddPath (path);
g.DrawPath (CGPathDrawingMode.FillStroke);

UIGraphics.EndPDFContent ();

var mail = new MFMailComposeViewController ();
mail.AddAttachmentData (data, "text/x-pdf", "output.pdf");

view raw

hosted with ❤ by GitHub

If you have a question feel free to contact me through my blog. I get lots of questions like this, but I do my best to respond to them all.

Updated Scratch Ticket Code

Someone asked a question in the Xamarin forums last week about the scratch ticket code I wrote a while back, so I decided to update it to work with the unified API and show how to get an image from the view, which is what the person in the forums was asking for.

One thing I find super useful in Xamarin Studio is the ability to see the image at runtime in the debugger (similar to what you’d get in Xamarin Sketches), as shown below:

image from view

You can get the updated code from my repo: