流程:设置PDF保存路径->将图片转成PDF并存放到设置好的路径->将生成好的PDF转Data使用原生分享功能分享出去。
1、设置PDF保存路径
#pragma mark - 创建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];
}
2、生成PDF
#pragma mark - 创建PDF
- (NSString *)createPDF {
NSString * pdfPath = [self createPDFPathWithName:@"test.pdf"];
// CGRectZero 表示默认尺寸,参数可修改,设置自己需要的尺寸
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, NULL);
CGRect pdfBounds = UIGraphicsGetPDFContextBounds();
CGFloat pdfWidth = pdfBounds.size.width;
CGFloat pdfHeight = pdfBounds.size.height;
[self.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;
}
3、分享
#pragma mark - 分享
- (void)shareClick {
NSString * path = [self createPDF];
NSURL * file = [NSURL fileURLWithPath:path];
NSData * data = [NSData dataWithContentsOfFile:path];
UIActivityViewController * activity = [[UIActivityViewController alloc]initWithActivityItems:@[data,file]
applicationActivities:nil];
[self presentViewController:activity animated:YES completion:nil];
}
4、demo地址:demo
5、效果图
图一
图二
网友评论