Repository Public License
1// ORIX Convert — Packages/EnginePDF/Tests/EnginePDFTests/AssembleTests.swift2// Description: Merge, split, extract, delete, reorder, rotate, metadata, and what each operation keeps of a document3// with attachments, tags, XMP, forms and JavaScript.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import CoreGraphics7import PDFKit8import Testing9import ConvertCore10@testable import EnginePDF1112extension PDFEngineTests {13 @Suite struct PageOperations {14 typealias Op = PDFEngine.Operation1516 @Test func mergeKeepsOrderOutlineAndAnnotations() async throws {17 let rich = Fx.richPDF("alpha-rich.pdf"), beta = Fx.simplePDF("beta.pdf", pages: 3, word: "Beta"), gamma = Fx.simplePDF("gamma.pdf", pages: 2, word: "Gamma")18 let result = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.merge, more: [beta, gamma]))19 let document = try #require(PDFDocument(url: result.file))20 #expect(document.pageCount == 9)21 #expect(Fx.pdfText(result.file, page: 0).contains("Richdoc first page"))22 #expect(Fx.pdfText(result.file, page: 4).contains("BetaPAGE1") && Fx.pdfText(result.file, page: 6).contains("BetaPAGE3"))23 #expect(Fx.pdfText(result.file, page: 7).contains("GammaPAGE1") && Fx.pdfText(result.file, page: 8).contains("GammaPAGE2"))24 // Outline: one entry per file, the file's own outline nested below it.25 let root = try #require(document.outlineRoot)26 #expect((0..<root.numberOfChildren).map { root.child(at: $0)?.label } == ["alpha-rich", "beta", "gamma"])27 let first = try #require(root.child(at: 0))28 #expect((0..<first.numberOfChildren).map { first.child(at: $0)?.label } == ["Chapter One", "Chapter Two", "Chapter Three"])29 #expect(first.child(at: 1)?.child(at: 0)?.label == "Section 2.1")30 func target(_ item: PDFOutline?) -> Int? { item?.destination?.page.map { document.index(for: $0) } }31 #expect(target(root.child(at: 1)) == 4 && target(root.child(at: 2)) == 7 && target(first.child(at: 2)) == 3 && target(first.child(at: 1)?.child(at: 0)) == 2)32 #expect(result.output.facts["outline.entries"] == "7")33 // Annotations: web link, internal link (still pointing at the right page), form field with its value, square.34 let structure = Fx.structure(result.file)35 #expect(structure.links == 2 && structure.urlLinks == 1 && structure.gotoLinks == 1 && structure.widgets == 1 && structure.squares == 1 && structure.fieldValue == "FieldValue42")36 let jump = try #require(document.page(at: 0)?.annotations.first { ($0.action as? PDFActionGoTo) != nil || $0.destination != nil })37 let destination = jump.destination ?? (jump.action as? PDFActionGoTo)?.destination38 #expect(destination?.page.map { document.index(for: $0) } == 3)39 #expect(PDFInspector.infoDictionary(result.file, password: nil)["Title"] == "Rich Fixture")40 // Reverse order, no outline, new title.41 let reversed = try await Fx.run(Fx.request(gamma, to: .pdf, op: Op.merge, ["outline.keep": .bool(false), "metadata.title": .string("Merged Title")], more: [rich]))42 #expect(Fx.pdfText(reversed.file, page: 0).contains("GammaPAGE1") && Fx.pdfText(reversed.file, page: 2).contains("Richdoc first page"))43 #expect(Fx.structure(reversed.file).outline == 0)44 #expect(PDFInspector.infoDictionary(reversed.file, password: nil)["Title"] == "Merged Title")45 await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(rich, to: .pdf, op: Op.merge)) }46 }4748 @Test func splitModes() async throws {49 let rich = Fx.richPDF("split-rich.pdf")50 let every = try await Fx.run(Fx.request(rich, to: .folder, op: Op.split))51 #expect(every.files.map(\.lastPathComponent) == ["split-rich-001.pdf", "split-rich-002.pdf", "split-rich-003.pdf", "split-rich-004.pdf"])52 #expect(Fx.pdfText(every.files[2], page: 0).contains("third page"))53 #expect(Fx.structure(every.files[1]).widgets == 1 && Fx.structure(every.files[0]).urlLinks == 1)54 #expect(PDFInspector.infoDictionary(every.files[3], password: nil)["Title"] == "Rich Fixture")5556 let seven = Fx.simplePDF("seven.pdf", pages: 7, word: "Seven")57 let chunks = try await Fx.run(Fx.request(seven, to: .folder, op: Op.split, ["split.mode": .string("every-n"), "split.every": .int(3)]))58 #expect(chunks.files.map { Fx.structure($0).pages } == [3, 3, 1])59 #expect(Fx.pdfText(chunks.files[2], page: 0).contains("SevenPAGE7"))6061 let ranges = try await Fx.run(Fx.request(seven, to: .folder, op: Op.split, ["split.mode": .string("ranges"), "split.ranges": .string("1-2,4-")]))62 #expect(ranges.files.map { Fx.structure($0).pages } == [2, 4])63 let grouped = try await Fx.run(Fx.request(seven, to: .folder, op: Op.split, ["split.mode": .string("ranges"), "split.ranges": .string("1,3,1;2")]))64 #expect(grouped.files.map { Fx.structure($0).pages } == [3, 1])65 #expect(Fx.pdfText(grouped.files[0], page: 2).contains("SevenPAGE1") && Fx.pdfText(grouped.files[0], page: 1).contains("SevenPAGE3"))6667 let byOutline = try await Fx.run(Fx.request(rich, to: .folder, op: Op.split, ["split.mode": .string("outline")]))68 #expect(byOutline.files.map(\.lastPathComponent) == ["001-Chapter One.pdf", "002-Chapter Two.pdf", "003-Chapter Three.pdf"])69 #expect(byOutline.files.map { Fx.structure($0).pages } == [1, 2, 1])70 #expect(Fx.structure(byOutline.files[1]).outline == 2) // Chapter Two + Section 2.1 travel with their pages71 await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(seven, to: .folder, op: Op.split, ["split.mode": .string("outline")])) }72 await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(seven, to: .folder, op: Op.split, ["split.mode": .string("ranges"), "split.ranges": .string("1-9")])) }73 }7475 @Test func extractDeleteReorder() async throws {76 let rich = Fx.richPDF("pages-rich.pdf")77 let extracted = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.extractPages, ["pages": .string("3,1")]))78 #expect(Fx.structure(extracted.file).pages == 2)79 #expect(Fx.pdfText(extracted.file, page: 0).contains("third page") && Fx.pdfText(extracted.file, page: 1).contains("first page"))80 // Chapter One (page 1), Chapter Two (kept for its child) and Section 2.1 (page 3) survive; Chapter Three does not.81 #expect(Fx.structure(extracted.file).outline == 3)82 #expect(extracted.hasWarning("links-to-removed-pages"))83 await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(rich, to: .pdf, op: Op.extractPages)) }84 await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(rich, to: .pdf, op: Op.extractPages, ["pages": .string("5")])) }8586 let deleted = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.deletePages, ["pages": .string("2")]))87 #expect(Fx.structure(deleted.file).pages == 3 && Fx.pdfText(deleted.file, page: 1).contains("third page"))88 #expect(Fx.structure(deleted.file).widgets == 0 && Fx.structure(deleted.file).gotoLinks == 1)89 await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(rich, to: .pdf, op: Op.deletePages, ["pages": .string("1-4")])) }9091 let reversed = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.reorderPages))92 #expect(Fx.pdfText(reversed.file, page: 0).contains("fourth page") && Fx.pdfText(reversed.file, page: 3).contains("first page"))93 let before = Fx.structure(rich), after = Fx.structure(reversed.file)94 #expect(after == before)95 let partial = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.reorderPages, ["order": .string("3,1")]))96 #expect([0, 1, 2, 3].map { Fx.pdfText(partial.file, page: $0).contains(["third", "first", "second", "fourth"][$0] + " page") } == [true, true, true, true])97 await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(rich, to: .pdf, op: Op.reorderPages, ["order": .string("1,1")])) }98 }99100 @Test func rotationIsWrittenAsPageRotation() async throws {101 let pdf = Fx.textPDF("rotate.pdf", pages: [Fx.PageSpec(lines: ["Rotate one"]), Fx.PageSpec(lines: ["Rotate two"]), Fx.PageSpec(lines: ["Rotate three"])], rotations: [1: 270])102 let some = try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.rotate, ["pages": .string("1,2"), "rotate.angle": .string("90")]))103 let document = try #require(PDFDocument(url: some.file))104 #expect((0..<3).map { document.page(at: $0)?.rotation } == [90, 0, 0])105 #expect((0..<3).map { document.page(at: $0)!.pageRef!.rotationAngle } == [90, 0, 0])106 #expect(document.page(at: 0)?.bounds(for: .mediaBox).size == CGSize(width: 612, height: 792)) // stored box untouched107 #expect(Fx.pdfText(some.file, page: 0).contains("Rotate one"))108 let all = try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.rotate, ["rotate.angle": .string("180")]))109 #expect((0..<3).map { PDFDocument(url: all.file)?.page(at: $0)?.rotation } == [180, 90, 180])110 // A structured document keeps its outline, links and form field.111 let rich = Fx.richPDF("rotate-rich.pdf")112 let rotated = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.rotate, ["rotate.angle": .string("270")]))113 #expect(Fx.structure(rotated.file) == Fx.structure(rich))114 await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.rotate, ["rotate.angle": .string("45")])) }115 }116117 @Test func metadataCanBeSetAndStripped() async throws {118 let rich = Fx.richPDF("meta-rich.pdf")119 let set = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.setMetadata, [120 "metadata.title": .string("New Title é"), "metadata.subject": .string("A subject"), "metadata.keywords": .string("one, two"),121 "metadata.creator": .string("ORIX Convert tests"), "metadata.creation-date": .string("2024-02-29T12:00:00Z"),122 ]))123 let info = PDFInspector.infoDictionary(set.file, password: nil)124 #expect(info["Title"] == "New Title é" && info["Author"] == "ORIX Tests" && info["Subject"] == "A subject" && info["Creator"] == "ORIX Convert tests")125 #expect(info["Keywords"]?.contains("one") == true && info["Keywords"]?.contains("two") == true)126 #expect(info["CreationDate"] == "2024-02-29T12:00:00Z")127 #expect(Fx.structure(set.file) == Fx.structure(rich))128 let stripped = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.setMetadata, ["metadata.strip": .bool(true)]))129 let left = PDFInspector.infoDictionary(stripped.file, password: nil)130 #expect(left["Title"] == nil && left["Author"] == nil)131 print("MEASURE metadata-strip remaining-info-keys=\(left.keys.sorted())")132 let replaced = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.setMetadata, ["metadata.strip": .bool(true), "metadata.author": .string("Only Author")]))133 let only = PDFInspector.infoDictionary(replaced.file, password: nil)134 #expect(only["Author"] == "Only Author" && only["Title"] == nil)135 await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(rich, to: .pdf, op: Op.setMetadata)) }136 await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(rich, to: .pdf, op: Op.setMetadata, ["metadata.creation-date": .string("yesterday")])) }137 }138139 /// Measures what each PDF-producing operation keeps of a document with an attachment, a tag structure, XMP,140 /// an AcroForm, and JavaScript; the preflight warnings must predict exactly what is lost.141 @Test func featureRetentionMatchesThePreflightWarnings() async throws {142 let pdf = Fx.featurePDF()143 let before = PDFInspector.features(try #require(CGPDFDocument(pdf as CFURL)))144 #expect(before.hasAttachments && before.isTagged && before.hasStructureTree && before.hasXMP && before.hasAcroForm && before.formFields == 1 && before.hasJavaScript && before.annotations == 1)145 let other = Fx.simplePDF("other.pdf", pages: 1)146 let rich = Fx.richPDF("form-rich.pdf")147 let richForm = PDFInspector.features(try #require(CGPDFDocument(rich as CFURL)))148 let richMerged = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.merge, more: [other]))149 let richExtract = try await Fx.run(Fx.request(rich, to: .pdf, op: Op.extractPages, ["pages": .string("2")]))150 let mergedForm = PDFInspector.features(try #require(CGPDFDocument(richMerged.file as CFURL))), extractForm = PDFInspector.features(try #require(CGPDFDocument(richExtract.file as CFURL)))151 print("MEASURE acroform PDFKit-made field: source=\(richForm.hasAcroForm)/\(richForm.formFields) merge=\(mergedForm.hasAcroForm)/\(mergedForm.formFields) extract=\(extractForm.hasAcroForm)/\(extractForm.formFields) value=\(Fx.structure(richExtract.file).fieldValue ?? "nil")")152 let cases: [(String, ConversionRequest)] = [153 (Op.rotate, Fx.request(pdf, to: .pdf, op: Op.rotate)),154 (Op.setMetadata, Fx.request(pdf, to: .pdf, op: Op.setMetadata, ["metadata.title": .string("T")])),155 (Op.compress, Fx.request(pdf, to: .pdf, op: Op.compress, ["output.password.owner": .string("force-rewrite")])),156 (Op.extractPages, Fx.request(pdf, to: .pdf, op: Op.extractPages, ["pages": .string("1")])),157 (Op.reorderPages, Fx.request(pdf, to: .pdf, op: Op.reorderPages)),158 (Op.merge, Fx.request(pdf, to: .pdf, op: Op.merge, more: [other])),159 ]160 for (operation, request) in cases {161 let result = try await Fx.run(request)162 let document = try #require(CGPDFDocument(result.file as CFURL))163 if !document.isUnlocked { _ = document.unlockWithPassword("force-rewrite") }164 let after = PDFInspector.features(document)165 print("MEASURE retention \(operation): attachments=\(after.hasAttachments) tagged=\(after.isTagged) structTree=\(after.hasStructureTree) xmp=\(after.hasXMP) acroForm=\(after.hasAcroForm) fields=\(after.formFields) javascript=\(after.hasJavaScript) annotations=\(after.annotations) text=\(Fx.pdfText(result.file, page: 0, password: "force-rewrite").contains("Featureful"))")166 let predicted = PDFEngine.droppedFeatures(operation: operation, destination: .pdf, features: before)167 func predicts(_ word: String) -> Bool { predicted.contains { $0.contains(word) } }168 #expect(predicts("attachments") == !after.hasAttachments, "\(operation): attachments")169 #expect(predicts("tag structure") == !(after.isTagged || after.hasStructureTree), "\(operation): tags")170 #expect(predicts("XMP") == !after.hasXMP, "\(operation): XMP")171 #expect(predicts("JavaScript") == !after.hasJavaScript, "\(operation): JavaScript")172 #expect(predicts("form definition") == !after.hasAcroForm, "\(operation): AcroForm")173 #expect(after.annotations == 1, "\(operation): the form widget")174 let warned = Fx.engine.preflight(request, inspection: nil).filter { $0.code == "feature-dropped" }.count175 #expect(warned == predicted.count)176 }177 }178 }179}180