You are on page 1of 10

9/18/12

Generating PDF Documents

Generating PDF Documents


C.A. Beninati on Jun 27th 2012 with 5 comments

Tutorial Details
Technology: iOS SDK Difficulty: Intermediate Completion Time: 1 Hour In a previous tutorial, I demonstrated how to Read & Display PDF documents with the help of the VFR Reader open source library. In this followup lesson, Ill teach you how to generate your own custom PDF documents in-app as well.

Project Background
In iOS, there are a few different ways to draw content to the screen, or even off-screen. While it wont be necessary to have a deep understanding of these different methods for following this tutorial, it would be well worth your time to become familiar with Core Graphics, UIKit, and maybe even OpenGL ES. You can read more about these subjects from the Apple documentation. Well be using the UIKit framework in our tutorial today, which will give us some good flexibility without inferring too much overhead and complex development. Before reading further, it would be a VERY good idea to read at least the introductory section on Generating PDF Content from the official Apple documentation. Basically, there are five steps to generating a PDF on iOS. The details may vary, but this process will be the same for all PDFs. 1. Make a New PDF File in The Documents Directory Here well set the name and location for our new PDF. 2. Create a Graphics Context This is the environment that well create our content within. Its kind of like the book where well put our PDF pages. 3. Begin a New Page This creates a blank page to draw on. 4. Draw Our Content Here, well put text, images, and other content onto our new page. 5. Finish Our Document We basically close and save our new PDF.
mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/ 1/10

9/18/12

Generating PDF Documents

Project Setup Adding Our Asset


Well be drawing an image onto our PDF, so go ahead and add the tree.jpg image to our project. Since this tutorial is of intermediate difficulty, Ill skip the steps involved in adding images to an Xcode project, but if youre not sure what to do, there are plenty of good tutorials that you can find on Mobiletuts+ that will help you out.

Setting Up Our View


Before getting started on those easy steps, go ahead and open the PDFViewer project from part one. Well add a new button on the MTViewController.xib page, and well label it Make PDF.

mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/

2/10

9/18/12

Generating PDF Documents

Next, well switch to our Assistant editor.

Now we can right-click (control-click) and drag an IBAction into our MTViewController.h, and well name it didClickMakePDF.

mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/

3/10

9/18/12

Generating PDF Documents

mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/

4/10

9/18/12

Generating PDF Documents

Now we can switch back to the the Standard editor, and open the MTViewController.m file, where well implement the rest of our PDF-creating methods.

Setting Our Attributes


In order to keep the content that we draw on our PDF page from drawing right on the edges, well set a 20 point padding. At the top of our MTViewController.m file, just underneath the #import statement, add the following: 1 #eiekadn0 dfnPdig2

