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. Figure 13-2 shows a PDF document displayed by the PDFViewer sample application. After you install the Xcode Tools CD, you can find the Xcode project for this application in:
/Developer/Examples/Quartz/PDF/PDFViewer
Listing 13-1 shows how to create a CGPDFDocument object and obtain the number of pages in the document. A detailed explanation for each numbered line of code appears following the listing.
Listing 13-1 A function that creates a CGPDFDocument object from a PDF file
CGPDFDocumentRef MyGetPDFDocumentRef (const char *filename) |
{ |
CFStringRef path; |
CFURLRef url; |
CGPDFDocumentRef document; |
path = CFStringCreateWithCString (NULL, filename, |
kCFStringEncodingUTF8); |
url = CFURLCreateWithFileSystemPath (NULL, path, // 1 |
kCFURLPOSIXPathStyle, 0); |
CFRelease (path); |
document = CGPDFDocumentCreateWithURL (url);// 2 |
CFRelease(url); |
count = CGPDFDocumentGetNumberOfPages (document);// 3 |
if (count == 0) { |
printf("`%s' needs at least one page!", filename); |
return NULL; |
} |
return document; |
} |
Here’s what the code does:
Calls the Core Foundation function to create a CFURL object from a CFString object that represents the filename of the PDF file to display.
Creates a CGPDFDocument object from a CFURL object.
Gets the number of pages in the PDF so that the next statement in the code can ensure that the document has at least one page.
You can see how to draw a PDF page to a graphics context by looking at the code in Listing 13-2. A detailed explanation for each numbered line of code appears following the listing.
Listing 13-2 A function that draws a PDF page
void MyDisplayPDFPage (CGContextRef myContext, |
size_t pageNumber, |
const char *filename) |
{ |
CGPDFDocumentRef document; |
CGPDFPageRef page; |
CGRect box; |
document = MyGetPDFDocumentRef (filename);// 1 |
page = CGPDFDocumentGetPage (document, pageNumber);// 2 |
CGContextDrawPDFPage (myContext, page);// 3 |
CGPDFDocumentRelease (document);// 4 |
} |
Here’s what the code does:
Calls your function (see Listing 13-1) to create a CGPDFDocument object from a file name you supply.
Gets the page for the specified page number from the PDF document.
Draws the specified page from the PDF file by calling the function CGContextDrawPDFPage. You need to supply a graphics context and the page to draw. For applications running in Mac OS X v10.3 and later, this function is recommended as a replacement for the older function CGContextDrawPDFDocument.
Releases the CGPDFDocument object.
Last updated: 2007-12-11