SPB Git

Repository Public License

Fixtures.swift 25.8 KB 447 lines swift

1// ORIX Convert — Packages/EnginePDF/Tests/EnginePDFTests/Fixtures.swift2// Description: Fixtures generated in code (Core Graphics, Core Text, PDFKit, ImageIO, hand-written PDF objects) and3//              the helper that runs a request through convert + validate.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import CoreGraphics7import CoreText8import ImageIO9import PDFKit10import Testing11import UniformTypeIdentifiers12import ConvertCore13@testable import EnginePDF1415/// Every test of the package runs serialised: PDFKit, Vision and the timing / memory measurements are steadier.16@Suite(.serialized) struct PDFEngineTests {}1718final class Collected<T: Sendable>: @unchecked Sendable {19    private let lock = NSLock()20    private var items: [T] = []21    func add(_ item: T) { lock.lock(); items.append(item); lock.unlock() }22    var all: [T] { lock.lock(); defer { lock.unlock() }; return items }23}2425struct RunResult {26    let output: ConversionOutput27    let warnings: [ConversionWarning]28    let checks: [ValidationCheck]29    let progress: [ProgressUpdate]30    var file: URL { output.files[0] }31    func hasWarning(_ code: String) -> Bool { warnings.contains { $0.code == code } }32    var files: [URL] { PDFValidator.files(in: output) }33}3435enum Fx {36    static let engine = PDFEngine()3738    static let root: URL = {39        let url = FileManager.default.temporaryDirectory.appendingPathComponent("orix-enginepdf-tests-\(ProcessInfo.processInfo.processIdentifier)", isDirectory: true)40        try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)41        // Fixtures and outputs are removed when the test process exits.42        atexit {43            let path = FileManager.default.temporaryDirectory.appendingPathComponent("orix-enginepdf-tests-\(ProcessInfo.processInfo.processIdentifier)", isDirectory: true)44            try? FileManager.default.removeItem(at: path)45        }46        return url47    }()4849    static func dir(_ name: String = "work") -> URL {50        let url = root.appendingPathComponent("\(name)-\(UUID().uuidString.prefix(8))", isDirectory: true)51        try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)52        return url53    }5455    static func size(_ url: URL) -> Int { Int(PDFSupport.fileSize(url)) }5657    /// Converts and validates; fails the test when a validation check does not pass.58    @discardableResult59    static func run(_ request: ConversionRequest, validate: Bool = true, sourceLocation: SourceLocation = #_sourceLocation) async throws -> RunResult {60        #expect(engine.path(for: request) != nil, "undeclared path", sourceLocation: sourceLocation)61        let warnings = Collected<ConversionWarning>(), progress = Collected<ProgressUpdate>()62        let context = ConversionContext(workDirectory: dir("out"), progress: { progress.add($0) }, warn: { warnings.add($0) })63        let output = try await engine.convert(request, context: context)64        for file in output.files {65            #expect(file.path.hasPrefix(context.workDirectory.path), "output outside the work directory", sourceLocation: sourceLocation)66            #expect(FileManager.default.fileExists(atPath: file.path), sourceLocation: sourceLocation)67        }68        for update in progress.all {69            if let f = update.fraction { #expect(f >= 0 && f <= 1.0001, sourceLocation: sourceLocation) }70        }71        var checks: [ValidationCheck] = []72        if validate {73            checks = try await engine.validate(output, request: request, source: nil)74            #expect(!checks.isEmpty, "no validation checks", sourceLocation: sourceLocation)75            for check in checks { #expect(check.passed, "validation “\(check.name)” failed: \(check.detail)", sourceLocation: sourceLocation) }76        }77        return RunResult(output: output, warnings: warnings.all, checks: checks, progress: progress.all)78    }7980    static func request(_ source: URL, to destination: FormatID, op: String? = nil, _ options: [String: OptionValue] = [:], more: [URL] = [], from: FormatID = .pdf) -> ConversionRequest {81        ConversionRequest(source: source, sourceFormat: from, destinationFormat: destination, operation: op, options: ConversionOptions(options), additionalSources: more)82    }8384    // MARK: Drawing helpers8586    static func font(_ size: CGFloat, _ name: String = "Helvetica") -> CTFont { CTFontCreateWithName(name as CFString, size, nil) }8788    static func draw(_ text: String, at point: CGPoint, size: CGFloat, font name: String = "Helvetica", in ctx: CGContext, gray: CGFloat = 0) {89        let color = CGColor(gray: gray, alpha: 1)90        let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [91            NSAttributedString.Key(kCTFontAttributeName as String): font(size, name),92            NSAttributedString.Key(kCTForegroundColorAttributeName as String): color,93        ]))94        ctx.textMatrix = .identity95        ctx.textPosition = point96        CTLineDraw(line, ctx)97    }9899    /// Bounds of a word inside a line drawn with `draw(_:at:size:)`.100    static func wordRect(_ word: String, in text: String, at point: CGPoint, size: CGFloat) -> CGRect {101        let f = font(size)102        let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): f]))103        let range = (text as NSString).range(of: word)104        let x0 = CTLineGetOffsetForStringIndex(line, range.location, nil), x1 = CTLineGetOffsetForStringIndex(line, range.location + range.length, nil)105        return CGRect(x: point.x + x0, y: point.y - CTFontGetDescent(f), width: x1 - x0, height: CTFontGetAscent(f) + CTFontGetDescent(f))106    }107108    struct PageSpec {109        var size = CGSize(width: 612, height: 792)110        var lines: [String]111        var fontSize: CGFloat = 14112        var marker = true113    }114115    /// Text PDF: each page lists its lines from the top; a black square marks the top-left corner of the sheet.116    @discardableResult117    static func textPDF(_ name: String, pages: [PageSpec], rotations: [Int: Int] = [:], info: [CFString: Any] = [:]) -> URL {118        let raw = dir("fixture").appendingPathComponent(rotations.isEmpty ? name : "raw-" + name)119        let ctx = CGContext(raw as CFURL, mediaBox: nil, info as CFDictionary)!120        for spec in pages {121            var box = CGRect(origin: .zero, size: spec.size)122            ctx.beginPage(mediaBox: &box)123            if spec.marker { ctx.setFillColor(gray: 0, alpha: 1); ctx.fill(CGRect(x: 20, y: spec.size.height - 60, width: 40, height: 40)) }124            for (i, line) in spec.lines.enumerated() {125                draw(line, at: CGPoint(x: 72, y: spec.size.height - 100 - CGFloat(i) * spec.fontSize * 1.5), size: spec.fontSize, in: ctx)126            }127            ctx.endPage()128        }129        ctx.closePDF()130        guard !rotations.isEmpty else { return raw }131        let source = PDFDocument(url: raw)!132        let out = PDFDocument()133        for i in 0..<source.pageCount {134            let page = source.page(at: i)!135            if let r = rotations[i] { page.rotation = r }136            out.insert(page, at: i)137        }138        let url = raw.deletingLastPathComponent().appendingPathComponent(name)139        precondition(out.write(to: url))140        return url141    }142143    static func simplePDF(_ name: String = "simple.pdf", pages: Int = 3, word: String = "Alpha") -> URL {144        textPDF(name, pages: (1...pages).map { PageSpec(lines: ["\(word) document page \($0)", "Marker \(word)PAGE\($0) zebra crossing"]) })145    }146147    // MARK: Rich PDF: outline + links + annotations + form field148149    static func richPDF(_ name: String = "rich.pdf") -> URL {150        let base = textPDF("base-" + name, pages: [151            PageSpec(lines: ["Chapter One introduction", "Richdoc first page with a link"]),152            PageSpec(lines: ["Chapter Two methods", "Richdoc second page with a form field"]),153            PageSpec(lines: ["Section Two point one", "Richdoc third page with a note"]),154            PageSpec(lines: ["Chapter Three results", "Richdoc fourth page"]),155        ], info: [kCGPDFContextTitle: "Rich Fixture", kCGPDFContextAuthor: "ORIX Tests"])156        let source = PDFDocument(url: base)!157        let doc = PDFDocument()158        for i in 0..<source.pageCount { doc.insert(source.page(at: i)!, at: i) }159        let root = PDFOutline()160        doc.outlineRoot = root161        func entry(_ label: String, _ page: Int) -> PDFOutline {162            let o = PDFOutline(); o.label = label163            o.destination = PDFDestination(page: doc.page(at: page)!, at: CGPoint(x: 0, y: 792))164            return o165        }166        let one = entry("Chapter One", 0), two = entry("Chapter Two", 1), sub = entry("Section 2.1", 2), three = entry("Chapter Three", 3)167        root.insertChild(one, at: 0); root.insertChild(two, at: 1); two.insertChild(sub, at: 0); root.insertChild(three, at: 2)168        let web = PDFAnnotation(bounds: CGRect(x: 72, y: 600, width: 120, height: 20), forType: .link, withProperties: nil)169        web.url = URL(string: "https://example.com/orix")170        doc.page(at: 0)!.addAnnotation(web)171        let jump = PDFAnnotation(bounds: CGRect(x: 72, y: 560, width: 120, height: 20), forType: .link, withProperties: nil)172        jump.action = PDFActionGoTo(destination: PDFDestination(page: doc.page(at: 3)!, at: CGPoint(x: 0, y: 792)))173        doc.page(at: 0)!.addAnnotation(jump)174        let field = PDFAnnotation(bounds: CGRect(x: 72, y: 500, width: 200, height: 24), forType: .widget, withProperties: nil)175        field.widgetFieldType = .text; field.fieldName = "customer"; field.widgetStringValue = "FieldValue42"176        doc.page(at: 1)!.addAnnotation(field)177        let note = PDFAnnotation(bounds: CGRect(x: 300, y: 300, width: 200, height: 100), forType: .square, withProperties: nil)178        note.color = .red; note.interiorColor = .red179        doc.page(at: 2)!.addAnnotation(note)180        doc.documentAttributes = [PDFDocumentAttribute.titleAttribute: "Rich Fixture", PDFDocumentAttribute.authorAttribute: "ORIX Tests"]181        let url = base.deletingLastPathComponent().appendingPathComponent(name)182        precondition(doc.write(to: url))183        return url184    }185186    struct Structure: Equatable {187        var pages = 0, outline = 0, links = 0, urlLinks = 0, gotoLinks = 0, widgets = 0, squares = 0188        var fieldValue: String?189    }190191    static func structure(_ url: URL, password: String? = nil) -> Structure {192        guard let doc = PDFDocument(url: url) else { return Structure() }193        if let password { _ = doc.unlock(withPassword: password) }194        var s = Structure(pages: doc.pageCount, outline: PDFAssemble.outlineCount(doc))195        for i in 0..<doc.pageCount {196            for a in doc.page(at: i)?.annotations ?? [] {197                switch a.type ?? "" {198                case "Link":199                    s.links += 1200                    if a.url != nil || (a.action as? PDFActionURL) != nil { s.urlLinks += 1 }201                    if a.destination?.page != nil || (a.action as? PDFActionGoTo)?.destination.page != nil { s.gotoLinks += 1 }202                case "Widget": s.widgets += 1; s.fieldValue = a.widgetStringValue203                case "Square": s.squares += 1204                default: break205                }206            }207        }208        return s209    }210211    // MARK: Scanned pages212213    struct ScanLine { let text: String; let at: CGPoint; let size: CGFloat }214    static let scanLines = [215        ScanLine(text: "Quantum physics describes nature", at: CGPoint(x: 72, y: 650), size: 18),216        ScanLine(text: "ORIX Convert makes scanned documents searchable", at: CGPoint(x: 72, y: 600), size: 14),217        ScanLine(text: "Invoice number 48213 dated November 2026", at: CGPoint(x: 72, y: 540), size: 16),218    ]219    static let scanProbes = ["Quantum", "searchable", "Invoice", "48213"]220221    /// Bitmap of a page of text (black on white) at `dpi`; `size` in points.222    static func scanBitmap(size: CGSize = CGSize(width: 612, height: 792), dpi: Double, lines: [ScanLine] = scanLines) -> CGImage {223        let w = Int((size.width * dpi / 72).rounded()), h = Int((size.height * dpi / 72).rounded())224        let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!225        ctx.setFillColor(gray: 1, alpha: 1); ctx.fill(CGRect(x: 0, y: 0, width: w, height: h))226        ctx.scaleBy(x: dpi / 72, y: dpi / 72)227        for line in lines { draw(line.text, at: line.at, size: line.size, in: ctx) }228        return ctx.makeImage()!229    }230231    /// Expected bounds of each probe word in the coordinate space of the upright scan (points).232    static func scanProbeRects() -> [String: CGRect] {233        var out: [String: CGRect] = [:]234        for probe in scanProbes {235            if let line = scanLines.first(where: { $0.text.contains(probe) }) { out[probe] = wordRect(probe, in: line.text, at: line.at, size: line.size) }236        }237        return out238    }239240    /// Image-only PDF: page 1 upright; with `variants`, page 2 is stored sideways with /Rotate 90 and page 3 has a241    /// media box that does not start at the origin plus a smaller crop box.242    static func scannedPDF(_ name: String, dpi: Double, variants: Bool = false) -> URL {243        let bitmap = scanBitmap(dpi: dpi)244        let raw = dir("fixture").appendingPathComponent(variants ? "raw-" + name : name)245        let ctx = CGContext(raw as CFURL, mediaBox: nil, nil)!246        var box = CGRect(x: 0, y: 0, width: 612, height: 792)247        ctx.beginPage(mediaBox: &box); ctx.draw(bitmap, in: box); ctx.endPage()248        guard variants else { ctx.closePDF(); return raw }249        // Page 2: the upright scan (612 × 792) drawn rotated counter-clockwise on a 792 × 612 sheet shown with /Rotate 90.250        var wide = CGRect(x: 0, y: 0, width: 792, height: 612)251        ctx.beginPage(mediaBox: &wide)252        ctx.saveGState(); ctx.translateBy(x: 792, y: 0); ctx.rotate(by: .pi / 2); ctx.draw(bitmap, in: box); ctx.restoreGState()253        ctx.endPage()254        // Page 3: media box [50 50 662 842], crop box inset by 10.255        let media = CGRect(x: 50, y: 50, width: 612, height: 792), crop = media.insetBy(dx: 10, dy: 10)256        ctx.beginPDFPage([kCGPDFContextMediaBox: withUnsafeBytes(of: media) { Data($0) }, kCGPDFContextCropBox: withUnsafeBytes(of: crop) { Data($0) }] as CFDictionary)257        ctx.draw(bitmap, in: media)258        ctx.endPDFPage()259        ctx.closePDF()260        let source = PDFDocument(url: raw)!, out = PDFDocument()261        for i in 0..<3 { let p = source.page(at: i)!; if i == 1 { p.rotation = 90 }; out.insert(p, at: i) }262        let url = raw.deletingLastPathComponent().appendingPathComponent(name)263        precondition(out.write(to: url))264        return url265    }266267    /// Hand-written one-page scan whose media box really starts at (50, 50), with a smaller crop box.268    static func offsetScanPDF(_ name: String = "offset-scan.pdf", dpi: Double = 150) -> URL {269        let bitmap = scanBitmap(dpi: dpi)270        let w = bitmap.width, h = bitmap.height271        let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue)!272        ctx.draw(bitmap, in: CGRect(x: 0, y: 0, width: w, height: h))273        let pixels = Data(bytes: ctx.data!, count: w * h)274        func s(_ t: String) -> Data { Data(t.utf8) }275        let objects: [(Int, Data)] = [276            (1, s("<< /Type /Catalog /Pages 2 0 R >>")),277            (2, s("<< /Type /Pages /Kids [3 0 R] /Count 1 >>")),278            (3, s("<< /Type /Page /Parent 2 0 R /MediaBox [50 50 662 842] /CropBox [60 60 652 832] /Contents 4 0 R /Resources << /XObject << /Im1 5 0 R >> >> >>")),279            (4, stream("", s("q 612 0 0 792 50 50 cm /Im1 Do Q"))),280            (5, stream("/Type /XObject /Subtype /Image /Width \(w) /Height \(h) /ColorSpace /DeviceGray /BitsPerComponent 8", pixels)),281        ]282        let url = dir("fixture").appendingPathComponent(name)283        try! rawPDF(objects, root: 1).write(to: url)284        return url285    }286287    /// Where a rect of the upright scan lands in the unrotated page space of each page of the `variants` fixture.288    static func expectedRect(_ r: CGRect, page: Int) -> CGRect {289        switch page {290        case 1: return CGRect(x: 792 - r.maxY, y: r.minX, width: r.height, height: r.width)291        default: return r                               // Core Graphics moved the media box of page 3 back to the origin292        }293    }294295    // MARK: Images296297    static func noise(_ w: Int, _ h: Int, alpha: Bool = false, seed: UInt64 = 88172645463325252) -> CGImage {298        let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, space: CGColorSpace(name: CGColorSpace.sRGB)!,299                            bitmapInfo: (alpha ? CGImageAlphaInfo.premultipliedLast : CGImageAlphaInfo.noneSkipLast).rawValue)!300        let p = ctx.data!.bindMemory(to: UInt8.self, capacity: w * h * 4)301        var s = seed302        for y in 0..<h {303            for x in 0..<w {304                s ^= s << 13; s ^= s >> 7; s ^= s << 17305                let n = Int(s & 31), i = (y * w + x) * 4306                let a = alpha ? (x < w / 2 ? 255 : 96) : 255307                p[i] = UInt8(min(255, x * 255 / w + n) * a / 255); p[i + 1] = UInt8(min(255, y * 255 / h + n) * a / 255); p[i + 2] = UInt8(n * 4 * a / 255); p[i + 3] = UInt8(a)308            }309        }310        return ctx.makeImage()!311    }312313    /// Opaque image with a pure red left half and a pure blue right half (orientation tests).314    static func halves(_ w: Int, _ h: Int) -> CGImage {315        let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!316        ctx.setFillColor(red: 1, green: 0, blue: 0, alpha: 1); ctx.fill(CGRect(x: 0, y: 0, width: w / 2, height: h))317        ctx.setFillColor(red: 0, green: 0, blue: 1, alpha: 1); ctx.fill(CGRect(x: w / 2, y: 0, width: w - w / 2, height: h))318        return ctx.makeImage()!319    }320321    @discardableResult322    static func write(_ images: [CGImage], _ name: String, type: UTType, properties: [CFString: Any] = [:], in directory: URL? = nil) -> URL {323        let url = (directory ?? dir("img")).appendingPathComponent(name)324        let dest = CGImageDestinationCreateWithURL(url as CFURL, type.identifier as CFString, images.count, nil)!325        for image in images { CGImageDestinationAddImage(dest, image, properties as CFDictionary) }326        precondition(CGImageDestinationFinalize(dest), "cannot write \(name)")327        return url328    }329330    static func jpegData(_ image: CGImage, quality: Double = 0.9) -> Data { ImagesToPDF.jpegData(image, quality: quality)! }331332    /// PDF with a text line and large embedded images: a JPEG (3000 × 2000 drawn 6 in wide = 500 dpi) on page 1 and333    /// a lossless RGB image (1600 × 1200 drawn 6 in wide ≈ 267 dpi) on page 2. Returns the JPEG bytes too.334    static func imageHeavyPDF(_ name: String = "images.pdf") -> (url: URL, jpeg: Data) {335        let jpeg = jpegData(noise(3000, 2000), quality: 0.9)336        let url = dir("fixture").appendingPathComponent(name)337        let ctx = CGContext(url as CFURL, mediaBox: nil, nil)!338        var box = CGRect(x: 0, y: 0, width: 612, height: 792)339        ctx.beginPage(mediaBox: &box)340        draw("Compressible photo page SELECTABLE", at: CGPoint(x: 72, y: 700), size: 16, in: ctx)341        ctx.draw(CGImage(jpegDataProviderSource: CGDataProvider(data: jpeg as CFData)!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)!, in: CGRect(x: 72, y: 300, width: 432, height: 288))342        ctx.move(to: CGPoint(x: 72, y: 250)); ctx.addLine(to: CGPoint(x: 500, y: 200)); ctx.strokePath()343        ctx.endPage()344        ctx.beginPage(mediaBox: &box)345        draw("Lossless image page SELECTABLE", at: CGPoint(x: 72, y: 700), size: 16, in: ctx)346        ctx.draw(noise(1600, 1200, seed: 7), in: CGRect(x: 72, y: 250, width: 432, height: 324))347        ctx.endPage()348        ctx.closePDF()349        return (url, jpeg)350    }351352    // MARK: Hand-written PDFs353354    /// Serialises PDF objects (number → body) with a classic cross-reference table.355    static func rawPDF(_ objects: [(Int, Data)], root: Int, info: Int? = nil) -> Data {356        var data = Data("%PDF-1.7\n%\u{E2}\u{E3}\u{CF}\u{D3}\n".utf8)357        var offsets: [Int: Int] = [:]358        for (number, body) in objects {359            offsets[number] = data.count360            data.append(Data("\(number) 0 obj\n".utf8)); data.append(body); data.append(Data("\nendobj\n".utf8))361        }362        let maxNumber = objects.map(\.0).max() ?? 0363        let xref = data.count364        var table = "xref\n0 \(maxNumber + 1)\n0000000000 65535 f \n"365        for n in 1...maxNumber {366            if let o = offsets[n] { table += String(format: "%010d 00000 n \n", o) } else { table += "0000000000 65535 f \n" }367        }368        table += "trailer\n<< /Size \(maxNumber + 1) /Root \(root) 0 R\(info.map { " /Info \($0) 0 R" } ?? "") >>\nstartxref\n\(xref)\n%%EOF\n"369        data.append(Data(table.utf8))370        return data371    }372373    static func stream(_ dict: String, _ payload: Data) -> Data {374        var d = Data("<< \(dict) /Length \(payload.count) >>\nstream\n".utf8)375        d.append(payload); d.append(Data("\nendstream".utf8))376        return d377    }378379    /// One-page PDF with an attachment, a tag structure, XMP, an AcroForm text field, JavaScript, a fake380    /// linearisation dictionary, a CCITT image XObject and an inline image.381    static func featurePDF(_ name: String = "features.pdf") -> URL {382        func s(_ t: String) -> Data { Data(t.utf8) }383        var content = Data("BT /F1 24 Tf 72 700 Td (Featureful RAWPDF document) Tj ET\nq 100 0 0 100 72 500 cm /Im1 Do Q\nq 20 0 0 20 300 500 cm BI /W 2 /H 2 /CS /G /BPC 8 ID ".utf8)384        content.append(Data([0x00, 0xFF, 0xFF, 0x00])); content.append(Data("\nEI Q\n".utf8))385        let xmp = "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"><dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">XMPTITLE</rdf:li></rdf:Alt></dc:title></rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>"386        let objects: [(Int, Data)] = [387            (12, s("<< /Linearized 1 /L 4096 /H [0 0] /O 3 /E 0 /N 1 /T 0 >>")),388            (1, s("<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(note.txt) 6 0 R] >> /JavaScript << /Names [(init) 13 0 R] >> >> /MarkInfo << /Marked true >> /StructTreeRoot 8 0 R /Metadata 9 0 R /AcroForm << /Fields [10 0 R] /DA (/Helv 0 Tf 0 g) >> >>")),389            (2, s("<< /Type /Pages /Kids [3 0 R] /Count 1 >>")),390            (3, s("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /XObject << /Im1 11 0 R >> >> /Annots [10 0 R] >>")),391            (4, stream("", content)),392            (5, s("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")),393            (6, s("<< /Type /Filespec /F (note.txt) /EF << /F 7 0 R >> >>")),394            (7, stream("/Type /EmbeddedFile", s("hello attachment"))),395            (8, s("<< /Type /StructTreeRoot >>")),396            (9, stream("/Type /Metadata /Subtype /XML", s(xmp))),397            (10, s("<< /Type /Annot /Subtype /Widget /FT /Tx /T (field1) /V (hello) /Rect [72 400 272 424] /P 3 0 R >>")),398            (11, stream("/Type /XObject /Subtype /Image /Width 8 /Height 8 /ColorSpace /DeviceGray /BitsPerComponent 1 /Filter /CCITTFaxDecode /DecodeParms << /K -1 /Columns 8 /Rows 8 >>", Data([0x00, 0x10, 0x01, 0x00, 0x10, 0x01]))),399            (13, s("<< /S /JavaScript /JS (app.alert\\('never run'\\);) >>")),400            (14, s("<< /Title (Feature Title) /Author (Feature Author) /Keywords (alpha, beta) >>")),401        ]402        let url = dir("fixture").appendingPathComponent(name)403        try! rawPDF(objects, root: 1, info: 14).write(to: url)404        return url405    }406407    /// Protected copy of a PDF. `permissions` are the allowed actions (PDFAccessPermissions raw values or-ed).408    static func protect(_ source: URL, name: String, user: String?, owner: String, permissions: UInt) -> URL {409        let doc = PDFDocument(url: source)!410        var options: [PDFDocumentWriteOption: Any] = [.ownerPasswordOption: owner, .accessPermissionsOption: NSNumber(value: permissions)]411        if let user { options[.userPasswordOption] = user }412        let url = dir("fixture").appendingPathComponent(name)413        precondition(doc.write(to: url, withOptions: options))414        return url415    }416417    static let printOnly: UInt = PDFAccessPermissions.allowsLowQualityPrinting.rawValue | PDFAccessPermissions.allowsHighQualityPrinting.rawValue418419    // MARK: Pixels420421    /// RGBA of a decoded image at (x, y), origin top-left.422    static func pixel(_ image: CGImage, _ x: Int, _ y: Int) -> (r: Int, g: Int, b: Int, a: Int) {423        let ctx = CGContext(data: nil, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!424        ctx.draw(image, in: CGRect(x: -CGFloat(x), y: -CGFloat(image.height - 1 - y), width: CGFloat(image.width), height: CGFloat(image.height)))425        let p = ctx.data!.bindMemory(to: UInt8.self, capacity: 4)426        return (Int(p[0]), Int(p[1]), Int(p[2]), Int(p[3]))427    }428429    static func load(_ url: URL, frame: Int = 0) -> CGImage? {430        CGImageSourceCreateWithURL(url as CFURL, nil).flatMap { CGImageSourceCreateImageAtIndex($0, frame, nil) }431    }432433    static func peakRSSMegabytes() -> Double {434        var usage = rusage()435        getrusage(RUSAGE_SELF, &usage)436        return Double(usage.ru_maxrss) / 1_048_576437    }438439    static func text(_ url: URL) -> String { (try? String(contentsOf: url, encoding: .utf8)) ?? "" }440441    static func pdfText(_ url: URL, page: Int, password: String? = nil) -> String {442        guard let doc = PDFDocument(url: url) else { return "" }443        if let password { _ = doc.unlock(withPassword: password) }444        return doc.page(at: page)?.string ?? ""445    }446}447
Files main
Menu

Theme