I went a different route to print page numbers than that suggested by the challenge. I decided to turn on the printing of page headers and footers by adding the key-value pair [1 : “NSPrintHeadersAndFooter”] to the printInfo dictionary and let the OS print the page numbers for me. It works except that the font for the header/footer is different from what the EmployeePrintingView uses. I read the documentation and user reference guide for the NSPrintInfo class but I could find anything that allows me to set the header/footer font. How can my program set the header/footer font?
The following code place the page number in the bottom center of the pages:
in knowsPageRange
// Make space to draw the page number
linesPerPage -= 2
At the end of drawRect (after the for loop)
// Draw page number
let pageNumberString = "Page \(currentPage + 1)"
let pageNumberStringSize = pageNumberString.sizeWithAttributes(textAttributes)
var pageNumberRect = NSRect(x: pageRect.minX, y: 0, width: pageNumberStringSize.width, height: pageNumberStringSize.height)
pageNumberRect.origin.y = pageRect.maxY - lineHeight * 2
pageNumberRect.origin.x = (pageRect.width / 2) - pageNumberStringSize.width / 2
pageNumberString.drawInRect(pageNumberRect, withAttributes: textAttributes)
[quote=“Miyano”]The following code place the page number in the bottom center of the pages:
in knowsPageRange
// Make space to draw the page number
linesPerPage -= 2
[/quote]
I put in a Boolean variable to check if page numbers should be printed. It activates only if there are at least 4 lines of text to use.
[quote=“Miyano”]At the end of drawRect (after the for loop)
[code]
// Draw page number
let pageNumberString = "Page (currentPage + 1)"
let pageNumberStringSize = pageNumberString.sizeWithAttributes(textAttributes)
var pageNumberRect = NSRect(x: pageRect.minX, y: 0, width: pageNumberStringSize.width, height: pageNumberStringSize.height)
pageNumberRect.origin.y = pageRect.maxY - lineHeight * 2
pageNumberRect.origin.x = (pageRect.width / 2) - pageNumberStringSize.width / 2
pageNumberString.drawInRect(pageNumberRect, withAttributes: textAttributes)
[/code][/quote]
I made a NSRect for the entire bottom line, and added center-positioning to the attribute dictionary.
To Enable header and footer
printInfo.dictionary()[NSPrintInfo.AttributeKey.headerAndFooter.rawValue] = true
To set the header/footer with font.
private let font = NSFont.userFixedPitchFont(ofSize: 12.0)!
private let textAttributes: [NSAttributedStringKey: Any] = [.font: font]
class EmployeesPrintingView: NSView {
override var pageHeader: NSAttributedString {
return NSAttributedString(string: "RaiseMan Report", attributes: textAttributes)
}
override var pageFooter: NSAttributedString {
var footerAttributes = textAttributes
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .right
footerAttributes[.paragraphStyle] = paragraphStyle
return NSAttributedString(string: "Page \(currentPage + 1)", attributes: footerAttributes)
}