iOS 多张图片或单张生成pdf

1,999 阅读2分钟

一、效果图

如果所示的pdf是多张图片生成的pdf调用系统的分享,分享到微信打开,图片的大小可以自定义

二、核心代码以及逻辑(多图)

代码上有些项目的东西,使用的时候稍微改改就可以使用,改动不多

1.核心

多图绘制成pdf,并获取文件路径

#pragma mark - 创建PDF
- (NSString *)createPDF {
    //生成pdf路径
    NSString *pdfPath = [self createPDFPathWithName:[NSString stringWithFormat:@"%@.pdf",[self getTimeString]]];;
    // CGRectZero 表示默认尺寸,参数可修改,设置自己需要的尺寸
    UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, NULL);
    CGRect  pdfBounds = UIGraphicsGetPDFContextBounds();
    CGFloat pdfWidth  = pdfBounds.size.width;
    CGFloat pdfHeight = pdfBounds.size.height;

  //获取多张图片
    NSMutableArray *images = [NSMutableArray new];
    for (NSInteger i = 0; i < self.boardDatasource.count; i ++ ) {
        XWDrawingBoard *boardView = self.boardDatasource[i];
        [images addObject:boardView.getCurrentImage];
    }

    //遍历绘制
    [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) {
        // 绘制PDF
        UIGraphicsBeginPDFPage();

        CGFloat imageW = image.size.width;
        CGFloat imageH = image.size.height;

        if (imageW <= pdfWidth && imageH <= pdfHeight) {
            CGFloat originX = (pdfWidth - imageW) / 2;
            CGFloat originY = (pdfHeight - imageH) / 2;
            [image drawInRect:CGRectMake(originX, originY, imageW, imageH)];
        } else {
            CGFloat width,height;
            if ((imageW / imageH) > (pdfWidth / pdfHeight))
            {
                width  = pdfWidth;
                height = width * imageH / imageW;
            } else {
                height = pdfHeight;
                width = height * imageW / imageH;
            }
            [image drawInRect:CGRectMake((pdfWidth - width) / 2, (pdfHeight - height) / 2, width, height)];
        }
    }];
    UIGraphicsEndPDFContext();
    return pdfPath;
}

2.创建pdf存储路径

- (NSString *)createPDFPathWithName:(NSString *)pdfName {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString * finderPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
                                                                  NSUserDomainMask, YES) lastObject]
                             stringByAppendingPathComponent:@"PDF"];
    if (![fileManager fileExistsAtPath:finderPath])
    {
        [fileManager createDirectoryAtPath:finderPath withIntermediateDirectories:YES
                                attributes:nil
                                     error:NULL];
    }
    return [finderPath stringByAppendingPathComponent:pdfName];
}

3.图片昵称(用时间命名)

- (NSString *)getTimeString {
    NSDateFormatter  *dateformatter = nil;
    if (!dateformatter) {
        dateformatter = [[NSDateFormatter alloc] init];
    }
    [dateformatter setDateFormat:@"YYYYMMddHHmmssSSS"];
    return [dateformatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
}

三、调用系统分享pdf代码

使用 UIActivityViewController 分享pdf

1、分享文件类

- (void)shareFile {
    NSString *filePath = [self createPDF];
    if (!filePath) { //防止filePath导致崩溃
        return;
    }
    NSURL *file = [NSURL fileURLWithPath:filePath];

    NSArray *activityItems = @[file];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];
     // 分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            YMLog(@"completed");
            //分享 成功
        } else {
            YMLog(@"cancled");
            //分享 取消
        }
    };
}

2、分享图文类

- (void)shareImageTextUrl {
    //分享的标题
//    NSString *textToShare = @"分享的标题。";
    //分享的图片
    UIImage *imageToShare = [self.drawBoard getCurrentImage];
    //分享的url
//    NSURL *urlToShare = [NSURL URLWithString:@"http://www.baidu.com"];
    //分享图片 就把图片添加进去 文字
    NSArray *activityItems = @[imageToShare];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];
     // 分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            YMLog(@"completed");
            //分享 成功
        } else {
            YMLog(@"cancled");
            //分享 取消
        }
    };
}

四、单张图片生成pdf

单张图片生成pdf,其实就是将上述的循环内部的代码拿出来,如下:

- (NSString *)createPDF {
    NSString *pdfPath = [self createPDFPathWithName:[NSString stringWithFormat:@"%@.pdf",[self getTimeString]]];
    // CGRectZero 表示默认尺寸,参数可修改,设置自己需要的尺寸
    UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, NULL);
    CGRect  pdfBounds = UIGraphicsGetPDFContextBounds();
    CGFloat pdfWidth  = pdfBounds.size.width;
    CGFloat pdfHeight = pdfBounds.size.height;
    //获取图片
    UIImage *image = self.drawImage.image;
    // 绘制PDF
    UIGraphicsBeginPDFPage();
    CGFloat imageW = image.size.width;
    CGFloat imageH = image.size.height;

    if (imageW <= pdfWidth && imageH <= pdfHeight)
    {
        CGFloat originX = (pdfWidth - imageW) / 2;
        CGFloat originY = (pdfHeight - imageH) / 2;
        [image drawInRect:CGRectMake(originX, originY, imageW, imageH)];
    } else {
        CGFloat width,height;
        if ((imageW / imageH) > (pdfWidth / pdfHeight))
        {
            width  = pdfWidth;
            height = width * imageH / imageW;
        } else {
            height = pdfHeight;
            width = height * imageW / imageH;
        }
        [image drawInRect:CGRectMake((pdfWidth - width) / 2, (pdfHeight - height) / 2, width, height)];
    }
    UIGraphicsEndPDFContext();
    return pdfPath;
}