How to generate thumbnails from a PDF document with iPhone SDK?

后端 未结 6 974
予麋鹿
予麋鹿 2020-12-24 08:46

I have read the Apple PDF documentation with Quartz.

But I do not know how to generate the thumbnails from a PDF document...

Any idea/sample code ?

6条回答
  •  一向
    一向 (楼主)
    2020-12-24 09:16

    In the meantime I have created a library which does support PDF, Images and Videos for creating thumbnails. Maybe someone else can use it:

    https://github.com/prine/ROThumbnailGenerator

    Solution in Swift. Just pass the NSURL to the PDF and the page number you want to retrieve as UIImage:

    func getThumbnail(url:NSURL, pageNumber:Int) -> UIImage {
    
        var pdf:CGPDFDocumentRef = CGPDFDocumentCreateWithURL(url as CFURLRef);
    
        var firstPage = CGPDFDocumentGetPage(pdf, pageNumber)
    
        // Change the width of the thumbnail here
        var width:CGFloat = 240.0;
    
        var pageRect:CGRect = CGPDFPageGetBoxRect(firstPage, kCGPDFMediaBox);
        var pdfScale:CGFloat = width/pageRect.size.width;
        pageRect.size = CGSizeMake(pageRect.size.width*pdfScale, pageRect.size.height*pdfScale);
        pageRect.origin = CGPointZero;
    
        UIGraphicsBeginImageContext(pageRect.size);
    
        var context:CGContextRef = UIGraphicsGetCurrentContext();
    
        // White BG
        CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
        CGContextFillRect(context,pageRect);
    
        CGContextSaveGState(context);
    
        // ***********
        // Next 3 lines makes the rotations so that the page look in the right direction
        // ***********
        CGContextTranslateCTM(context, 0.0, pageRect.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(firstPage, kCGPDFMediaBox, pageRect, 0, true));
    
        CGContextDrawPDFPage(context, firstPage);
        CGContextRestoreGState(context);
    
        var thm:UIImage = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();
        return thm;
    }
    

提交回复
热议问题