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

cg_pdf.md

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.

One thought on “Reader Q&A – PDFs in iOS

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 )

Facebook photo

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

Connecting to %s