Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 646
fvisticot Avatar asked Dec 21 '10 23:12

fvisticot


People also ask

What is the thumbnail of a PDF file?

Page thumbnails are miniature previews of the pages in a document. You can use page thumbnails to jump quickly to a selected page or to adjust the view of the page. When you move, copy, or delete a page thumbnail, you move, copy, or delete the corresponding page.


2 Answers

Here is my sample code.

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);
like image 193
alones Avatar answered Oct 21 '22 09:10

alones


From iOS 11 you can use PDFKit.

import PDFKit

func generatePdfThumbnail(of thumbnailSize: CGSize , for documentUrl: URL, atPage pageIndex: Int) -> UIImage? {
    let pdfDocument = PDFDocument(url: documentUrl)
    let pdfDocumentPage = pdfDocument?.page(at: pageIndex)
    return pdfDocumentPage?.thumbnail(of: thumbnailSize, for: PDFDisplayBox.trimBox)
}

Call it:

let thumbnailSize = CGSize(width: 100, height: 100)

let thumbnail = generatePdfThumbnail(of: thumbnailSize, for: url, atPage: 0)
like image 22
SuperGlenn Avatar answered Oct 21 '22 09:10

SuperGlenn