SPB Git

Repository Public

DocumentConverter.swift 6.6 KB 112 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocAutomation/DocumentConverter.swift3// Description: One entry point for reading and writing every supported format (native, DOCX, RTF, text, Markdown, HTML, PDF),4//              shared by the application, the workflow engine and the command-line tool.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel10import DocContainer11import DocDOCX12import DocFormats13import DocLayout14import DocReferences1516public enum DocumentConverter {17    /// Formats that can be opened.18    public static let importFormats: [DocFormat] = [.orixdoc, .docx, .rtf, .txt, .markdown, .html, .pdf]19    /// Formats that can be written.20    public static let exportFormats: [DocFormat] = [.orixdoc, .docx, .pdf, .rtf, .markdown, .html, .txt]2122    /// Reads a document. `baseURL` is the folder of the source file: Markdown and HTML may reference images next to it23    /// (only files inside that folder are read; remote resources are never fetched).24    public static func importDocument(_ data: Data, format: DocFormat, baseURL: URL? = nil) throws -> ImportResult {25        switch format {26        case .docx:27            return try DocxImporter.importDocument(data)28        case .orixdoc:29            do { return try NativeContainer.read(data) } catch let strict {30                // A damaged file is opened as far as it can be, and says so.31                guard var recovered = try? NativeContainer.recover(data) else { throw strict }32                recovered.warnings.insert(FormatWarning(.dropped, feature: "Damaged document", detail: "The file failed its integrity check (\(strict)). What could be read was recovered; save it under a new name."), at: 0)33                return recovered34            }35        default:36            let loader: ((String) -> Data?)? = baseURL.map { base in37                { path in DocumentConverter.confinedResource(path, in: base) }38            }39            return try DocumentIO.importDocument(data, format: format, resourceLoader: loader)40        }41    }4243    /// Reads a file referenced by an imported document, only when it really lies inside `folder`:44    /// symbolic links are resolved first and the comparison is made on whole path components, so neither `../folder-other/x`45    /// nor a link pointing outside can escape. Remote references are never fetched.46    static func confinedResource(_ path: String, in folder: URL) -> Data? {47        guard !path.contains("://"), !path.hasPrefix("/"), !path.hasPrefix("~") else { return nil }48        let root = folder.standardizedFileURL.resolvingSymlinksInPath()49        let target = root.appendingPathComponent(path.removingPercentEncoding ?? path).standardizedFileURL.resolvingSymlinksInPath()50        let rootParts = root.pathComponents, parts = target.pathComponents51        guard parts.count > rootParts.count, Array(parts.prefix(rootParts.count)) == rootParts else { return nil }52        guard let values = try? target.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey]), values.isRegularFile == true,53              let size = values.fileSize, size < 64 * 1024 * 1024 else { return nil }54        return try? Data(contentsOf: target)55    }5657    public static func importDocument(at url: URL) throws -> ImportResult {58        guard let format = DocFormat(fileExtension: url.pathExtension) else { throw FormatError.unreadable("Unknown file type “.\(url.pathExtension)”.") }59        var result = try importDocument(try Data(contentsOf: url), format: format, baseURL: url.deletingLastPathComponent())60        if result.document.meta.title.isEmpty, format != .orixdoc { result.document.meta.title = url.deletingPathExtension().lastPathComponent }61        return result62    }6364    /// What exporting to `format` would lose or approximate. Shown before the export happens.65    public static func preflight(_ doc: DocumentModel, format: DocFormat) -> [FormatWarning] {66        switch format {67        case .docx: return DocxExporter.preflight(doc)68        case .orixdoc: return []69        case .pdf:70            var w: [FormatWarning] = []71            if doc.hasTrackedChanges { w.append(FormatWarning(.info, feature: "Tracked changes", detail: "The PDF shows the document as if every pending change were accepted.")) }72            if !doc.comments.isEmpty { w.append(FormatWarning(.info, feature: "Comments", detail: "Comments are not included in the PDF.", count: doc.comments.count)) }73            let missing = FontCache.shared.missingFamilies74            if !missing.isEmpty { w.append(FormatWarning(.approximated, feature: "Missing fonts", detail: "Not installed, replaced by a substitute: " + missing.joined(separator: ", "))) }75            return w76        default: return DocumentIO.preflight(doc, format: format)77        }78    }7980    public static func export(_ doc: DocumentModel, format: DocFormat, pdfOptions: PDFOptions = PDFOptions()) throws -> ExportResult {81        let engine = CitationEngine(document: doc)82        switch format {83        case .orixdoc:84            return ExportResult(data: try NativeContainer.write(doc))85        case .docx:86            // Page numbers of cross-references and the contents are written as cached field results.87            let layout = Paginator.layout(doc, citations: engine, options: PDFPublisher.layoutOptions)88            var options = DocxExportOptions()89            options.citations = engine90            options.pageCount = layout.pageCount91            let pages = Dictionary(uniqueKeysWithValues: layout.pageOfBlock.map { ($0.key, layout.pages[$0.value].numberText) })92            options.pageOf = { pages[$0] }93            return try DocxExporter.export(doc, options: options)94        case .pdf:95            let r = PDFPublisher.publish(doc, citations: engine, options: pdfOptions)96            return ExportResult(data: r.data, warnings: preflight(doc, format: .pdf) + r.notes.map { FormatWarning(.approximated, feature: "PDF", detail: $0) })97        default:98            var options = ExportOptions()99            options.citations = engine100            options.mathML = { latex, display in MathConverter.mathML(fromLatex: latex, display: display) }101            return try DocumentIO.export(doc, format: format, options: options)102        }103    }104105    public static func export(_ doc: DocumentModel, to url: URL, pdfOptions: PDFOptions = PDFOptions()) throws -> [FormatWarning] {106        guard let format = DocFormat(fileExtension: url.pathExtension) else { throw FormatError.unreadable("Unknown file type “.\(url.pathExtension)”.") }107        let result = try export(doc, format: format, pdfOptions: pdfOptions)108        try result.data.write(to: url, options: .atomic)109        return result.warnings110    }111}112
Files main
Menu

Theme