iOS PDF与各种格式文件转换

目录

  • 各种格式文件转PDF
  • 多张图片转PDF
  • UIWebView转图片

Snip20170630_2.png

各种格式文件转PDF

webView2PDF.gif

其实就是用UIWebView去加载文件,然后通过UIPrintPageRendererUIGraphicsBeginPDFContextToData配合使用将UIWebview上显示的内容生成PDF文件。给UIWebView添加一个分类,在分类里面添加以下方法:

- (NSData *)convert2PDFData{

//    返回视图的打印格式化
    UIViewPrintFormatter *format = [self viewPrintFormatter];
    UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
    [render addPrintFormatter:format startingAtPageAtIndex:0];

    // 设置PDF文件每页的尺寸
    CGRect pageRect =  CGRectMake(0, 0, 600, 768);
//    呈现每个页面的上下文的尺寸大小
    CGRect printableRect = CGRectInset(pageRect, 50, 50);

    [render setValue:[NSValue valueWithCGRect:pageRect] forKey:@"paperRect"];
    [render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];

    NSMutableData *pdfData = [NSMutableData data];
    //    文档信息 可设置为nil
    //    CFMutableDictionaryRef myDictionary = CFDictionaryCreateMutable(nil, 0,
    //                                             &kCFTypeDictionaryKeyCallBacks,
    //                                             &kCFTypeDictionaryValueCallBacks);

    //    CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("My PDF File"));
    //    CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name"));

    UIGraphicsBeginPDFContextToData(pdfData, pageRect, NULL);

    for (NSInteger i = 0; i < [render numberOfPages]; i++) {

        UIGraphicsBeginPDFPage();
        CGRect bounds = UIGraphicsGetPDFContextBounds();
        [render drawPageAtIndex:i inRect:bounds];
    }

    UIGraphicsEndPDFContext();

    return pdfData;

}

多张图片转PDF

images2PDF.gif

在UIWebview加载单张图片,通过上述方法也是能将图片转成PDF文件的,但如果是多张图片要通过UIWebview来实现比较麻烦。苹果在UIGraphics.h给我们提供了一个绘制PDF的方法:UIKIT_EXTERN BOOL UIGraphicsBeginPDFContextToFile(NSString *path, CGRect bounds, NSDictionary * __nullable documentInfo) NS_AVAILABLE_IOS(3_2);

- path:文件保存路径
- bounds:设置PDF每页的宽高,设置CGRectZero为默认值( 612 by 792 points)
- documentInfo :设置文档的额外信息,比如文档作者和密码这样的信息,可以为nil。

为了PDF显示效果,我将PDF的size设置成默认Size,而且一张图片作为PDF的一页并且居中显示,但是这个时候你不能保证每张图片尺寸一样。因为如果image Size如果大于PDF Size,这样转换后的PDF就不能正常显示了,所以我需要判断每张图片的的实际大小,根据图片的宽高比去对原图片进行缩放。

具体实现如下:

+ (BOOL)convertPDFWithImages:(NSArray<UIImage *>*)images fileName:(NSString *)fileName{

    if (!images || images.count == 0) return NO;

    // pdf文件存储路径
    NSString *pdfPath = [self saveDirectory:fileName];
    NSLog(@"****************文件路径:%@*******************",pdfPath);

    BOOL result = UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, NULL);

    // pdf每一页的尺寸大小

    CGRect pdfBounds = UIGraphicsGetPDFContextBounds();
    CGFloat pdfWidth = pdfBounds.size.width;
    CGFloat pdfHeight = pdfBounds.size.height;

    NSLog(@"%@",NSStringFromCGRect(pdfBounds));

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

        // 获取每张图片的实际长宽
        CGFloat imageW = image.size.width;
        CGFloat imageH = image.size.height;
//        CGRect imageBounds = CGRectMake(0, 0, imageW, imageH);
//        NSLog(@"%@",NSStringFromCGRect(imageBounds));

        // 每张图片居中显示
        // 如果图片宽高都小于PDF宽高
        if (imageW <= pdfWidth && imageH <= pdfHeight) {

            CGFloat originX = (pdfWidth - imageW) * 0.5;
            CGFloat originY = (pdfHeight - imageH) * 0.5;
            [image drawInRect:CGRectMake(originX, originY, imageW, imageH)];

        }
        else{
            CGFloat w,h; // 先声明缩放之后的宽高
//            图片宽高比大于PDF
            if ((imageW / imageH) > (pdfWidth / pdfHeight)){
                w = pdfWidth - 20;
                h = w * imageH / imageW;

            }else{
//             图片高宽比大于PDF
                h = pdfHeight - 20;
                w = h * imageW / imageH;
            }
            [image drawInRect:CGRectMake((pdfWidth - w) * 0.5, (pdfHeight - h) * 0.5, w, h)];
        }
    }];

    UIGraphicsEndPDFContext();

    return result;
}

UIWebView转图片

webView2image.gif
在项目里经常需要用到WebView去展示各种页面,然后需要把整个页面的内容转为图片转发出去,简书里也有这个功能。具体实现步骤如下:

  • 将 UIWebView 分屏截取,然后将截取的图片拼接成一张图片
  • 将 UIWebView 从头,contentOffset = (0, 0),开始截取webView.bounds.size.height高度的图片
  • 然后将 webView 可见区域下移继续截屏,这样将所有截取的图片按照顺序拼接,就能得到整个 UIWebView 显示内容的完整图片。

实现代码如下:

CGSize boundsSize = self.bounds.size;
    CGFloat boundsWidth = self.bounds.size.width;
    CGFloat boundsHeight = self.bounds.size.height;
    CGPoint offset = self.scrollView.contentOffset;

    [self.scrollView setContentOffset:CGPointMake(0, 0)];

    CGFloat contentHeight = self.scrollView.contentSize.height;
    NSMutableArray *images = [NSMutableArray array];

    while (contentHeight > 0) {
        UIGraphicsBeginImageContext(boundsSize);

        [self.layer renderInContext:UIGraphicsGetCurrentContext()];

        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        [images addObject:image];

        CGFloat offsetY = self.scrollView.contentOffset.y;

        [self.scrollView setContentOffset:CGPointMake(0, offsetY + boundsHeight)];

        contentHeight -= boundsHeight;
    }

    [self.scrollView setContentOffset:offset];

    UIGraphicsBeginImageContext(self.scrollView.contentSize);

    [images enumerateObjectsUsingBlock:^(UIImage *image, NSUInteger idx, BOOL *stop) {
        [image drawInRect:CGRectMake(0, boundsHeight * idx, boundsWidth, boundsHeight)];
    }];

    UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return fullImage;

老规矩还是在文章末尾奉上本文Demo地址

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值