cvp
Oct 12, 2019 - 10:01
I use it for pdf covers as buttons images.
from objc_util import *
import ui
def GetUIImageOfPDFPage(path,pageid=1):
UIGraphicsGetCurrentContext = c.UIGraphicsGetCurrentContext
UIGraphicsGetCurrentContext.restype = c_void_p
UIGraphicsGetCurrentContext.argtypes = []
CGPDFDocumentCreateWithURL = c.CGPDFDocumentCreateWithURL
CGPDFDocumentCreateWithURL.restype = c_void_p
CGPDFDocumentCreateWithURL.argtypes = [c_void_p]
CGPDFDocumentGetNumberOfPages = c.CGPDFDocumentGetNumberOfPages
CGPDFDocumentGetNumberOfPages.restype = c_void_p
CGPDFDocumentGetNumberOfPages.argtypes = [c_void_p]
CGPDFDocumentGetPage = c.CGPDFDocumentGetPage
CGPDFDocumentGetPage.restype = c_void_p
CGPDFDocumentGetPage.argtypes = [c_void_p, c_void_p]
CGPDFPageGetBoxRect= c.CGPDFPageGetBoxRect
CGPDFPageGetBoxRect.restype = CGRect
CGPDFPageGetBoxRect.argtypes = [c_void_p,c_void_p]
CGContextDrawPDFPage = c.CGContextDrawPDFPage
CGContextDrawPDFPage.restype = None
CGContextDrawPDFPage.argtypes = [c_void_p,c_void_p]
ns_url = nsurl(path)
document = CGPDFDocumentCreateWithURL(ObjCInstance(ns_url))
#np = CGPDFDocumentGetNumberOfPages(document)
#print('CGPDFDocumentGetNumberOfPages=',np) # to check if document is ok
page = CGPDFDocumentGetPage(document,pageid)
page_mediabox = CGPDFPageGetBoxRect(page,0) # CGPDFBox=0=>kCGPDFMediaBox
w = page_mediabox.size.width
h = page_mediabox.size.height
#print('mediabox=',w,h) # to check if mediabox is ok
with ui.ImageContext(w,h) as context:
cn = UIGraphicsGetCurrentContext()
CGContextDrawPDFPage(cn,page)
ui_image = context.get_image()
return ui_image
# Protect against import
if __name__ == '__main__':
full_path = '......pdf'
ui_image = GetUIImageOfPDFPage(full_path,pageid=40)
v = ui.ImageView()
v.image = ui_image
v.transform = ui.Transform.scale(1,-1) # CGContext is up/down inverted
v.present(hide_title_bar=True)