SPB Git

Repository Public

AnnotatedPDFExporter.swift 6.9 KB 120 lines swift

1// SP Lecture Studio — LecturePDF2// File: Packages/LecturePDF/Sources/AnnotatedPDFExporter.swift3// Description: Writes a derived annotated PDF (flattened vector ink, or editable ink annotations). The source PDF is never modified.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import CoreGraphics9import PDFKit10import LectureCore1112public enum AnnotatedPDFMode: String, Sendable, CaseIterable, Codable {13    /// Ink is drawn into the page content as vector paths (exact appearance, cannot be removed by a reader).14    case flattened15    /// Ink is added as standard PDF ink annotations on a copy of the original (links and text kept, editable in Preview).16    case annotations17}1819public enum AnnotatedPDFExporter {20    public enum ExportError: Error { case cannotCreate, cannotWrite }2122    /// - Parameter strokes: final strokes for a page index (the state at the end of the timeline).23    public static func export(document: SlideDocument, strokes: (Int) -> [Stroke], to destination: URL, mode: AnnotatedPDFMode = .flattened,24                              title: String? = nil) throws {25        precondition(destination.standardizedFileURL != document.url.standardizedFileURL, "the source PDF must never be overwritten")26        switch mode {27        case .flattened: try exportFlattened(document: document, strokes: strokes, to: destination, title: title)28        case .annotations: try exportAnnotations(document: document, strokes: strokes, to: destination)29        }30    }3132    static func exportFlattened(document: SlideDocument, strokes: (Int) -> [Stroke], to destination: URL, title: String?) throws {33        var info: [CFString: Any] = [kCGPDFContextCreator: "SP Lecture Studio"]34        if let title { info[kCGPDFContextTitle] = title }35        guard let ctx = CGContext(destination as CFURL, mediaBox: nil, info as CFDictionary) else { throw ExportError.cannotCreate }36        for i in 0..<document.pageCount {37            let size = document.pageSize(i)38            var box = CGRect(origin: .zero, size: size)39            ctx.beginPage(mediaBox: &box)40            document.draw(page: i, in: ctx, rect: box, background: nil)41            let mapping = PageMapping(rect: box, flipped: false)42            for s in strokes(i) { StrokeRenderer.draw(s, in: ctx, mapping: mapping) }43            ctx.endPage()44        }45        ctx.closePDF()46        guard FileManager.default.fileExists(atPath: destination.path) else { throw ExportError.cannotWrite }47    }4849    static func exportAnnotations(document: SlideDocument, strokes: (Int) -> [Stroke], to destination: URL) throws {50        // Work on an in-memory copy of the original bytes.51        guard let data = try? Data(contentsOf: document.url), let copy = PDFDocument(data: data) else { throw ExportError.cannotCreate }52        for i in 0..<copy.pageCount {53            guard let page = copy.page(at: i) else { continue }54            let list = strokes(i)55            guard !list.isEmpty else { continue }56            let crop = page.bounds(for: .cropBox)57            // Displayed (rotated) page space → unrotated page space used by annotations.58            let rot = ((page.rotation % 360) + 360) % 36059            let display = rot % 180 == 0 ? crop.size : CGSize(width: crop.height, height: crop.width)60            func pagePoint(_ x: Double, _ y: Double) -> CGPoint {61                let dx = x * display.width, dy = (1 - y) * display.height          // display space, origin bottom-left62                let p: CGPoint63                switch rot {64                case 90: p = CGPoint(x: display.height - dy, y: dx)65                case 180: p = CGPoint(x: display.width - dx, y: display.height - dy)66                case 270: p = CGPoint(x: dy, y: display.width - dx)67                default: p = CGPoint(x: dx, y: dy)68                }69                return CGPoint(x: p.x + crop.minX, y: p.y + crop.minY)70            }71            for s in list {72                let width = max(0.5, s.width * display.width)73                let pts = polyline(for: s).map { pagePoint($0.0, $0.1) }74                guard let first = pts.first else { continue }75                var bounds = CGRect(origin: first, size: .zero)76                for p in pts { bounds = bounds.union(CGRect(origin: p, size: .zero)) }77                bounds = bounds.insetBy(dx: -width, dy: -width)78                let ann = PDFAnnotation(bounds: bounds, forType: .ink, withProperties: nil)79                #if os(macOS)80                let path = NSBezierPath()81                path.move(to: NSPoint(x: first.x - bounds.minX, y: first.y - bounds.minY))82                for p in pts.dropFirst() { path.line(to: NSPoint(x: p.x - bounds.minX, y: p.y - bounds.minY)) }83                if pts.count == 1 { path.line(to: NSPoint(x: first.x - bounds.minX + 0.1, y: first.y - bounds.minY)) }84                path.lineCapStyle = .round; path.lineJoinStyle = .round85                ann.color = NSColor(srgbRed: s.color.r, green: s.color.g, blue: s.color.b, alpha: s.color.a)86                #else87                let path = UIBezierPath()88                path.move(to: CGPoint(x: first.x - bounds.minX, y: first.y - bounds.minY))89                for p in pts.dropFirst() { path.addLine(to: CGPoint(x: p.x - bounds.minX, y: p.y - bounds.minY)) }90                if pts.count == 1 { path.addLine(to: CGPoint(x: first.x - bounds.minX + 0.1, y: first.y - bounds.minY)) }91                path.lineCapStyle = .round; path.lineJoinStyle = .round92                ann.color = UIColor(red: s.color.r, green: s.color.g, blue: s.color.b, alpha: s.color.a)93                #endif94                let border = PDFBorder(); border.lineWidth = width; ann.border = border95                ann.add(path)96                ann.userName = "SP Lecture Studio"97                page.addAnnotation(ann)98            }99        }100        guard copy.write(to: destination) else { throw ExportError.cannotWrite }101    }102103    /// Outline of a stroke as page-normalized points (shapes are expanded to their contour).104    public static func polyline(for s: Stroke) -> [(Double, Double)] {105        guard let a = s.points.first, let b = s.points.last else { return [] }106        switch s.tool {107        case .rectangle: return [(a.x, a.y), (b.x, a.y), (b.x, b.y), (a.x, b.y), (a.x, a.y)]108        case .ellipse:109            let cx = (a.x + b.x) / 2, cy = (a.y + b.y) / 2, rx = abs(b.x - a.x) / 2, ry = abs(b.y - a.y) / 2110            return (0...48).map { let t = Double($0) / 48 * 2 * .pi; return (cx + rx * cos(t), cy + ry * sin(t)) }111        case .line: return [(a.x, a.y), (b.x, b.y)]112        case .arrow:113            let ang = atan2(b.y - a.y, b.x - a.x), len = hypot(b.x - a.x, b.y - a.y), head = min(len * 0.45, max(s.width * 4.5, 0.012))114            let l = (b.x + head * cos(ang + .pi - 0.45), b.y + head * sin(ang + .pi - 0.45)), r = (b.x + head * cos(ang + .pi + 0.45), b.y + head * sin(ang + .pi + 0.45))115            return [(a.x, a.y), (b.x, b.y), l, (b.x, b.y), r]116        default: return s.points.map { ($0.x, $0.y) }117        }118    }119}120
Files main
Menu

Theme