// Handwritten PDF to text with Apple Vision. Tested on macOS 26.6.
// Run: swift pdf2text.swift notes.pdf > notes.txt   (a second argument sets the render dpi, default 300)
import Foundation
import PDFKit
import Vision

let args = CommandLine.arguments
guard args.count > 1, let doc = PDFDocument(url: URL(fileURLWithPath: args[1])) else {
    print("usage: swift pdf2text.swift file.pdf [dpi]"); exit(1)
}
let scale = (args.count > 2 ? Double(args[2]) ?? 300 : 300) / 72 // 72 to 300 dpi: within 1 point in our test
for n in 0..<doc.pageCount {
    let page = doc.page(at: n)!
    let size = page.bounds(for: .mediaBox).applying(page.transform(for: .mediaBox)).size // turned pages too
    let w = Int(size.width * scale), h = Int(size.height * scale)
    let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0,
                        space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
    ctx.setFillColor(.white)
    ctx.fill(CGRect(x: 0, y: 0, width: w, height: h))
    ctx.scaleBy(x: scale, y: scale)
    page.draw(with: .mediaBox, to: ctx)
    let req = VNRecognizeTextRequest()
    req.recognitionLevel = .accurate // .fast finds almost no handwriting
    req.usesLanguageCorrection = true
    req.recognitionLanguages = ["en-US"]
    try VNImageRequestHandler(cgImage: ctx.makeImage()!, options: [:]).perform([req])
    if n > 0 { print("\u{0C}") } // a form feed between pages, as pdftotext writes
    for line in req.results ?? [] { print(line.topCandidates(1).first?.string ?? "") }
}