And finally, for setup, well create an ivar that we can use to set the size of our PDF pages. Well add this to @ n e f c M V e C n r l e ( , which we can find right below our new # e i estatement. itrae Tiwotolr) dfn 1 2 3 4 @nefcTiwotolr( itraeMVeCnrle) { CSzpgSz; Gie_aeie }

And thats it for the set up. Now, on to the actual PDF methods.

Step 1: Make a New PDF File


Our first method will set up our PDF document and our PDF context. Just beneath the empty didClickMadePDF method, which was created for us when we linked up our Make PDF button earlier, well make a new method called setupPDFDocumentNamed:Width:Height. As the name suggests, well take three parameters- an NSString for our PDF name, and two floats. One float will be for the width and the other for the height of our PDF document.
-(odstpDDcmnNmd(Stig)aeWdh(la)it Hih:fothih vi)euPFouetae:NSrn*nm it:fotwdh egt(la)egt { }

Inside this method, well set the documents page size with the ivar that we created in our interface.
_aeie=CSzMk(it,hih) pgSz Gieaewdh egt;
mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/ 5/10

9/18/12

Generating PDF Documents

Next, well get the path to our Apps documents directory, and append our filename to it to get the new PDFs full path name. 1 2 3 4

NSrnnwDNmNSrntigihomt@%.d"ae; Stig*ePFae=[StigsrnWtFra:"@pf,nm] NAry*ahSerhahoDrcoisnoan(SirrDrcoy Srapts=NSacPtFrietreIDmisNLbayietr NSrndcmnsietrptsojcAIdx0; Stig*ouetDrcoy=[ahbettne:] NSrnpfah=[ouetDrcoysrnBApnigahopnn:eP Stig*dPtdcmnsietrtigypednPtCmoetnw

Step 2: Create a Graphics Context


To create our PDF graphics context, well add a single line to the end of the setupPDF: method that we just created.
UGahcBgnDCnetoiepfah CRcZr,nl; IrpiseiPFotxTFl(dPt, Geteo i)

Now, in the didClickMakePDF method, we can call setupPDF: to begin the PDF creation. Im calling my document NewPDF, and well be using that same name later. If you change your document name, be sure to remember to use the same name in step 6.
[efstpDDcmnNmd@NwD"Wdh80Hih:10; sl euPFouetae:"ePF it:5 egt10]

Step 3: Begin a New Page


Were going to make a simple method called beginPDFPage, using the documents page size that we set in our setupPDF method. Just beneath the setupPDF: method, add the following: 1 2 3

(odbgnDPg vi)eiPFae{ UGahcBgnDPgWtIf(Getae0,_aeiewdhpgS IrpiseiPFaeihnoCRcMk(,0pgSz.it,_ae }

And just like that, we can create a new PDF page by calling [self beginPDFPage]; from our didClickMakePDF method, which will now look like this: 1 2 3 4 (BcinddlcMkPF{ IAto)iCikaeD [efstpDDcmnNmd@NwD"Wdh80Hih:10; sleuPFouetae:"ePFit:5egt10] [efbgnDPg] sleiPFae; }

Step 4: Draw Our Content


So far, our methods have been very simple. Now though, were going to get into some larger and slightly
mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/ 6/10

9/18/12

Generating PDF Documents

more complex code.

Creating Our Drawing Methods


What we want to do now is draw our desired content to our new PDF page. The three elements that well be adding to our page are: 1. text 2. lines (or solid boxes) 3. images As you might imagine, well be creating new methods for each of these elements. Beneath our beginPDFPage method, add the following three methods: 1 2 3

(Getadet(Stig)etwtFae(GetfaefnSz:fot CRc)dTx:NSrn*txihrm:CRc)rmotie(la (Getadieihrm:CRc)rmihoo:UClr)oo CRc)dLnWtFae(GetfaewtClr(Ioo*clr{ (Getadmg:UIae)mgton:CPitpit{} CRc)dIae(Img*iaeaPit(Gon)on

Youll notice that each of these methods is returning a CGRect- this is so that we know where the elements frame is in our document, so that we dont accidentally draw over something. Lets start with text. First, we want to set our font. We are accepting a float for our font size in our addText:withFrame:fontSize: call, so we can easily create our font with this line:
UFn *ot=[IotsseFnOSz:otie; Iot fn UFn ytmotfiefnSz]

Next, well calculate the size of our string to ensure that we dont spill text off the page. Well also set our line to wrap after words (as opposed to wrapping between characters, etc.). 1 2 3 4 5 6

CSztigie=[etszWtFn:otcntandoieCSzMk(p GiesrnSztxieihotfnosrieTSz:Gieae_ fottxWdh=faesz.it; laetitrm.iewdh itxWdh<srnSz.it) f(etittigiewdh txWdh=srnSz.it; etittigiewdh itxWdh>_aeiewdh f(etitpgSz.it) txWdh=_aeiewdhfaeoii.; etitpgSz.itrm.rgnx

Then, well build a frame for our text, and actually draw it to our page. 1 2 3 4 5 6

CRcedrnRcGetaefaeoii.,faeoii.,txWdh Getrneiget=CRcMk(rm.rgnxrm.rgnyetit [etdaIRc:edrnRc txrwnetrneiget wtFn:ot ihotfn ieraMd:IieraMdWrWa lnBekoeULnBekoeodrp lgmn:IetlgmnLf] ainetUTxAinetet; fae=CRcMk(rm.rgnxrm.rgnyetit,srnSz.e rmGetaefaeoii.,faeoii.,txWdhtigieh

And finally, well return the CGRect frame variable to our calling method.
rtr fae eun rm;
mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/ 7/10

9/18/12

Generating PDF Documents

And thats it for text. Now for lines In our addLineWithFrame:withColor method, we will pass a UIColor to set the color of our line. In our addLine method, we start by getting our current context, and then well set the color for drawing. 1 2 CCneteurnCnet=UGahcGturnCnet) GotxRfcretotxIrpiseCretotx(; CCneteSrkClrihoo(urnCnetoo.Goo) GotxSttoeooWtClrcretotx,clrCClr;

With our addLine: method, we are also accepting a CGRect with the coordinates for where to start our line (x,y), how long it will go (width), and how thick it will be (height). With these coordinates, we can set the line in place: 1 2 3 4

/hsihhcnsfteln /tistetikesohie CCneteLnWdhcretotx,faesz.egt; GotxStieit(urnCnetrm.iehih) CPitsatonrm.rgn GontrPit=faeoii; CPitedonGonMk(rm.rgnx+faesz.it,faeoi GonnPit=CPitaefaeoii.rm.iewdhrm.r

And now, well do the actual drawing to our context: 1 2 3 4 5 CCneteiPt(urnCnet; GotxBgnahcretotx) CCnetoeoon(urnCnettrPitxtrPity; GotxMvTPitcretotx,saton.,saton.) CCnetdLnTPitcretotx,edon.,edon.) GotxAdieoon(urnCnetnPitxnPity; CCnetlsPt(urnCnet; GotxCoeahcretotx) CCnetrwahcretotx,kGahiltoe; GotxDaPt(urnCnetCPtFlSrk)

And, of course, we finish by returning our lines frame to the calling method:
rtr fae eun rm;

Lets add an image. Our addImage: method is really simple- we just take our UIImage and draw it at the appropriate place on the page: 1 2

CRcmgFae=CRcMk(on.,pitymg.iewdhmg.i GetiaermGetaepitxon.,iaesz.it,iaes [mgrwnetiaerm] iaedaIRc:mgFae;

And then we return our frame:


rtr iaerm; eun mgFae

Notice that in each of these methods, were just drawing to the PDF by either calling drawInRect:, or by drawing directly to our context, as in CGContextDrawPath. At that point, were taking the elements that we created and were actually putting them on the page.

Calling Our Drawing Methods


Well call all of our drawing methods from the didClickMakePDF method, just beneath the call to beginPDFPage. Remember that were returning the CGRect frames for each of our elements, so well be
mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/ 8/10

9/18/12

Generating PDF Documents

saving those into variables as we call them, and then using them to position our next element. Starting with the text: 1 2

CRcetet=[efadet@Tissmietxeeo'og GettxRcsldTx:"hsioencethr,dntyua wtFaeCRcMk(PdigPdig0,20 ihrm:Getaekadn,kadn,400

This will appear 20 points from the top and 20 points from the left, as indicated by the kPadding constant that we set in step 1. So far, so good. Now, well take the frame textRect from our text element, and use it to position a blue line. 1 2

CRcleieet=[efadieihrm:Getaekadn,txRc. GetbuLnRcsldLnWtFaeCRcMk(Pdigetet ihoo:UClrbuClr] wtClr[Iooleoo];

Next, well create a UIImage using the tree.jpg image that we added back during set-up. Then, well draw that image to our PDF by calling our addImage: method. Notice that we are now using the blueLineRect frame to position our UIImage. 1 2 3

UIae*nmgUIaeiaeae:"rejg] ImgaIae=[ImgmgNmd@te.p"; CRcmgRcsldIaeaIae Getiaeet=[efadmg:nmg ton:GonMk(_aeiewdh2aIae aPitCPitae(pgSz.it/)(nmg

And finally, we can add another line to help set apart the image on our page. Well make this line red and, since we arent positioning any elements after it, we dont need to store its frame. 1 2

[efadieihrm:Getaekadn,iaeetoii.mgRc. sldLnWtFaeCRcMk(PdigmgRc.rgny+iaeet wtClr[IooeClr] ihoo:UClrrdoo];

Step 5: Finish Our Document


Now that our elements have been drawn to our PDF context, we need to end that context, which will close our PDF file. Well create another method to do this called finishPDF. 1 2 3 (odfnsPF{ vi)iihD UGahcEdDCnet) IrpisnPFotx(; }

We will then call [self finishPDF] at the bottom of our didClickMakePDF method.
[effnsPF; sl iihD]

Step 6: View Our Document


All we have to do to view our PDF document now, is go back to the didClickOpenPDF method that we created in the last tutorial, and modify it to open our new PDF- NewPDF.pdf in my case. To do this, well have to change most of the method, since we are now working with the documents directory to find the file and load it, so go ahead and replace the current didClickOpenPDF with the following:
mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/ 9/10

9/18/12

Generating PDF Documents

1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6

(BcinddlcOePF{ IAto)iCikpnD NAry*ahSerhahoDrcoisnoan(SirrDrco Srapts=NSacPtFrietreIDmisNLbayietr NSrndcmnsietrptsojcAIdx0; Stig*ouetDrcoy=[ahbettne:] NSrnpfah=[ouetDrcoysrnBApnigahopnn Stig*dPtdcmnsietrtigypednPtCmoet i([SieaaeealMngriexsstahpfah){ f[NFlMngrdfutaae]flEitAPt:dPt] RaeDcmndcmnRaeDcmnihouetieahp edrouet*ouet=[edrouetwtDcmnFlPt:d idcmn=nl f(ouet!i) { RaeVeCnrleraeVeCnrle[edriwot edriwotolr*edriwotolr=[RaeVeCnr raeVeCnrle.eeae=sl; edriwotolrdlgtef raeVeCnrle.oaTastoSye=UMdlrniin edriwotolrmdlrniintlIoaTastoS raeVeCnrle.oaPeettoSye=UMdlrsna edriwotolrmdlrsnaintlIoaPeett [efpeetoaVeCnrle:edriwotolraiae slrsnMdliwotolrraeVeCnrlenmtd } } }

Now, when you run your App, tap once on the Make PDF button, and then tap on the Open PDF button, and you should see your new PDF. Then, you can email it, print it, or close it.

Conclusion
There are many more things that can be drawn into the graphics context, but with a little bit of tinkering and the Apple docs ready-at-hand, its short work to make fantastic PDFs for your specific needs.
Like 1 person likes this. Sign Up to see what your friends like.

Tags: iOS SDKiPhone SDKPDF

By C.A. Beninati
As a free-time fiction writer and full-time iOS developer, C. A. Beninati might best be described as an artistic fusion of writing fury and iOS passion. His background is in web development, but that has shifted focus more recently to iOS projects.

mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/

10/10

You might also like