My app creates a pdf page from app data, using Quartz and UIGraphics.
Basically I define a CGRect docRect to fit on that page, then increment an NSInteger yOffset each time I draw something.
If yOffset gets larger than docRect.size.height I do a UIGraphicsBeginPDFPage().
This works fine, BUT:
I would like to draw a page count at the bottom, like “Page X of Y“.
X is obviously easy to tell, but at the moment when I create a new page, I don’t know how large Y might be.
I see 2 possible solutions for this:
-
After drawing all pages, reiterate through all pages and add the counter.
Problem: As far as I can tell, after callingUIGraphicsBeginPDFPage()there is no way to return back to previous pages. Is anyone able to disconfirm that? -
Calculate all
yOffsetincrements in advance to get the total page count.
Possible, but IMHO not really an elegant solution.
Has anyone advice on this problem?
Thanks in advance, m
If you don’t want to pre-calculate the sizes of everything to determine in advance how many pages you’ll have, one option is to render in two passes, much like you mention in your question. Render the first pass to temp.pdf and leave room for the page number counter.
If working through the source content is a memory or performance burden, the second pass can go to final.pdf, using temp.pdf as an input. Loop through all the pages of temp.pdf, using
CGPDFDocumentGetNumberOfPagesto get your page count. Draw each page from temp.pdf viaCGContextDrawPDFPage, followed by drawing the page counter.When you’re done, delete temp.pdf as cleanup, and you’re all set.
Update: Something along the lines of this untested code, summarized from some previous work: