Rendering PDF in Apple TV tvOS

前端 未结 2 1113
悲哀的现实
悲哀的现实 2021-02-14 17:23

I am working on an addition to my tvOS app that would allow viewing of PDFs stored in the app. However, without UIWebView, I\'m at a loss on how to do this. I\'ve asked questi

2条回答
  •  臣服心动
    2021-02-14 17:45

    The tvOS documentation contains a section on creating, viewing and transforming PDF documents so I think it contains the functionality you need.

    There’s lots of example code on that page, but here’s some code I use on iOS for the same purpose. It should work on tvOS, but I don’t have a way to test it:

    func imageForPDF(URL: NSURL, pageNumber: Int, imageWidth: CGFloat) -> UIImage {
        let document = CGPDFDocumentCreateWithURL(URL)
        let page = CGPDFDocumentGetPage(document, pageNumber)
        var pageRect = CGPDFPageGetBoxRect(page, .MediaBox)
        let scale = imageWidth / pageRect.size.width
        pageRect.size = CGSizeMake(pageRect.size.width * scale, pageRect.size.height * scale)
        pageRect.origin = CGPointZero
    
        UIGraphicsBeginImageContext(pageRect.size)
        let ctx = UIGraphicsGetCurrentContext()
        CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0) // White background
        CGContextFillRect(ctx, pageRect)
        CGContextSaveGState(ctx)
    
        // Rotate the PDF so that it’s the right way around
        CGContextTranslateCTM(ctx, 0.0, pageRect.size.height)
        CGContextScaleCTM(ctx, 1.0, -1.0)
        CGContextConcatCTM(ctx, CGPDFPageGetDrawingTransform(page, .MediaBox, pageRect, 0, true))
    
        CGContextDrawPDFPage(ctx, page)
        CGContextRestoreGState(ctx)
    
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    
        return image
    }
    

提交回复
热议问题