import Foundation import PDFKit import AppKit // Render one page of a PDF to PNG, and print the page's own label and the page count. // Usage: swift pdfpage.swift file.pdf out.png [scale] let args = CommandLine.arguments guard args.count >= 4, let doc = PDFDocument(url: URL(fileURLWithPath: args[1])), let n = Int(args[2]) else { print("usage: swift pdfpage.swift file.pdf page out.png [scale]"); exit(2) } let scale = args.count > 4 ? (Double(args[4]) ?? 2.0) : 2.0 print("pages \(doc.pageCount)") guard n >= 1, n <= doc.pageCount, let page = doc.page(at: n - 1) else { print("no page \(n)"); exit(1) } print("page \(n) label \(page.label ?? "-")") let box = page.bounds(for: .mediaBox) let w = Int(box.width * scale), h = Int(box.height * scale) let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: w, pixelsHigh: h, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)! let ctx = NSGraphicsContext(bitmapImageRep: rep)! NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = ctx let cg = ctx.cgContext cg.setFillColor(NSColor.white.cgColor) cg.fill(CGRect(x: 0, y: 0, width: w, height: h)) cg.scaleBy(x: CGFloat(scale), y: CGFloat(scale)) page.draw(with: .mediaBox, to: cg) NSGraphicsContext.restoreGraphicsState() try! rep.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: args[3])) print("wrote \(args[3]) \(w)x\(h)")