19
Adding Document Generation to iPad Apps in 30 Minutes Using the Docmosis Cloud iOS SDK Introduction This tutorial demonstrates how to add document generation to an iPad app using Docmosis. We will extend the Xcode application-template called 'Master Detail Application' and add a print button to generate a PDF containing data from the tutorial app. This PDF is then displayed on the iPad. There are 6 main steps and it takes about 30 minutes to run through: 1. Create a new Xcode project ........................................................... 2 2. Add the print button on the user interface. ..................................... 6 3. Add the Docmosis SDK. ................................................................. 8 4. Generate the document (pdf) ......................................................... 9 5. Display the document (pdf) ........................................................... 14 6. Run the Xcode Project .................................................................. 17 You Need To get started, you require: an iOS development environment (this example is created using Xcode4.2.1) a Docmosis Cloud account. You can sign up for a free 1 month trial here: https://www.docmosis.com/accounts/register the Docmosis iOS SDK which can be downloaded here: http://www.docmosis.com/content/ipad-developer-page Copyright Docmosis 2013 January 2013 1 of 19

Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Adding Document Generation to iPad Apps in 30 MinutesUsing the Docmosis Cloud iOS SDK

Introduction

This tutorial demonstrates how to add document generation to an iPad app using Docmosis.

We will extend the Xcode application-template called 'Master Detail Application' and add a print button to generate a PDF containing data from the tutorial app. This PDF is then displayed on the iPad.

There are 6 main steps and it takes about 30 minutes to run through:

1. Create a new Xcode project ........................................................... 2 2. Add the print button on the user interface. ..................................... 6 3. Add the Docmosis SDK. ................................................................. 8 4. Generate the document (pdf) ......................................................... 9 5. Display the document (pdf) ........................................................... 14 6. Run the Xcode Project .................................................................. 17

You Need

To get started, you require:• an iOS development environment (this example is created using Xcode4.2.1)• a Docmosis Cloud account. You can sign up for a free 1 month trial here:

https://www.docmosis.com/accounts/register

• the Docmosis iOS SDK which can be downloaded here:http://www.docmosis.com/content/ipad-developer-page

Copyright Docmosis 2013 January 2013 1 of 19

Page 2: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

1. Create a new Xcode project

Start Xcode, create a new project and click 'Open'.

Choose Master-DetailSelect the 'Master-Detail Application' template for your new project as shown below and click 'Next':

The master detail application template creates an application which displays a popup where you can click the '+' button to insert time stamps into the display.

As shown on this page, this tutorial uses a red-box in screen shots to highlight the specific areas of interest.

Copyright Docmosis 2013 January 2013 2 of 19

Page 3: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family'. Ensure all tick-box options are selected as shown below and click 'Next'.

When prompted, select a directory to save your Xcode project file and click 'Create' (the 'Source Control' checkbox is selected by default).

Add the Quick Look Framework

We use the built-in Quick Look framework to handle the display of the PDF on our iPad. In the central area, scroll down the project's 'Summary' tab to the 'Linked Frameworks and Libraries' section:

There are other PDF viewer libraries that you can use instead of Quick Look providing different features and sometimes having better memory use.

Copyright Docmosis 2013 January 2013 3 of 19

Page 4: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Click '+', select 'QuickLook.framework' from the pull down list and click 'Add' to include it in the list of frameworks and libraries:

Turn On the ToolBar

Open the 'MainStoryboard.storyboard' file and select the 'Navigation Controller' within the 'Navigation Controller Scene':

Copyright Docmosis 2013 January 2013 4 of 19

Page 5: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Click the Attributes Inspector on the right hand side of the window, and then click the 'Shows Toolbar' checkbox so that it is selected. Your screen should look like this:

The bar at the bottom of the user interface is now visible. The print button, added to the user interface in the next step, will appear on this bar.

Set up of the project is now complete. The next section of the tutorial steps through adding the code to display the print button.

Copyright Docmosis 2013 January 2013 5 of 19

Page 6: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

2. Add the print button on the user interface.Select the 'MasterViewController.m' file and scroll down to locate the 'viewDidLoad' method:

Create the Print ButtonInsert the following code into the bottom of the 'viewDidLoad' method before the end bracket:

// create the print button which calls the printObject methodUIBarButtonItem *printButton = [[UIBarButtonItem alloc] initWithTitle:@"Print" style:UIBarButtonItemStyleDone target:self action:@selector(printObjects:)];// add it to the toolbarself.toolbarItems = [[NSArray alloc] initWithObjects:printButton, nil];

The code above simply creates a print button and adds it to the tool bar items. When the button is clicked it will call printObjects()

Copyright Docmosis 2013 January 2013 6 of 19

Page 7: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

So that it looks like this:

Create the Entry Point for the Print ButtonWhen the print button is pressed it will call the printObjects() method. To create the printObjects method:Copy the following code and insert it after the 'viewDidLoad' method:

- (void)printObjects:(id)sender{}

Your code will now look as follows:

