How can I programmatically generate a thumbnail of a PDF with iOS?

后端 未结 4 900
执笔经年
执笔经年 2020-12-28 09:24

We\'re displaying PDF content using UIWebViews at the moment. Ideally I would like to be able to display thumbnails in the UITableView without loa

4条回答
  •  没有蜡笔的小新
    2020-12-28 09:47

    Here is sample code considering transformation. :)

    NSURL* pdfFileUrl = [NSURL fileURLWithPath:finalPath];
    CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfFileUrl);
    CGPDFPageRef page;
    
    CGRect aRect = CGRectMake(0, 0, 70, 100); // thumbnail size
    UIGraphicsBeginImageContext(aRect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIImage* thumbnailImage;
    
    
    NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(pdf);
    
    for(int i = 0; i < totalNum; i++ ) {
    
    
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, 0.0, aRect.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
    
        CGContextSetGrayFillColor(context, 1.0, 1.0);
        CGContextFillRect(context, aRect);
    
    
        // Grab the first PDF page
        page = CGPDFDocumentGetPage(pdf, i + 1);
        CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, aRect, 0, true);
        // And apply the transform.
        CGContextConcatCTM(context, pdfTransform);
    
        CGContextDrawPDFPage(context, page);
    
        // Create the new UIImage from the context
        thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
    
        //Use thumbnailImage (e.g. drawing, saving it to a file, etc)
    
        CGContextRestoreGState(context);
    
    }
    
    
    UIGraphicsEndImageContext();    
    CGPDFDocumentRelease(pdf);
    

提交回复
热议问题