The problem

Recently, there was a scene where it was necessary to save base64 transferred from H5 as A PDF file. After analysis, H5 directly converted PNG to Base64. Even if the saved file was renamed as [xxx.pdf], it still could not be opened in [file.app], and only UIImage could be converted from Base64. Then save it by drawing PDF

The solution

  1. So let’s turn base64Str into 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; }Copy the code
  1. Create a file name and save directory
/ / / folder to the root directory nsstrings * localFileDirectory = [PATH_OF_DOCUMENT stringByAppendingPathComponent: @ "/ PDF"]. NSFileManager *fileManger = [NSFileManager defaultManager]; // Create folder directory if (! [[NSFileManager defaultManager] contentsOfDirectoryAtPath:localFileDirectory error:nil]) { [fileManger createDirectoryAtPath:localFileDirectory withIntermediateDirectories:YES attributes:nil error:nil]; } / / create the file path nsstrings * fileNamePath = [localFileDirectory stringByAppendingPathComponent: self. The fileName];Copy the code
  1. Start drawing PDF
CGRect frame = CGRectMake(0, 0, imgForBase64.sie.width, imgForBase64.sie.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();Copy the code
  1. Output save directory fileNamePath