问题
最近有个场景,需要把H5传递过来的base64保存为PDF文件,经解析,H5是直接把png转base64,保存下来的文件就算是重命名为【xxx.pdf】,依然还是没法在【文件.app】中打开,只能把base64转成UIImage,再通过绘制PDF来进行保存
解决方案
- 先把base64Str转成UIImage
UIImage * imgForBase64 = [UIImage imageFromBase64ToWithStr:self.base64Data]; /// base64str->Image + (UIImage *)imageFromBase64ToWithStr:(NSString *)str{ NSString *base64Str = [str copy]; if ([base64Str containsString:@"data:image/jpeg;base64,"]) { base64Str = [base64Str stringByReplacingOccurrencesOfString:@"data:image/jpeg;base64," withString:@""]; }else if ([base64Str containsString:@"data:image/png;base64,"]) { base64Str = [base64Str stringByReplacingOccurrencesOfString:@"data:image/png;base64," withString:@""]; } if (kStringIsEmpty(base64Str)) { return nil; } NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:base64Str options:NSDataBase64DecodingIgnoreUnknownCharacters]; UIImage *image = [[UIImage alloc]initWithData:decodeData]; return image; }
- 创建文件名和保存目录
///文件夹根目录 NSString * localFileDirectory = [PATH_OF_DOCUMENT stringByAppendingPathComponent:@"/PDF"]; NSFileManager *fileManger = [NSFileManager defaultManager]; // 创建文件夹目录 if (![[NSFileManager defaultManager] contentsOfDirectoryAtPath:localFileDirectory error:nil]) { [fileManger createDirectoryAtPath:localFileDirectory withIntermediateDirectories:YES attributes:nil error:nil]; } // 创建文件路径 NSString *fileNamePath = [localFileDirectory stringByAppendingPathComponent:self.fileName];
- 开始绘制PDF
// 绘制PDF CGRect frame = CGRectMake(0, 0, imgForBase64.size.width, imgForBase64.size.height); // Create the PDF context using the default page size of 612 x 792. UIGraphicsBeginPDFContextToFile(fileNamePath, CGRectZero, nil); // Mark the beginning of a new page. UIGraphicsBeginPDFPageWithInfo(frame, nil); [imgForBase64 drawInRect:frame]; // Close the PDF context and write the contents out. UIGraphicsEndPDFContext();
- 输出保存目录【fileNamePath】