At this point you can run the project and hit the 'Print' button, but it won't do anything yet

Copyright Docmosis 2013 January 2013 7 of 19

Page 8: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

3. Add the Docmosis SDK.Download the SDKTo download the Docmosis SDK go to http://www.docmosis.com/content/ipad-developer-page and download the SDK. It is a zip file containing two files::

libDocmosisRenderer.aDocmosisRenderer.h

Add the SDK files to the ProjectOpen the zip file and drag and drop the two files into your Xcode project and click 'Finish':

So that your screen looks like this:

The Docmosis SDK is now part of your project and we can now add the code to call Docmosis to create documents.

Copyright Docmosis 2013 January 2013 8 of 19

Page 9: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

4. Generate the document (pdf)Add the Header FileSelect the 'MasterViewController.h' file and select the following code:

Remove the selected code and replace it with the following code:

#import "DocmosisRenderer.h"

@interface MasterViewController : UITableViewController <DocmosisRendererDelegate, NSFetchedResultsControllerDelegate>

So that your screen looks like this:

Copyright Docmosis 2013 January 2013 9 of 19

Page 10: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Update the MasterView ImplementationSelect 'MasterViewController.m' file and replace the highlighted code

with the following code:

@implementation MasterViewController { DocmosisRenderer *_docmosis; // handle to Docmosis Renderer}

So that your screen looks like this:

Initialise The SDKWe now add the code to initialise the Docmosis renderer library. Insert the following code to the end of the 'viewDidLoad' method.

// now initialise the Docmosis Renderer_docmosis = [DocmosisRenderer newWithDelegate:self accessKey:@"XXXXXXXXXXXXXX"];

The XXXXXXXXXXXXXX is just a placeholder. It will be replaced by your Docmosis Cloud account access key

Copyright Docmosis 2013 January 2013 10 of 19

Page 11: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Your screen should look like this:

Insert Your Access KeyReplace the XXXXXXXXXXXXXX text with your own access key from your Docmosis Cloud account.If you don't know your access key, log in to the Docmosis site to pick it up: http://www.docmosis.com/accounts (under the Account Settings tab as shown below).

Now that we are using your access key, the Docmosis SDK will be able to see your templates and make requests on your behalf.

Copyright Docmosis 2013 January 2013 11 of 19

Page 12: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Implement the Print LogicThe next step is to make the printObjects method do something useful. Within the 'MasterViewController.m' file, replace the highlighted code:

With the following code:

- (void)printObjects:(id)sender{ // stored the fetched objects in an array NSArray *items = [self.fetchedResultsController fetchedObjects];

// convert the timestamps to dictionaries so we can create a JSON String out of them.

NSMutableArray *itemDictionaries = [[NSMutableArray alloc] initWithCapacity:[items count]]; NSEnumerator *e = [items objectEnumerator]; id item; while (item = [e nextObject]) { // each date has a "msg" : "timestamp description" dictionary [itemDictionaries addObject:[NSDictionary dictionaryWithObjectsAndKeys:[[item valueForKey:@"timeStamp"] description],@"msg", nil]]; } // create the full dictionary to convert to a JSON string NSDictionary *requestItemDict = [NSDictionary dictionaryWithObjectsAndKeys: [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterNoStyle], @"date", @"Master Detail Template With Docmosis",@"title", itemDictionaries,@"messages", nil];

NSError* error; NSData* jsonData = [NSJSONSerialization dataWithJSONObject:requestItemDict options:NSJSONWritingPrettyPrinted error:&error]; NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

// send the request to docmosis [_docmosis sendRequestWithData:jsonStr templateName: @"samples/WelcomeTemplate.doc" outputFormat:DocmosisOutputPDF requestId:@"samplePrint"];}

The above code implements the call to Docmosis to produce the PDF document. If you look closely, you can see key-value pairs being set (eg “date” set to the date. Herein lies the power of the Docmosis SDK.

Copyright Docmosis 2013 January 2013 12 of 19

Page 13: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

So your printObjects method now looks like this:

Collect the Generated DocumentNext we create the placeholder for the call back when the document is generated. Within the 'MasterViewController.m' file, insert the following code before @end:

#pragma mark - Docmosis Renderer delegate

-(void) documentGenerated:(DocmosisResponse *)response { NSLog(@"\nResponse Received\nSuccess : %@\nHTTP Status : %d\nShort Message : %@\nLong Message : %@\nRequest Id : %@\n" , ([response succeeded] ? @"Yes" : @"No"), [response httpStatus], [response shortMessage], [response longMessage], [response requestId]);}

So that your screen looks like this:

The Docmosis response can include generated documents or error messages. It is important to always check for errors and respond accordingly.

Copyright Docmosis 2013 January 2013 13 of 19

Page 14: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

5. Display the document (pdf)Include Quick Look in the HeaderSelect 'MasterViewController.h' and replace the highlighted declaration:

with the following code:

#import <QuickLook/QuickLook.h>

@interface MasterViewController : UITableViewController <DocmosisRendererDelegate, QLPreviewControllerDataSource,NSFetchedResultsControllerDelegate>

So that your screen looks like this:

Copyright Docmosis 2013 January 2013 14 of 19

Page 15: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Update the MasterViewControllerNow we create an iVar for storing the documents once they are produced (and to assist with the Quick Look framework). Select 'MasterViewController.m' and replace the following highlighted code:

With the following code:

@implementation MasterViewController {

// handle to Docmosis RendererDocmosisRenderer *_docmosis;

// contains rendered documents NSMutableArray *_documents;

}

So that it looks like this:

Copyright Docmosis 2013 January 2013 15 of 19

Page 16: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Implement the Display PDF CodeWe can now complete the documentGenerated method. Still within the 'MasterViewController.m' file, replace the following highlighted code:

with the following code:

-(void) documentGenerated:(DocmosisResponse *)response { NSLog(@"\nResponse Received\nSuccess : %@\nHTTP Status : %d\nShort Message : %@\nLong Message : %@\nRequest Id : %@\n", ([response succeeded] ? @"Yes" : @"No"), [response httpStatus], [response shortMessage], [response longMessage], [response requestId]); // we received a response from Docmosis - lets assume its all OK (normally the response code must be checked) if ([response succeeded] && [[response requestId] isEqualToString:@"samplePrint"]) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *appFile = [documentsDirectory stringByAppendingPathComponent :@"sample.pdf"]; NSData *document = [response data]; [document writeToFile:appFile atomically:YES]; _documents = [NSMutableArray arrayWithObject:appFile]; QLPreviewController *previewController = [[QLPreviewController alloc] init]; [previewController setDataSource:self]; // present the report modally [self presentViewController:previewController animated:YES completion:NULL]; }}

To look like this:

The code above displays the PDF in a modal dialog box.

Copyright Docmosis 2013 January 2013 16 of 19

Page 17: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Complete the Quick Look ImplementationWe must implement the required Quick Look data source methods to get the modal dialog to work. Still within the 'MasterViewController.m' file, insert the following code before @end:

#pragma mark - Quick look data source

-(NSInteger)numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller { if (_documents == nil) return 0; return [_documents count];}

-(id <QLPreviewItem>)previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index { if (_documents == nil || index >= [_documents count]) return nil; return [NSURL fileURLWithPath:[_documents objectAtIndex:index]];}

To look like this:

6. Run the Xcode Project

Finally it is time to run the project to see how it operates. To run the iPad simulator click on the 'Run' button.

The app will build and launch into the iOS Simulator. When you click the 'Master' button a popup is displayed as shown to the right.

The only visual difference to the default Master Detail Application is the print button bottom left which we have added during this tutorial.

Copyright Docmosis 2013 January 2013 17 of 19

Page 18: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

Click '+' button a few times. This will add some timestamps into your list. Your iPad simulator should look like this:

To generate the pdf document, click the blue 'Print' button. Your pdf document will display like this:

So what occurred when you clicked the Print button?Your app bundled up some data along with instructions including the document-template to use and that we want PDF output. It passed these to the Docmosis SDK which called the live Docmosis Cloud service to render the document. Specifically, it used the “samples/WelcomeTemplate.doc” template which is available by default in all cloud accounts. It passed the list of timestamps, a title and the date to be populated.

Copyright Docmosis 2013 January 2013 18 of 19

Page 19: Adding Document Generation to iPad Apps in 30 Minutes · Give your project a 'Product Name' and a 'Company Identifier'. Select iPad from the drop-down menu as the 'Device Family

The image below shows how the template relates to the document produced.

In the image above, you can see the place-holders for the title, date and messages (if you look again at the printObjects() method in the code, you'll see where values are being set). This template is a DOC format file and so is easily created, modified and copied. Docmosis also allows you to use ODT (Open Office) documents as templates too. Regardless of your template format, you can tell Docmosis to produce documents in a variety of formats including PDF, DOC, DOCX, ODT and RTF.

What now?Well, you now know how to add Docmosis capability to any iOS application. Here's some things you might like to try to see how Docmosis might work for your apps:

1) Create a different templateLog in to the Docmosis site (https://www.docmosis.com/accounts) and look at the templates tab. Download the template, modify it and upload it with a new name (eg myTemplate.doc). Change printObjects() to refer to your new template name instead.

2) Change the instruction in printObjects() to email you the PDF instead (or as well). You will need to examine the Render request in the Docmosis Cloud services API to understand many options available to the iOS SDK.

3) Change printObjects to stream back a PDF for display at the same time as emailing a Word version of the document4) Learn more about the Docmosis template features or the Cloud Services document delivery/storage options

There's quite a bit to explore. Hopefully this tutorial has given you a taste of what you can do with Docmosis to have your apps producing documentation in no time. Please contact us (mailto:[email protected]) if you have any questions or would like to provide feedback on this tutorial.

Wishing you success with your apps.The Docmosis Team.

Copyright Docmosis 2013 January 2013 19 of 19