Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Tests/DocLayoutTests/PDFTests.swift3// Description: PDF output validation with PDFKit and Poppler's pdffonts/pdftotext: page count and size, selectable and searchable text,4// embedded fonts, hyperlinks, internal links, outline, metadata, images, structure tags, crop marks and page ranges.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Testing9import Foundation10import PDFKit11import CoreGraphics12import ImageIO13@testable import DocLayout14import DocModel15import DocTemplates1617func tool(_ path: String, _ args: [String], input: Data) -> String? {18 guard FileManager.default.isExecutableFile(atPath: path) else { return nil }19 let url = FileManager.default.temporaryDirectory.appendingPathComponent("orix-pdf-\(UUID().uuidString).pdf")20 try? input.write(to: url)21 defer { try? FileManager.default.removeItem(at: url) }22 let p = Process()23 p.executableURL = URL(fileURLWithPath: path)24 p.arguments = args.map { $0 == "@" ? url.path : $0 }25 let pipe = Pipe()26 p.standardOutput = pipe; p.standardError = Pipe()27 do { try p.run() } catch { return nil }28 let data = pipe.fileHandleForReading.readDataToEndOfFile()29 p.waitUntilExit()30 return String(decoding: data, as: UTF8.self)31}3233func pngData(width: Int, height: Int) -> Data {34 let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!35 ctx.setFillColor(CGColor(srgbRed: 0.2, green: 0.4, blue: 0.9, alpha: 1)); ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))36 ctx.setFillColor(CGColor(srgbRed: 1, green: 0.7, blue: 0.1, alpha: 1)); ctx.fillEllipse(in: CGRect(x: width / 4, y: height / 4, width: width / 2, height: height / 2))37 let data = NSMutableData()38 let dest = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil)!39 CGImageDestinationAddImage(dest, ctx.makeImage()!, nil)40 CGImageDestinationFinalize(dest)41 return data as Data42}4344@Suite struct PDFPublishingTests {45 func sample() -> DocumentModel {46 var doc = letterDoc([])47 doc.meta.title = "Quarterly Review"; doc.meta.author = "Ada Lovelace"; doc.meta.subject = "Testing"; doc.meta.keywords = ["orix", "pdf"]48 let h1 = Paragraph("Overview of the quarter", style: StyleID.heading(1))49 let h2 = Paragraph("Details and numbers", style: StyleID.heading(2), props: ParaProps(pageBreakBefore: true))50 let asset = Asset(mimeType: "image/png", data: pngData(width: 400, height: 240))51 doc.assets[asset.id] = asset52 doc.body = [53 .paragraph(h1),54 .paragraph(Paragraph(runs: [Run("Visit "), Run("the project site", props: CharProps(link: "https://example.org/orix")), Run(" or jump to "),55 Run("the details", props: CharProps(link: "#" + h2.id)), Run(". Unicode: café, naïve, Ωmega, 日本語, 😀.")])),56 .paragraph(Paragraph(runs: [Run(inline: .image(ImageObject(asset: asset.id, width: 200, height: 120, altText: "A blue rectangle with an amber disc")))])),57 .paragraph(Paragraph(runs: [Run("Energy is "), Run(inline: .equation(Equation(latex: "E = mc^2"))), Run(".")])),58 .paragraph(h2),59 .table(Table(strings: [["Item", "Amount"], ["Alpha", "12.50"], ["Beta", "7.25"]], width: 300)),60 longPara(4),61 ]62 return doc63 }6465 @Test func pagesTextAndMetadata() throws {66 let doc = sample()67 let result = PDFPublisher.publish(doc)68 let pdf = try #require(PDFDocument(data: result.data))69 #expect(pdf.pageCount == 2 && result.pageCount == 2)70 let box = try #require(pdf.page(at: 0)).bounds(for: .mediaBox)71 #expect(box.size == CGSize(width: 612, height: 792))72 let text = pdf.string ?? ""73 for needle in ["Overview of the quarter", "the project site", "café", "naïve", "日本語", "Details and numbers", "Alpha", "12.50"] {74 #expect(text.contains(needle), "PDF text should contain “\(needle)”")75 }76 // Text is searchable.77 #expect(!pdf.findString("Details and numbers", withOptions: []).isEmpty)78 let attrs = pdf.documentAttributes ?? [:]79 #expect(attrs[PDFDocumentAttribute.titleAttribute] as? String == "Quarterly Review")80 #expect(attrs[PDFDocumentAttribute.authorAttribute] as? String == "Ada Lovelace")81 #expect(attrs[PDFDocumentAttribute.creatorAttribute] as? String == "ORIX Docs")82 #expect((attrs[PDFDocumentAttribute.keywordsAttribute] as? [String])?.contains("orix") == true || (attrs[PDFDocumentAttribute.keywordsAttribute] as? String)?.contains("orix") == true)83 }8485 @Test func textIsVectorWithEmbeddedFonts() throws {86 let data = PDFPublisher.publish(sample()).data87 guard let fonts = tool("/opt/homebrew/bin/pdffonts", ["@"], input: data) else { print("ORIX-PDF-SKIP pdffonts not installed"); return }88 let rows = fonts.split(separator: "\n").dropFirst(2)89 #expect(rows.count >= 2, "the PDF should reference fonts (text is not rasterised)")90 for row in rows {91 let cols = row.split(separator: " ", omittingEmptySubsequences: true)92 // columns: name type… encoding emb sub uni object id — "emb" is the 5th from the end93 #expect(cols.count >= 6 && cols[cols.count - 5] == "yes", "font not embedded: \(row)")94 }95 // The equation is typeset with the math font, not drawn as an image.96 #expect(fonts.contains("Math"), "the equation's math font should be embedded")97 }9899 @Test func popplerExtractsTheSameText() throws {100 let data = PDFPublisher.publish(sample()).data101 guard let text = tool("/opt/homebrew/bin/pdftotext", ["-enc", "UTF-8", "@", "-"], input: data) else { print("ORIX-PDF-SKIP pdftotext not installed"); return }102 for needle in ["Overview of the quarter", "café", "Details and numbers", "Beta", "7.25"] { #expect(text.contains(needle)) }103 }104105 @Test func externalAndInternalLinks() throws {106 let pdf = try #require(PDFDocument(data: PDFPublisher.publish(sample()).data))107 let annotations = try #require(pdf.page(at: 0)).annotations.filter { $0.type == "Link" }108 #expect(annotations.contains { $0.url?.absoluteString == "https://example.org/orix" }, "external hyperlink missing")109 let internalLink = annotations.first { $0.url == nil }110 #expect(internalLink != nil, "internal link missing")111 if let dest = internalLink?.destination, let page = dest.page { #expect(pdf.index(for: page) == 1, "the internal link should lead to page 2") }112 else if let action = internalLink?.action as? PDFActionGoTo, let page = action.destination.page { #expect(pdf.index(for: page) == 1) }113 else { Issue.record("the internal link has no resolvable destination") }114 }115116 @Test func outlineMirrorsTheHeadings() throws {117 let pdf = try #require(PDFDocument(data: PDFPublisher.publish(sample()).data))118 let root = try #require(pdf.outlineRoot)119 #expect(root.numberOfChildren == 1)120 let first = try #require(root.child(at: 0))121 #expect(first.label == "Overview of the quarter" && first.numberOfChildren == 1)122 let child = try #require(first.child(at: 0))123 #expect(child.label == "Details and numbers")124 #expect(child.destination?.page.map { pdf.index(for: $0) } == 1)125 // The outline pass must not lose text or links.126 #expect((pdf.string ?? "").contains("Alpha"))127 #expect(pdf.page(at: 0)?.annotations.contains { $0.type == "Link" } == true)128 }129130 @Test func imagesKeepTheirResolution() throws {131 let data = PDFPublisher.publish(sample()).data132 guard let list = tool("/opt/homebrew/bin/pdfimages", ["-list", "@"], input: data) else { print("ORIX-PDF-SKIP pdfimages not installed"); return }133 #expect(list.contains(" 400 ") && list.contains(" 240 "), "the embedded image should keep its 400 × 240 pixels: \(list)")134 }135136 @Test func structureTagsArePresentWhenRequested() throws {137 var options = PDFOptions(); options.tagged = true; options.includeOutline = false138 let tagged = PDFPublisher.publish(sample(), options: options).data139 options.tagged = false140 let plain = PDFPublisher.publish(sample(), options: options).data141 let marker = Data("StructTreeRoot".utf8)142 #expect(tagged.range(of: marker) != nil, "a tagged PDF carries a structure tree")143 #expect(plain.range(of: marker) == nil)144 }145146 @Test func cropMarksEnlargeThePageAndDeclareTheTrimBox() throws {147 var options = PDFOptions(); options.cropMarks = true; options.bleed = 9148 let pdf = try #require(PDFDocument(data: PDFPublisher.publish(sample(), options: options).data))149 let page = try #require(pdf.page(at: 0))150 #expect(page.bounds(for: .mediaBox).size == CGSize(width: 612 + 66, height: 792 + 66))151 #expect(page.bounds(for: .trimBox) == CGRect(x: 33, y: 33, width: 612, height: 792))152 #expect(page.bounds(for: .bleedBox) == CGRect(x: 24, y: 24, width: 630, height: 810))153 }154155 @Test func pageRangeLimitsTheOutput() throws {156 var options = PDFOptions(); options.pageRange = 2...2157 let result = PDFPublisher.publish(sample(), options: options)158 let pdf = try #require(PDFDocument(data: result.data))159 #expect(pdf.pageCount == 1 && (pdf.string ?? "").contains("Details and numbers") && !(pdf.string ?? "").contains("Overview of the quarter"))160 }161162 @Test func pendingChangesArePublishedAsAcceptedWithoutTouchingTheDocument() throws {163 var doc = sample()164 doc.settings.trackChanges = true165 var editor = DocumentEditor(doc: doc, selection: Selection(caret: Position(block: 0, offset: 0)), author: "R")166 editor.insertText("INSERTED ")167 editor.selection = Selection(anchor: Position(block: 0, offset: 9), head: Position(block: 0, offset: 18))168 editor.deleteSelection()169 let before = editor.doc170 let pdf = try #require(PDFDocument(data: PDFPublisher.publish(editor.doc).data))171 let text = pdf.string ?? ""172 #expect(text.contains("INSERTED") && !text.contains("Overview of"), "deleted text must not be in the published PDF, even hidden")173 #expect(editor.doc == before)174 }175176 @Test func screenAndPrintLayoutsPaginateIdentically() {177 for id in ["academic-paper", "technical-manual", "thesis", "financial-report"] {178 let doc = TemplateLibrary.template(id: id)!.make(TemplateContext(author: "A", language: "en", paper: .letter))179 let screen = Paginator.layout(doc)180 let print = Paginator.layout(doc, options: PDFPublisher.layoutOptions)181 #expect(screen.pageCount == print.pageCount, "\(id)")182 #expect(screen.pageOfBlock == print.pageOfBlock, "\(id): a block lands on a different page on screen and in print")183 for (a, b) in zip(screen.pages, print.pages) {184 #expect(a.texts.count == b.texts.count)185 for (fa, fb) in zip(a.texts, b.texts) { #expect(fa.frame == fb.frame && fa.lines == fb.lines, "\(id): fragment geometry differs between screen and print") }186 }187 }188 }189}190