Thursday, October 15, 2009

Instant Cocoa: Checkbook project 8

Exporting a csv file, printing

Any respectable document-based application should allow the user to print. Just for fun, I added a toolbar (as described briefly here) and put in a print toolbar item. It turns out to be hooked up automatically. You just have to implement the function below in MyDocument. The current version doesn't handle page setup properly---I'll have to explore that further. The dictionary we get passed is empty.

The other code listing is to export a CSV (comma separated values) file, that could be imported into a spreadsheet. This is just like a standard file save for a non-document based application. It uses a block as the "completionHandler," which I also discussed briefly the other day.

- (NSPrintOperation *)printOperationWithSettings:
(NSDictionary *)printSettings
error:(NSError **)outError {
NSLog(@"print %@", printSettings);
NSLog(@"window %@", [window contentView]);
NSLog(@"content view %@",
[[window contentView] subviews]);
NSLog(@"myScrollView subview %@ %@",
scrollView, [scrollView subviews]);
NSLog(@"myTV %@", myTV);

NSMutableDictionary *printAttrs;
printAttrs = [NSMutableDictionary
NSPrintInfo *pInfo;
pInfo = [[NSPrintInfo alloc]
[pInfo setOrientation:NSPortraitOrientation];
[pInfo setJobDisposition:NSPrintPreviewJob];
[pInfo setHorizontalPagination:NSFitPagination];
[pInfo setVerticallyCentered:NO];
[pInfo setTopMargin:90];
return [NSPrintOperation

- (IBAction)exportCSV:(id)sender{
NSLog(@"getFileToSave %@",[sender description]);
NSSavePanel *savePanel = [NSSavePanel savePanel];
[savePanel setRequiredFileType:@"csv"];

[savePanel beginSheetModalForWindow:[NSApp mainWindow]
completionHandler:^(NSInteger result) {
if (result == NSOKButton) {
[savePanel orderOut:self];
[self application:NSApp
saveCSVFile:[savePanel filename]];

- (BOOL)application:(NSApplication *)app
saveCSVFile:(NSString *)fn {
theData = [myDocument checkbookItemsArray];
[theData retain];
//thePrefs = [myUISettings settings];
//[thePrefs retain];
mA = [NSMutableArray arrayWithCapacity:50];
for (cbi in theData) {
lineArray = [NSMutableArray arrayWithCapacity:5];

date = [cbi date];
NSLog(@"%@", [date description]);

dateParts = [[date description]
componentsSeparatedByString:@" "];
s = [dateParts objectAtIndex:0];
NSLog(@"%@", s);
[lineArray addObject:s];
[lineArray addObject:@","];

isDeposit = [[cbi isDeposit] boolValue];
if (isDeposit) {
[lineArray addObject:@" "];
else {
[lineArray addObject:[cbi checkNumber]];
[lineArray addObject:@","];
[lineArray addObject:[cbi name]];
[lineArray addObject:@","];
[lineArray addObject:@"\n"];
line = [lineArray componentsJoinedByString:@""];
[mA addObject:line];
entry = [mA componentsJoinedByString:@""];
NSLog(@"now, do the save %@", entry);

NSError **e;
[entry writeToFile:fn atomically:YES
encoding:NSASCIIStringEncoding error:e];

[theData release];
//[thePrefs release];
return YES;

No comments: