如何使用iPhone SDK从PDF文档生成缩略图?

fvi*_*cot 11 pdf iphone quartz-graphics

我已经阅读了Quartz的Apple PDF文档.

但我不知道如何从PDF文档生成缩略图...

任何想法/示例代码?

alo*_*nes 28

这是我的示例代码.

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);
Run Code Online (Sandbox Code Playgroud)

  • 欢迎:请选择我的答案:)。对于您的informatino,如果尝试使所有超过300dpi的PDF缩略图都在iPad上打印数十页,则可能会崩溃。 (2认同)

Sup*_*enn 17

从 iOS 11 开始,您可以使用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)
}
Run Code Online (Sandbox Code Playgroud)

称它为:

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

let thumbnail = generatePdfThumbnail(of: thumbnailSize, for: url, atPage: 0)
Run Code Online (Sandbox Code Playgroud)


Max*_*tov 11

从iOS 11开始,PDFKit框架可用,您可以像下面这样获得缩略图:

import PDFKit

func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  guard let data = try? Data(contentsOf: url),
  let page = PDFDocument(data: data)?.page(at: 0) else {
    return nil
  }

  let pageSize = page.bounds(for: .mediaBox)
  let pdfScale = width / pageSize.width

  // Apply if you're displaying the thumbnail on screen
  let scale = UIScreen.main.scale * pdfScale
  let screenSize = CGSize(width: pageSize.width * scale, 
                          height: pageSize.height * scale)

  return page.thumbnail(of: screenSize, for: .mediaBox)
} 
Run Code Online (Sandbox Code Playgroud)