前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >把UIImage转成PDF进行保存

把UIImage转成PDF进行保存

作者头像
freesan44
发布2022-04-02 09:21:15
5820
发布2022-04-02 09:21:15
举报
文章被收录于专栏:freesan44freesan44

问题

最近有个场景,需要把H5传递过来的base64保存为PDF文件,经解析,H5是直接把png转base64,保存下来的文件就算是重命名为【xxx.pdf】,依然还是没法在【文件.app】中打开,只能把base64转成UIImage,再通过绘制PDF来进行保存

解决方案

  1. 先把base64Str转成UIImage
代码语言:javascript
复制
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;
}
  1. 创建文件名和保存目录
代码语言:javascript
复制
///文件夹根目录
    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];
  1. 开始绘制PDF
代码语言:javascript
复制
 // 绘制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();
  1. 输出保存目录【fileNamePath】
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022.01.26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题
  • 解决方案
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档