SPB Git

Repository Public License

ImagesToPDFTests.swift 12.5 KB 167 lines swift

1// ORIX Convert — Packages/EnginePDF/Tests/EnginePDFTests/ImagesToPDFTests.swift2// Description: Images → PDF for every declared source format, JPEG pass-through, orientation, page layout, OCR layer.3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import Foundation5import CoreGraphics6import ImageIO7import PDFKit8import Testing9import UniformTypeIdentifiers10import ConvertCore11@testable import EnginePDF1213extension PDFEngineTests {14    @Suite struct ImagesIntoPDF {15        static let tinyWebP = "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA=="1617        static func fixture(_ format: FormatID) throws -> URL {18            switch format {19            case .png: return Fx.write([Fx.noise(240, 160, alpha: true)], "alpha.png", type: .png)20            case .jpeg: return Fx.write([Fx.noise(240, 160)], "photo.jpg", type: .jpeg)21            case .heic: return Fx.write([Fx.noise(240, 160)], "photo.heic", type: .heic)22            case .tiff: return Fx.write([Fx.noise(240, 160), Fx.noise(100, 300, seed: 5), Fx.halves(64, 64)], "frames.tiff", type: .tiff)23            case .gif: return Fx.write([Fx.halves(120, 80), Fx.noise(120, 80)], "anim.gif", type: .gif)24            case .bmp: return Fx.write([Fx.noise(240, 160)], "bitmap.bmp", type: .bmp)25            default:26                let url = Fx.dir("img").appendingPathComponent("tiny.webp")27                try #require(Data(base64Encoded: tinyWebP)).write(to: url)28                return url29            }30        }3132        @Test(arguments: ImagesToPDF.sourceFormats)33        func everySourceFormat(format: FormatID) async throws {34            let source = try ImagesIntoPDF.fixture(format)35            let size = try #require(CGImageSourceCreateWithURL(source as CFURL, nil).flatMap { CGImageSourceCreateImageAtIndex($0, 0, nil) }, "ImageIO cannot decode the \(format) fixture")36            let result = try await Fx.run(Fx.request(source, to: .pdf, from: format))37            let document = try #require(PDFDocument(url: result.file))38            #expect(document.pageCount == (format == .tiff ? 3 : 1))39            let box = try #require(document.page(at: 0)).bounds(for: .mediaBox)40            #expect(abs(box.width - CGFloat(size.width)) < 0.01 && abs(box.height - CGFloat(size.height)) < 0.01)      // 72 dpi: one point per pixel41            #expect(result.hasWarning("animation-first-frame") == (format == .gif))42            if format == .gif { #expect(Fx.engine.preflight(Fx.request(source, to: .pdf, from: format), inspection: nil).contains { $0.code == "animation-first-frame" }) }43            if format == .tiff {44                let second = try #require(document.page(at: 1)).bounds(for: .mediaBox)45                #expect(second.width == 100 && second.height == 300)46            }47            // The page shows the picture: compare a rendered pixel with the source.48            let rendered = try #require(Fx.load(try await Fx.run(Fx.request(result.file, to: .png, ["resolution.dpi": .int(72), "pages": .string("1")])).file))49            if format != .webp && format != .png {50                let a = Fx.pixel(rendered, size.width / 4, size.height / 2), b = Fx.pixel(size, size.width / 4, size.height / 2)51                #expect(abs(a.r - b.r) < 40 && abs(a.g - b.g) < 40 && abs(a.b - b.b) < 40, "\(format): rendered \(a) against \(b)")52            }53            let inspection = try await Fx.engine.inspect(source, format: format)54            #expect(inspection.pixelWidth == size.width && inspection.frameCount == (format == .tiff ? 3 : (format == .gif ? 2 : 1)))55        }5657        @Test func jpegIsEmbeddedWithoutRecompression() async throws {58            let source = Fx.write([Fx.noise(2400, 1600)], "big.jpg", type: .jpeg, properties: [kCGImageDestinationLossyCompressionQuality: 0.9])59            let bytes = Fx.size(source)60            let result = try await Fx.run(Fx.request(source, to: .pdf, from: .jpeg))61            let overhead = Fx.size(result.file) - bytes62            print("MEASURE images-to-pdf jpeg source=\(bytes) pdf=\(Fx.size(result.file)) overhead=\(overhead)")63            #expect(overhead > 0 && overhead < 8_192)64            #expect(result.output.facts["images.jpeg-passthrough"] == "1")65            // Extracting the image gives the source file back, byte for byte.66            let extracted = try await Fx.run(Fx.request(result.file, to: .folder, op: PDFEngine.Operation.extractImages))67            #expect(try Data(contentsOf: extracted.files[0]) == Data(contentsOf: source))68            // Recompression on request: smaller, counted, and no longer the same bytes.69            let smaller = try await Fx.run(Fx.request(source, to: .pdf, ["image.compression": .string("jpeg"), "quality": .double(0.3)], from: .jpeg))70            #expect(Fx.size(smaller.file) < bytes / 2 && smaller.output.facts["images.jpeg-recompressed"] == "1")71        }7273        @Test func losslessByDefaultAndJPEGOnRequest() async throws {74            let source = Fx.write([Fx.noise(800, 600)], "opaque.png", type: .png)75            let lossless = try await Fx.run(Fx.request(source, to: .pdf, from: .png))76            let lossy = try await Fx.run(Fx.request(source, to: .pdf, ["image.compression": .string("jpeg"), "quality": .double(0.5)], from: .png))77            #expect(lossless.output.facts["images.lossless"] == "1" && lossy.output.facts["images.jpeg-recompressed"] == "1")78            #expect(Fx.size(lossy.file) < Fx.size(lossless.file) / 2)79            // Lossless means pixel-exact: extract and compare.80            let extracted = try await Fx.run(Fx.request(lossless.file, to: .folder, op: PDFEngine.Operation.extractImages))81            let back = try #require(Fx.load(extracted.files[0])), original = try #require(Fx.load(source))82            for (x, y) in [(0, 0), (399, 300), (799, 599), (123, 456)] {83                let a = Fx.pixel(back, x, y), b = Fx.pixel(original, x, y)84                #expect(a.r == b.r && a.g == b.g && a.b == b.b)85            }86            // Transparency survives (soft mask), and stays lossless even when JPEG is requested.87            let alpha = Fx.write([Fx.noise(200, 100, alpha: true)], "alpha.png", type: .png)88            let kept = try await Fx.run(Fx.request(alpha, to: .pdf, ["image.compression": .string("jpeg")], from: .png))89            #expect(kept.output.facts["images.lossless"] == "1")90            let alphaBack = try await Fx.run(Fx.request(kept.file, to: .folder, op: PDFEngine.Operation.extractImages))91            let withAlpha = try #require(Fx.load(alphaBack.files[0]))92            #expect(Fx.pixel(withAlpha, 20, 50).a == 255 && abs(Fx.pixel(withAlpha, 180, 50).a - 96) <= 2)93        }9495        @Test(arguments: [1, 3, 6, 8])96        func exifOrientationIsApplied(orientation: Int) async throws {97            // Stored 200 × 100: red on the left, blue on the right.98            let source = Fx.write([Fx.halves(200, 100)], "o\(orientation).jpg", type: .jpeg, properties: [kCGImagePropertyOrientation: orientation])99            let result = try await Fx.run(Fx.request(source, to: .pdf, from: .jpeg))100            let rendered = try #require(Fx.load(try await Fx.run(Fx.request(result.file, to: .png, ["resolution.dpi": .int(72)])).file))101            func isRed(_ x: Int, _ y: Int) -> Bool { let p = Fx.pixel(rendered, x, y); return p.r > 180 && p.b < 80 }102            func isBlue(_ x: Int, _ y: Int) -> Bool { let p = Fx.pixel(rendered, x, y); return p.b > 180 && p.r < 80 }103            switch orientation {104            case 1: #expect(rendered.width == 200 && isRed(30, 50) && isBlue(170, 50))105            case 3: #expect(rendered.width == 200 && isBlue(30, 50) && isRed(170, 50))106            case 6: #expect(rendered.width == 100 && rendered.height == 200 && isRed(50, 30) && isBlue(50, 170))107            default: #expect(rendered.width == 100 && rendered.height == 200 && isBlue(50, 30) && isRed(50, 170))108            }109        }110111        @Test func pageSizesMarginsOrderAndPasswords() async throws {112            let wide = Fx.write([Fx.halves(400, 200)], "wide.jpg", type: .jpeg), tall = Fx.write([Fx.noise(100, 300)], "tall.png", type: .png)113            let a4 = try await Fx.run(Fx.request(wide, to: .pdf, ["page.size": .string("a4"), "page.margin": .double(36)], more: [tall], from: .jpeg))114            let document = try #require(PDFDocument(url: a4.file))115            let first = document.page(at: 0)!.bounds(for: .mediaBox), second = document.page(at: 1)!.bounds(for: .mediaBox)116            #expect(abs(first.width - 841.89) < 0.01 && abs(first.height - 595.276) < 0.01)      // landscape for the wide image117            #expect(abs(second.width - 595.276) < 0.01 && abs(second.height - 841.89) < 0.01)118            // Fit with a 36 pt margin: the image is centred, 769.89 pt wide; the margin stays white.119            let rendered = try #require(Fx.load(try await Fx.run(Fx.request(a4.file, to: .png, ["pages": .string("1"), "resolution.dpi": .int(72)])).file))120            #expect(Fx.pixel(rendered, 18, 297).r > 240 && Fx.pixel(rendered, 18, 297).b > 240)121            #expect(Fx.pixel(rendered, 60, 297).r > 180 && Fx.pixel(rendered, 60, 297).b < 80)122            #expect(Fx.pixel(rendered, 780, 297).b > 180)123            // Fill covers the content area (cropping the overflow).124            let fill = try await Fx.run(Fx.request(tall, to: .pdf, ["page.size": .string("letter"), "page.orientation": .string("landscape"), "image.placement": .string("fill")], from: .png))125            let filled = try #require(Fx.load(try await Fx.run(Fx.request(fill.file, to: .png, ["resolution.dpi": .int(72)])).file))126            #expect(filled.width == 792 && filled.height == 612 && Fx.pixel(filled, 5, 300).a == 255 && Fx.pixel(filled, 5, 300).r + Fx.pixel(filled, 5, 300).g < 500)127            let custom = try await Fx.run(Fx.request(tall, to: .pdf, ["page.size": .string("custom"), "page.width": .double(100), "page.height": .double(50), "page.orientation": .string("portrait")], from: .png))128            let box = try #require(PDFDocument(url: custom.file)?.page(at: 0)).bounds(for: .mediaBox)129            #expect(abs(box.width - 141.73) < 0.01 && abs(box.height - 283.46) < 0.01)130            // Resolution: 300 dpi halves… a 100 × 300 px image is 24 × 72 pt.131            let dpi = try await Fx.run(Fx.request(tall, to: .pdf, ["image.dpi": .int(300)], from: .png))132            let small = try #require(PDFDocument(url: dpi.file)?.page(at: 0)).bounds(for: .mediaBox)133            #expect(abs(small.width - 24) < 0.01 && abs(small.height - 72) < 0.01)134            let locked = try await Fx.run(Fx.request(tall, to: .pdf, ["output.password.user": .string("open-me"), "metadata.title": .string("Locked Title")], from: .png))135            let reopened = try #require(PDFDocument(url: locked.file))136            #expect(reopened.isLocked && reopened.unlock(withPassword: "open-me"))137            #expect(PDFInspector.infoDictionary(locked.file, password: "open-me")["Title"] == "Locked Title")138        }139140        @Test func optionalTextLayer() async throws {141            try await withVision {142                let scan = Fx.write([Fx.scanBitmap(dpi: 150)], "scan.png", type: .png)143                let result = try await Fx.run(Fx.request(scan, to: .pdf, ["ocr": .bool(true), "image.dpi": .int(150)], from: .png))144                let document = try #require(PDFDocument(url: result.file)), page = try #require(document.page(at: 0))145                #expect(page.bounds(for: .mediaBox).size == CGSize(width: 612, height: 792))146                let expected = Fx.scanProbeRects()147                for probe in Fx.scanProbes {148                    let selection = try #require(document.findString(probe, withOptions: []).first, "\(probe) not found")149                    let found = selection.bounds(for: page), want = expected[probe]!150                    #expect(max(abs(found.midX - want.midX), abs(found.midY - want.midY)) < 7, "\(probe): \(found) against \(want)")151                }152                #expect((Int(result.output.facts["ocr.lines"] ?? "0") ?? 0) >= 3)153            }154        }155156        @Test func rejectsWhatIsNotAnImage() async throws {157            let fake = Fx.dir("img").appendingPathComponent("fake.png")158            try Data("not an image at all".utf8).write(to: fake)159            await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(fake, to: .pdf, from: .png)) }160            let missing = Fx.dir("img").appendingPathComponent("missing.png")161            await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(missing, to: .pdf, from: .png)) }162            let good = Fx.write([Fx.noise(10, 10)], "good.png", type: .png)163            await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(good, to: .pdf, ["page.size": .string("custom"), "page.width": .double(1)], from: .png)) }164        }165    }166}167
Files main
Menu

Theme