2010年11月18日 星期四

《親子王下載工具》製作方法(三)

取得 PictureLayer 及 TextLayer 圖片後,要做的是把它們合併,放進 PDF Context 並且建立 PDF 檔。一本《親子王》共有 76 頁,所以要下載 76 次。
- (void)download:(unsigned int)year month:(Byte)month day:(Byte)day  {
UIImage *pictureImage, *textImage, *finalImage;
NSString *string, *api, *filename;
BOOL contextCreated = NO;
NSData *data;
Byte page;

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableData *pdfData = [NSMutableData data];

for (page=1; page<=76; page++) {
NSLog(@"[download] Processing page %d...", page);
pictureImage = nil;
textImage = nil;

// Get text layer image
api = [NSString stringWithFormat:NETWORK_API_TEXT, year, month, day, page];
string = [NSString stringWithFormat:@"%@%@", NETWORK_SERVER, api];
data = [SmartParentsDownloaderViewController getDataFromFullURL:string];
if ([data length] > 10) {
textImage = [UIImage imageWithData:data];
}

// Get picture layer image
api = [NSString stringWithFormat:NETWORK_API_PICTURE, year, month, day, page];
string = [NSString stringWithFormat:@"%@%@", NETWORK_SERVER, api];
data = [SmartParentsDownloaderViewController getDataFromFullURL:string];
if ([data length] <= 10) {continue;}

pictureImage = [UIImage imageWithData:data];

if (contextCreated == NO) {
contextCreated = YES;
CGRect rect = CGRectMake(0, 0, pictureImage.size.width, pictureImage.size.height);
UIGraphicsBeginPDFContextToData(pdfData, rect, nil);
}

// Merge two uiimage
if (textImage != nil) {
UIGraphicsBeginImageContext(pictureImage.size);
[pictureImage drawAtPoint:CGPointZero];
[textImage drawAtPoint:CGPointZero];
finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
} else {
finalImage = pictureImage;
}

UIGraphicsBeginPDFPage();
[finalImage drawAtPoint:CGPointZero];
}

if (contextCreated == NO) {return;}

UIGraphicsEndPDFContext();

filename = [NSString stringWithFormat:@"SmartParents_%04d_%02d_%02d.pdf", year, month, day];
string = [SmartParentsDownloaderViewController getDocumentFilePath:filename];
[pdfData writeToFile:string atomically:YES];

[pool release];
}