Professional Documents
Culture Documents
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
mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/
2/10
9/18/12
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
mobile.tutsplus.com/tutorials/iphone/generatingpdfdocuments/
4/10
9/18/12
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.
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.
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
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
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]
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; }
9/18/12
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
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
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
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.
9/18/12
saving those into variables as we call them, and then using them to position our next element. Starting with the text: 1 2
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
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
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
We will then call [self finishPDF] at the bottom of our didClickMakePDF method.
[effnsPF; sl iihD]
9/18/12
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.
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