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

发布于 2024-10-09 07:54:22 字数 298 浏览 4 评论 0原文

我已阅读使用 Quartz 的 Apple PDF 文档

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

有什么想法/示例代码吗?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

素年丶 2024-10-16 07:54:22

这是我的示例代码。

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);

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);
我的奇迹 2024-10-16 07:54:22

从 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)
}

称之为:

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

let thumbnail = generatePdfThumbnail(of: thumbnailSize, for: url, atPage: 0)

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)
要走干脆点 2024-10-16 07:54:22

从 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)
} 

Starting with iOS 11 where PDFKit framework became available, you can get a thumbnail as simply as:

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)
} 
孤独陪着我 2024-10-16 07:54:22

与此同时,我创建了一个支持 PDF、图像和视频来创建缩略图的库。也许其他人可以使用它:

https://github.com/prine/ROTHumbnailGenerator

Swift 中的解决方案。只需将 NSURL 传递给 PDF 以及您想要以 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;
}

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;
}
若无相欠,怎会相见 2024-10-16 07:54:22

对于 Objective-C

CGRect pageSize = [[self.pdfView.document pageAtIndex:0] boundsForBox:kPDFDisplayBoxMediaBox];
CGFloat pdfScale = [UIScreen mainScreen].bounds.size.width /pageSize.size.width;
CGFloat scale = [UIScreen mainScreen].scale * pdfScale;
UIImage thumbnailImage = [[self.pdfView.document pageAtIndex:0] thumbnailOfSize:CGSizeMake(pageSize.size.width *scale, pageSize.size.height *scale) forBox:kPDFDisplayBoxMediaBox];

For objective-c

CGRect pageSize = [[self.pdfView.document pageAtIndex:0] boundsForBox:kPDFDisplayBoxMediaBox];
CGFloat pdfScale = [UIScreen mainScreen].bounds.size.width /pageSize.size.width;
CGFloat scale = [UIScreen mainScreen].scale * pdfScale;
UIImage thumbnailImage = [[self.pdfView.document pageAtIndex:0] thumbnailOfSize:CGSizeMake(pageSize.size.width *scale, pageSize.size.height *scale) forBox:kPDFDisplayBoxMediaBox];
意犹 2024-10-16 07:54:22

Prine 答案的 Swift 4 版本

func thumbnailFromPdf(withUrl url:URL, pageNumber:Int, width: CGFloat = 240) -> UIImage? {
    guard let pdf = CGPDFDocument(url as CFURL),
        let page = pdf.page(at: pageNumber)
        else {
            return nil
    }

    var pageRect = page.getBoxRect(.mediaBox)
    let pdfScale = width / pageRect.size.width
    pageRect.size = CGSize(width: pageRect.size.width*pdfScale, height: pageRect.size.height*pdfScale)
    pageRect.origin = .zero

    UIGraphicsBeginImageContext(pageRect.size)
    let context = UIGraphicsGetCurrentContext()!

    // White BG
    context.setFillColor(UIColor.white.cgColor)
    context.fill(pageRect)
    context.saveGState()

    // Next 3 lines makes the rotations so that the page look in the right direction
    context.translateBy(x: 0.0, y: pageRect.size.height)
    context.scaleBy(x: 1.0, y: -1.0)
    context.concatenate(page.getDrawingTransform(.mediaBox, rect: pageRect, rotate: 0, preserveAspectRatio: true))

    context.drawPDFPage(page)
    context.restoreGState()

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

Swift 4 Version of Prine's Answer

func thumbnailFromPdf(withUrl url:URL, pageNumber:Int, width: CGFloat = 240) -> UIImage? {
    guard let pdf = CGPDFDocument(url as CFURL),
        let page = pdf.page(at: pageNumber)
        else {
            return nil
    }

    var pageRect = page.getBoxRect(.mediaBox)
    let pdfScale = width / pageRect.size.width
    pageRect.size = CGSize(width: pageRect.size.width*pdfScale, height: pageRect.size.height*pdfScale)
    pageRect.origin = .zero

    UIGraphicsBeginImageContext(pageRect.size)
    let context = UIGraphicsGetCurrentContext()!

    // White BG
    context.setFillColor(UIColor.white.cgColor)
    context.fill(pageRect)
    context.saveGState()

    // Next 3 lines makes the rotations so that the page look in the right direction
    context.translateBy(x: 0.0, y: pageRect.size.height)
    context.scaleBy(x: 1.0, y: -1.0)
    context.concatenate(page.getDrawingTransform(.mediaBox, rect: pageRect, rotate: 0, preserveAspectRatio: true))

    context.drawPDFPage(page)
    context.restoreGState()

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文