Thomas Tempelmann
Thomas Tempelmann

Reputation: 12043

Determine rendered height in a PDF document for drawing dynamic-sized page footers, on macOS

Assuming I print a small amount of text into a PDF document, I like to know how much of the page is actually used by the text.

For example, if I render a short text paragraph into a PDF document, I like to learn the content height of only that text, not of the entire A4 (letter) page.

How high is this text?

Background

I need to render a long HTML page into a PDF document that uses a smaller page size. The result is that the content gets rendered into several PDF pages. I currently use NSPrintOperation for this.

The challenge is that I also need to render a footer page into each page. For this, I need to dynamically determine the height of that footer so that I can set the page's bottom margin accordingly, resulting in the footer area be kept free when rendering the main (body) HTML content. Once that's finished, I can then add the footer to each page in a separate step (using CGPDFDocument).

I wish there was a simpler way, but it seems that the macOS HTML renderer cannot handle html footers when printing multiple pages.

Upvotes: 0

Views: 225

Answers (1)

Thomas Tempelmann
Thomas Tempelmann

Reputation: 12043

I found a solution, though that's a bit ugly:

  1. Generate the PDF with the footer content, so that it renders at the top of the page (margins set to 0).
  2. Read the PDF into NSPDFImageRepMBS
  3. Create a NSImageMBS and add the imageRep to it with addRepresentation:
  4. Now the image has a size of the original PDF page, but contains only the drawable region of the footer content - the rest of the image is clear.
  5. By scanning the image's lines from bottom towards the top, looking for a non-clear line, the height of the footer content can be determined.
  6. With the footer height known, I can now render the main content to a PDF with the bottom margin set to keep free the footer area
  7. Finally, I create a new CGPDFDocument, going over each page of the main PDF, drawing thes main pages along with the footer (offset into the page's footer area) into each page.

Upvotes: 0

Related Questions