【PDF Document Creation, Viewing, and Transforming】
Quartz provides the data type CGPDFDocumentRef to represent a PDF document. You create a CGPDFDocument object using either the function CGPDFDocumentCreateWithProvider or the function CGPDFDocumentCreateWithURL. After you create a CGPDFDocument object, you can draw it to a graphics context.
Following code shows how to create a CGPDFDocument object and obtain the number of pages in the document. by
CGPDFDocumentGetNumberOfPages function. A detailed explanation for each numbered line of code appears following the listing.
1 CGPDFDocumentRef MyGetPDFDocumentRef (const char *filename) 2 { 3 CFStringRef path; 4 CFURLRef url; 5 CGPDFDocumentRef document; 6 size_t count; 7 8 path = CFStringCreateWithCString (NULL, filename, 9 kCFStringEncodingUTF8); 10 url = CFURLCreateWithFileSystemPath (NULL, path, // 1 11 kCFURLPOSIXPathStyle, 0); 12 CFRelease (path); 13 document = CGPDFDocumentCreateWithURL (url);// 2 14 CFRelease(url); 15 count = CGPDFDocumentGetNumberOfPages (document);// 3 16 if (count == 0) { 17 printf("`%s‘ needs at least one page!", filename); 18 return NULL; 19 } 20 return document; 21 }
Drawing a PDF page:
1 void MyDisplayPDFPage (CGContextRef myContext, 2 size_t pageNumber, 3 const char *filename) 4 { 5 CGPDFDocumentRef document; 6 CGPDFPageRef page; 7 8 document = MyGetPDFDocumentRef (filename);// 1 9 page = CGPDFDocumentGetPage (document, pageNumber);// 2 10 CGContextDrawPDFPage (myContext, page);// 3 11 CGPDFDocumentRelease (document);// 4 12 }