Commit 034081a872
Verified · cmc
Layout: unified · split
Sources/OrgApp/DocxWriter.swift +107 −20
| @@ -15,27 +15,52 @@ typealias DocxColor = UIColor | |||
| 15 | /// its `marker` alone. | 15 | /// its `marker` alone. |
| 16 | enum DocxWriter { | 16 | enum DocxWriter { |
| 17 | static func marker(_ index: Int) -> String { "\u{E000}\(index)\u{E001}" } | 17 | static func marker(_ index: Int) -> String { "\u{E000}\(index)\u{E001}" } |
| 18 | /// Put at the start of a heading's text: 0 for the title, 1 to 6 for Word's heading levels. | ||
| 19 | static func headingMarker(_ level: Int) -> String { "\u{E002}\(level)\u{E003}" } | ||
| 20 | /// Stands for `images[index]` in the text. | ||
| 21 | static func imageMarker(_ index: Int) -> String { "\u{E004}\(index)\u{E005}" } | ||
| 18 | 22 | ||
| 19 | static func data(from text: NSAttributedString, tables: [String] = []) -> Data { | 23 | /// A picture for the document: PNG, JPEG or GIF bytes and its size in pixels. |
| 24 | struct Image: Equatable { | ||
| 25 | let data: Data | ||
| 26 | let ext: String | ||
| 27 | let width: Int | ||
| 28 | let height: Int | ||
| 29 | } | ||
| 30 | |||
| 31 | /// EMUs to a pixel at 96 to the inch, and to a twip. | ||
| 32 | static let emuPerPixel = 9525, emuPerTwip = 635 | ||
| 33 | |||
| 34 | static func data(from text: NSAttributedString, tables: [String] = [], images: [Image] = []) -> Data { | ||
| 20 | var links: [String] = [] | 35 | var links: [String] = [] |
| 21 | let body = paragraphs(text, tables: tables, links: &links) | 36 | let letter = PDFExport.usesLetter() |
| 37 | let body = paragraphs(text, tables: tables, images: images, maxWidth: (letter ? 12240 : 11906) - 2 * 1134, links: &links) | ||
| 22 | let document = """ | 38 | let document = """ |
| 23 | <?xml version="1.0" encoding="UTF-8" standalone="yes"?> | 39 | <?xml version="1.0" encoding="UTF-8" standalone="yes"?> |
| 24 | <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" \ | 40 | <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" \ |
| 25 | xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>\(body)\ | 41 | xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" \ |
| 26 | \(section(letter: PDFExport.usesLetter()))\ | 42 | xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" \ |
| 43 | xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" \ | ||
| 44 | xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><w:body>\(body)\ | ||
| 45 | \(section(letter: letter))\ | ||
| 27 | </w:body></w:document> | 46 | </w:body></w:document> |
| 28 | """ | 47 | """ |
| 29 | let relationships = links.enumerated().map { index, url in | 48 | let relationships = "<Relationship Id=\"styles\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles\" Target=\"styles.xml\"/>" |
| 30 | "<Relationship Id=\"link\(index + 1)\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\" Target=\"\(escape(url))\" TargetMode=\"External\"/>" | 49 | + links.enumerated().map { index, url in |
| 31 | }.joined() | 50 | "<Relationship Id=\"link\(index + 1)\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\" Target=\"\(escape(url))\" TargetMode=\"External\"/>" |
| 51 | }.joined() | ||
| 52 | + images.enumerated().map { index, image in | ||
| 53 | "<Relationship Id=\"img\(index + 1)\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\" Target=\"media/image\(index + 1).\(image.ext)\"/>" | ||
| 54 | }.joined() | ||
| 55 | let mediaTypes = Set(images.map(\.ext)).sorted().map { "<Default Extension=\"\($0)\" ContentType=\"image/\($0)\"/>" }.joined() | ||
| 32 | var zip = ZipWriter() | 56 | var zip = ZipWriter() |
| 33 | zip.add("[Content_Types].xml", """ | 57 | zip.add("[Content_Types].xml", """ |
| 34 | <?xml version="1.0" encoding="UTF-8" standalone="yes"?> | 58 | <?xml version="1.0" encoding="UTF-8" standalone="yes"?> |
| 35 | <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\ | 59 | <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\ |
| 36 | <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\ | 60 | <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\ |
| 37 | <Default Extension="xml" ContentType="application/xml"/>\ | 61 | <Default Extension="xml" ContentType="application/xml"/>\(mediaTypes)\ |
| 38 | <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>\ | 62 | <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>\ |
| 63 | <Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>\ | ||
| 39 | </Types> | 64 | </Types> |
| 40 | """) | 65 | """) |
| 41 | zip.add("_rels/.rels", """ | 66 | zip.add("_rels/.rels", """ |
| @@ -49,9 +74,48 @@ enum DocxWriter { | |||
| 49 | <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\(relationships)</Relationships> | 74 | <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\(relationships)</Relationships> |
| 50 | """) | 75 | """) |
| 51 | zip.add("word/document.xml", document) | 76 | zip.add("word/document.xml", document) |
| 77 | zip.add("word/styles.xml", styles) | ||
| 78 | for (index, image) in images.enumerated() { zip.add("word/media/image\(index + 1).\(image.ext)", data: image.data) } | ||
| 52 | return zip.data() | 79 | return zip.data() |
| 53 | } | 80 | } |
| 54 | 81 | ||
| 82 | /// Normal, Title and Word's built-in heading 1 to 6, so the navigation pane, outline view | ||
| 83 | /// and contents fields see the headings. The runs keep their own fonts and colors. | ||
| 84 | static let styles: String = { | ||
| 85 | let headings = (1...6).map { level in | ||
| 86 | "<w:style w:type=\"paragraph\" w:styleId=\"Heading\(level)\"><w:name w:val=\"heading \(level)\"/><w:basedOn w:val=\"Normal\"/>" | ||
| 87 | + "<w:next w:val=\"Normal\"/><w:uiPriority w:val=\"9\"/><w:qFormat/><w:pPr><w:keepNext/><w:outlineLvl w:val=\"\(level - 1)\"/></w:pPr>" | ||
| 88 | + "<w:rPr><w:b/></w:rPr></w:style>" | ||
| 89 | }.joined() | ||
| 90 | return """ | ||
| 91 | <?xml version="1.0" encoding="UTF-8" standalone="yes"?> | ||
| 92 | <w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">\ | ||
| 93 | <w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Helvetica Neue" w:hAnsi="Helvetica Neue" w:cs="Helvetica Neue"/>\ | ||
| 94 | <w:sz w:val="22"/></w:rPr></w:rPrDefault><w:pPrDefault/></w:docDefaults>\ | ||
| 95 | <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>\ | ||
| 96 | <w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/>\ | ||
| 97 | <w:qFormat/><w:pPr><w:keepNext/></w:pPr><w:rPr><w:b/><w:sz w:val="40"/></w:rPr></w:style>\(headings)\ | ||
| 98 | </w:styles> | ||
| 99 | """ | ||
| 100 | }() | ||
| 101 | |||
| 102 | /// An inline picture, as wide as its pixels at 96 to the inch, or `maxWidth` twips if less. | ||
| 103 | static func drawing(_ image: Image, index: Int, maxWidth: Int) -> String { | ||
| 104 | var cx = image.width * emuPerPixel, cy = image.height * emuPerPixel | ||
| 105 | let limit = maxWidth * emuPerTwip | ||
| 106 | if cx > limit, cx > 0 { | ||
| 107 | cy = cy * limit / cx | ||
| 108 | cx = limit | ||
| 109 | } | ||
| 110 | let id = index + 1 | ||
| 111 | return "<w:drawing><wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\"><wp:extent cx=\"\(cx)\" cy=\"\(cy)\"/>" | ||
| 112 | + "<wp:docPr id=\"\(id)\" name=\"Picture \(id)\"/><a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" | ||
| 113 | + "<pic:pic><pic:nvPicPr><pic:cNvPr id=\"\(id)\" name=\"image\(id).\(image.ext)\"/><pic:cNvPicPr/></pic:nvPicPr>" | ||
| 114 | + "<pic:blipFill><a:blip r:embed=\"img\(id)\"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>" | ||
| 115 | + "<pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"\(cx)\" cy=\"\(cy)\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></pic:spPr>" | ||
| 116 | + "</pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing>" | ||
| 117 | } | ||
| 118 | |||
| 55 | /// The page: Letter or A4, as PDF export has it. Without a size, readers pick their own, and | 119 | /// The page: Letter or A4, as PDF export has it. Without a size, readers pick their own, and |
| 56 | /// Quick Look and Pages pick a narrow one. | 120 | /// Quick Look and Pages pick a narrow one. |
| 57 | static func section(letter: Bool) -> String { | 121 | static func section(letter: Bool) -> String { |
| @@ -76,7 +140,7 @@ enum DocxWriter { | |||
| 76 | return out + "</w:tbl>" | 140 | return out + "</w:tbl>" |
| 77 | } | 141 | } |
| 78 | 142 | ||
| 79 | private static func paragraphs(_ text: NSAttributedString, tables: [String], links: inout [String]) -> String { | 143 | private static func paragraphs(_ text: NSAttributedString, tables: [String], images: [Image], maxWidth: Int, links: inout [String]) -> String { |
| 80 | let string = text.string as NSString | 144 | let string = text.string as NSString |
| 81 | var out = "" | 145 | var out = "" |
| 82 | #if os(macOS) | 146 | #if os(macOS) |
| @@ -101,7 +165,7 @@ enum DocxWriter { | |||
| 101 | continue | 165 | continue |
| 102 | } | 166 | } |
| 103 | let style = text.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle | 167 | let style = text.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle |
| 104 | let paragraph = self.paragraph(text, range, style, links: &links) | 168 | let paragraph = self.paragraph(text, range, style, images: images, maxWidth: maxWidth, links: &links) |
| 105 | #if os(macOS) | 169 | #if os(macOS) |
| 106 | if let cell = style?.textBlocks.compactMap({ $0 as? NSTextTableBlock }).last { | 170 | if let cell = style?.textBlocks.compactMap({ $0 as? NSTextTableBlock }).last { |
| 107 | if table?.block !== cell.table { | 171 | if table?.block !== cell.table { |
| @@ -120,27 +184,35 @@ enum DocxWriter { | |||
| 120 | return out | 184 | return out |
| 121 | } | 185 | } |
| 122 | 186 | ||
| 123 | private static func paragraph(_ text: NSAttributedString, _ range: NSRange, _ style: NSParagraphStyle?, links: inout [String]) -> String { | 187 | private static func paragraph( |
| 188 | _ text: NSAttributedString, _ range: NSRange, _ style: NSParagraphStyle?, images: [Image], maxWidth: Int, links: inout [String] | ||
| 189 | ) -> String { | ||
| 190 | // In the order the schema has them: style, tabs, spacing, indentation, justification. | ||
| 124 | var properties = "" | 191 | var properties = "" |
| 192 | let content = (text.string as NSString).substring(with: range) | ||
| 193 | if let match = content.firstMatch(of: /^\s*\u{E002}(\d)\u{E003}/), let level = Int(match.1) { | ||
| 194 | properties += "<w:pStyle w:val=\"\(level == 0 ? "Title" : "Heading\(level)")\"/>" | ||
| 195 | } | ||
| 125 | if let style { | 196 | if let style { |
| 197 | if !style.tabStops.isEmpty { | ||
| 198 | properties += "<w:tabs>" + style.tabStops.map { "<w:tab w:val=\"left\" w:pos=\"\(Int($0.location * 20))\"/>" }.joined() + "</w:tabs>" | ||
| 199 | } | ||
| 200 | properties += "<w:spacing w:before=\"\(Int(style.paragraphSpacingBefore * 20))\" w:after=\"\(Int(style.paragraphSpacing * 20))\"/>" | ||
| 201 | let left = Int(style.headIndent * 20), first = Int((style.firstLineHeadIndent - style.headIndent) * 20) | ||
| 202 | if left != 0 || first != 0 { properties += "<w:ind w:left=\"\(left)\" \(first < 0 ? "w:hanging=\"\(-first)\"" : "w:firstLine=\"\(first)\"")/>" } | ||
| 126 | switch style.alignment { | 203 | switch style.alignment { |
| 127 | case .center: properties += "<w:jc w:val=\"center\"/>" | 204 | case .center: properties += "<w:jc w:val=\"center\"/>" |
| 128 | case .right: properties += "<w:jc w:val=\"right\"/>" | 205 | case .right: properties += "<w:jc w:val=\"right\"/>" |
| 129 | default: break | 206 | default: break |
| 130 | } | 207 | } |
| 131 | let left = Int(style.headIndent * 20), first = Int((style.firstLineHeadIndent - style.headIndent) * 20) | ||
| 132 | if left != 0 || first != 0 { properties += "<w:ind w:left=\"\(left)\" \(first < 0 ? "w:hanging=\"\(-first)\"" : "w:firstLine=\"\(first)\"")/>" } | ||
| 133 | properties += "<w:spacing w:before=\"\(Int(style.paragraphSpacingBefore * 20))\" w:after=\"\(Int(style.paragraphSpacing * 20))\"/>" | ||
| 134 | if !style.tabStops.isEmpty { | ||
| 135 | properties += "<w:tabs>" + style.tabStops.map { "<w:tab w:val=\"left\" w:pos=\"\(Int($0.location * 20))\"/>" }.joined() + "</w:tabs>" | ||
| 136 | } | ||
| 137 | } | 208 | } |
| 138 | var runs = "" | 209 | var runs = "" |
| 139 | text.enumerateAttributes(in: range, options: []) { attributes, runRange, _ in | 210 | text.enumerateAttributes(in: range, options: []) { attributes, runRange, _ in |
| 140 | var piece = (text.string as NSString).substring(with: runRange) | 211 | var piece = (text.string as NSString).substring(with: runRange) |
| 141 | piece = piece.trimmingCharacters(in: CharacterSet(charactersIn: "\n\r")) | 212 | piece = piece.trimmingCharacters(in: CharacterSet(charactersIn: "\n\r")) |
| 213 | piece = piece.replacing(/\u{E002}\d\u{E003}/, with: "") | ||
| 142 | guard !piece.isEmpty else { return } | 214 | guard !piece.isEmpty else { return } |
| 143 | var run = run(piece, attributes) | 215 | var run = run(piece, attributes, images: images, maxWidth: maxWidth) |
| 144 | let link = (attributes[.link] as? URL)?.absoluteString ?? (attributes[.link] as? String) | 216 | let link = (attributes[.link] as? URL)?.absoluteString ?? (attributes[.link] as? String) |
| 145 | if let link { | 217 | if let link { |
| 146 | links.append(link) | 218 | links.append(link) |
| @@ -151,7 +223,7 @@ enum DocxWriter { | |||
| 151 | return "<w:p><w:pPr>\(properties)</w:pPr>\(runs)</w:p>" | 223 | return "<w:p><w:pPr>\(properties)</w:pPr>\(runs)</w:p>" |
| 152 | } | 224 | } |
| 153 | 225 | ||
| 154 | private static func run(_ piece: String, _ attributes: [NSAttributedString.Key: Any]) -> String { | 226 | private static func run(_ piece: String, _ attributes: [NSAttributedString.Key: Any], images: [Image], maxWidth: Int) -> String { |
| 155 | var properties = "" | 227 | var properties = "" |
| 156 | if let font = attributes[.font] as? DocxFont { | 228 | if let font = attributes[.font] as? DocxFont { |
| 157 | let traits = self.traits(font) | 229 | let traits = self.traits(font) |
| @@ -175,8 +247,20 @@ enum DocxWriter { | |||
| 175 | if !textRun.isEmpty { content += "<w:t xml:space=\"preserve\">\(escape(textRun))</w:t>" } | 247 | if !textRun.isEmpty { content += "<w:t xml:space=\"preserve\">\(escape(textRun))</w:t>" } |
| 176 | textRun = "" | 248 | textRun = "" |
| 177 | } | 249 | } |
| 250 | // A picture's marker: its index between the two marker characters. | ||
| 251 | var picture: String? | ||
| 178 | for character in piece { | 252 | for character in piece { |
| 253 | if picture != nil { | ||
| 254 | if character == "\u{E005}" { | ||
| 255 | if let index = Int(picture!), images.indices.contains(index) { content += drawing(images[index], index: index, maxWidth: maxWidth) } | ||
| 256 | picture = nil | ||
| 257 | } else { | ||
| 258 | picture!.append(character) | ||
| 259 | } | ||
| 260 | continue | ||
| 261 | } | ||
| 179 | switch character { | 262 | switch character { |
| 263 | case "\u{E004}": flush(); picture = "" | ||
| 180 | case "\t": flush(); content += "<w:tab/>" | 264 | case "\t": flush(); content += "<w:tab/>" |
| 181 | case "\u{2028}", "\n": flush(); content += "<w:br/>" | 265 | case "\u{2028}", "\n": flush(); content += "<w:br/>" |
| 182 | default: textRun.append(character) | 266 | default: textRun.append(character) |
| @@ -225,7 +309,10 @@ struct ZipWriter { | |||
| 225 | private var archive = Data() | 309 | private var archive = Data() |
| 226 | 310 | ||
| 227 | mutating func add(_ name: String, _ text: String) { | 311 | mutating func add(_ name: String, _ text: String) { |
| 228 | let data = Data(text.utf8) | 312 | add(name, data: Data(text.utf8)) |
| 313 | } | ||
| 314 | |||
| 315 | mutating func add(_ name: String, data: Data) { | ||
| 229 | let nameData = Data(name.utf8) | 316 | let nameData = Data(name.utf8) |
| 230 | let crc = Self.crc32(data) | 317 | let crc = Self.crc32(data) |
| 231 | let offset = UInt32(archive.count) | 318 | let offset = UInt32(archive.count) |
Sources/OrgApp/OrgPreferences.swift +6
| @@ -74,6 +74,12 @@ public enum OrgPreferences { | |||
| 74 | return spec | 74 | return spec |
| 75 | } | 75 | } |
| 76 | 76 | ||
| 77 | /// `pdf-margin`, `pdf-font` and `pdf-page-numbers`. | ||
| 78 | @MainActor | ||
| 79 | public static func pdfOptions(_ defaults: UserDefaults = .standard) -> PDFExport.Options { | ||
| 80 | PDFExport.Options(margin: integer("pdfMargin", defaults), font: string("pdfFont", defaults), pageNumbers: bool("pdfPageNumbers", defaults)) | ||
| 81 | } | ||
| 82 | |||
| 77 | /// `show-markup`: link brackets and emphasis markers shown. | 83 | /// `show-markup`: link brackets and emphasis markers shown. |
| 78 | public static func showMarkup(_ defaults: UserDefaults = .standard) -> Bool { bool("showMarkup", defaults) } | 84 | public static func showMarkup(_ defaults: UserDefaults = .standard) -> Bool { bool("showMarkup", defaults) } |
| 79 | 85 | ||
Sources/OrgApp/PDFExport.swift +56 −10
| @@ -1,4 +1,5 @@ | |||
| 1 | import Foundation | 1 | import Foundation |
| 2 | import PDFKit | ||
| 2 | import WebKit | 3 | import WebKit |
| 3 | #if os(macOS) | 4 | #if os(macOS) |
| 4 | import AppKit | 5 | import AppKit |
| @@ -18,6 +19,50 @@ public enum PDFExport { | |||
| 18 | public let description: String | 19 | public let description: String |
| 19 | } | 20 | } |
| 20 | 21 | ||
| 22 | /// The page's margins in points, a font family for the text (empty: the export's own), and | ||
| 23 | /// whether pages are numbered. | ||
| 24 | public struct Options: Sendable, Equatable { | ||
| 25 | public var margin: Int | ||
| 26 | public var font: String | ||
| 27 | public var pageNumbers: Bool | ||
| 28 | public init(margin: Int = 50, font: String = "", pageNumbers: Bool = true) { | ||
| 29 | self.margin = margin | ||
| 30 | self.font = font | ||
| 31 | self.pageNumbers = pageNumbers | ||
| 32 | } | ||
| 33 | } | ||
| 34 | |||
| 35 | /// `printCSS` with the body font, when one is set. | ||
| 36 | static func css(_ options: Options) -> String { | ||
| 37 | guard !options.font.isEmpty else { return printCSS } | ||
| 38 | let family = options.font.replacingOccurrences(of: "\"", with: "") | ||
| 39 | return printCSS.replacingOccurrences(of: "</style>", with: "body { font-family: \"\(family)\", -apple-system, sans-serif; }\n</style>") | ||
| 40 | } | ||
| 41 | |||
| 42 | /// Each page's number, centred in its bottom margin, as an annotation: drawing it into the | ||
| 43 | /// page would mean drawing the page again and losing WebKit's links. | ||
| 44 | static func numberPages(_ data: Data, margin: Int) -> Data { | ||
| 45 | guard let document = PDFDocument(data: data) else { return data } | ||
| 46 | for index in 0..<document.pageCount { | ||
| 47 | guard let page = document.page(at: index) else { continue } | ||
| 48 | let box = page.bounds(for: .mediaBox) | ||
| 49 | let height: CGFloat = 14 | ||
| 50 | let bottom = box.minY + max(4, (CGFloat(margin) - height) / 2) | ||
| 51 | let note = PDFAnnotation(bounds: CGRect(x: box.midX - 40, y: bottom, width: 80, height: height), forType: .freeText, withProperties: nil) | ||
| 52 | note.contents = String(index + 1) | ||
| 53 | note.font = .systemFont(ofSize: 9) | ||
| 54 | note.fontColor = .gray | ||
| 55 | note.color = .clear | ||
| 56 | note.alignment = .center | ||
| 57 | let border = PDFBorder() | ||
| 58 | border.lineWidth = 0 | ||
| 59 | note.border = border | ||
| 60 | note.isReadOnly = true | ||
| 61 | page.addAnnotation(note) | ||
| 62 | } | ||
| 63 | return document.dataRepresentation() ?? data | ||
| 64 | } | ||
| 65 | |||
| 21 | /// Rules added for paper: the page's own width, light colors, and no breaks inside code, | 66 | /// Rules added for paper: the page's own width, light colors, and no breaks inside code, |
| 22 | /// tables and figures or right after a heading. | 67 | /// tables and figures or right after a heading. |
| 23 | static let printCSS = """ | 68 | static let printCSS = """ |
| @@ -33,8 +78,8 @@ public enum PDFExport { | |||
| 33 | 78 | ||
| 34 | /// The page `html` (an `HTMLExport.page`) as a PDF. `directory` is the Org file's folder, | 79 | /// The page `html` (an `HTMLExport.page`) as a PDF. `directory` is the Org file's folder, |
| 35 | /// where relative image links are read from. | 80 | /// where relative image links are read from. |
| 36 | public static func pdf(html: String, directory: URL?) async throws -> Data { | 81 | public static func pdf(html: String, directory: URL?, options: Options = Options()) async throws -> Data { |
| 37 | let page = html.replacingOccurrences(of: "</head>", with: printCSS + "\n</head>") | 82 | let page = html.replacingOccurrences(of: "</head>", with: css(options) + "\n</head>") |
| 38 | let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 800, height: 1100)) | 83 | let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 800, height: 1100)) |
| 39 | let loader = Loader() | 84 | let loader = Loader() |
| 40 | webView.navigationDelegate = loader | 85 | webView.navigationDelegate = loader |
| @@ -58,20 +103,21 @@ public enum PDFExport { | |||
| 58 | "if (window.MathJax && MathJax.startup && MathJax.startup.promise) { await MathJax.startup.promise; }", | 103 | "if (window.MathJax && MathJax.startup && MathJax.startup.promise) { await MathJax.startup.promise; }", |
| 59 | contentWorld: .page | 104 | contentWorld: .page |
| 60 | ) | 105 | ) |
| 61 | return try await render(webView) | 106 | let data = try await render(webView, margin: CGFloat(max(0, options.margin))) |
| 107 | return options.pageNumbers ? numberPages(data, margin: options.margin) : data | ||
| 62 | } | 108 | } |
| 63 | 109 | ||
| 64 | #if os(macOS) | 110 | #if os(macOS) |
| 65 | private static func render(_ webView: WKWebView) async throws -> Data { | 111 | private static func render(_ webView: WKWebView, margin: CGFloat) async throws -> Data { |
| 66 | let output = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString).pdf") | 112 | let output = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString).pdf") |
| 67 | defer { try? FileManager.default.removeItem(at: output) } | 113 | defer { try? FileManager.default.removeItem(at: output) } |
| 68 | let info = (NSPrintInfo.shared.copy() as? NSPrintInfo) ?? NSPrintInfo() | 114 | let info = (NSPrintInfo.shared.copy() as? NSPrintInfo) ?? NSPrintInfo() |
| 69 | info.jobDisposition = .save | 115 | info.jobDisposition = .save |
| 70 | info.dictionary()[NSPrintInfo.AttributeKey.jobSavingURL] = output | 116 | info.dictionary()[NSPrintInfo.AttributeKey.jobSavingURL] = output |
| 71 | info.topMargin = 50 | 117 | info.topMargin = margin |
| 72 | info.bottomMargin = 50 | 118 | info.bottomMargin = margin |
| 73 | info.leftMargin = 50 | 119 | info.leftMargin = margin |
| 74 | info.rightMargin = 50 | 120 | info.rightMargin = margin |
| 75 | info.horizontalPagination = .fit | 121 | info.horizontalPagination = .fit |
| 76 | info.verticalPagination = .automatic | 122 | info.verticalPagination = .automatic |
| 77 | info.isHorizontallyCentered = false | 123 | info.isHorizontallyCentered = false |
| @@ -103,13 +149,13 @@ public enum PDFExport { | |||
| 103 | } | 149 | } |
| 104 | } | 150 | } |
| 105 | #else | 151 | #else |
| 106 | private static func render(_ webView: WKWebView) async throws -> Data { | 152 | private static func render(_ webView: WKWebView, margin: CGFloat) async throws -> Data { |
| 107 | let letter = usesLetter() | 153 | let letter = usesLetter() |
| 108 | let paper = CGRect(x: 0, y: 0, width: letter ? 612 : 595.2, height: letter ? 792 : 841.8) | 154 | let paper = CGRect(x: 0, y: 0, width: letter ? 612 : 595.2, height: letter ? 792 : 841.8) |
| 109 | let renderer = UIPrintPageRenderer() | 155 | let renderer = UIPrintPageRenderer() |
| 110 | renderer.addPrintFormatter(webView.viewPrintFormatter(), startingAtPageAt: 0) | 156 | renderer.addPrintFormatter(webView.viewPrintFormatter(), startingAtPageAt: 0) |
| 111 | renderer.setValue(NSValue(cgRect: paper), forKey: "paperRect") | 157 | renderer.setValue(NSValue(cgRect: paper), forKey: "paperRect") |
| 112 | renderer.setValue(NSValue(cgRect: paper.insetBy(dx: 50, dy: 50)), forKey: "printableRect") | 158 | renderer.setValue(NSValue(cgRect: paper.insetBy(dx: margin, dy: margin)), forKey: "printableRect") |
| 113 | let data = NSMutableData() | 159 | let data = NSMutableData() |
| 114 | UIGraphicsBeginPDFContextToData(data, paper, nil) | 160 | UIGraphicsBeginPDFContextToData(data, paper, nil) |
| 115 | renderer.prepare(forDrawingPages: NSRange(location: 0, length: renderer.numberOfPages)) | 161 | renderer.prepare(forDrawingPages: NSRange(location: 0, length: renderer.numberOfPages)) |
Sources/OrgApp/RichTextExport.swift +58 −4
| @@ -1,4 +1,5 @@ | |||
| 1 | import Foundation | 1 | import Foundation |
| 2 | import ImageIO | ||
| 2 | #if os(macOS) | 3 | #if os(macOS) |
| 3 | import AppKit | 4 | import AppKit |
| 4 | #else | 5 | #else |
| @@ -49,16 +50,69 @@ public enum RichTextExport { | |||
| 49 | } | 50 | } |
| 50 | #endif | 51 | #endif |
| 51 | 52 | ||
| 52 | /// The HTML export as Word's `.docx`, tables included. | 53 | /// The HTML export as Word's `.docx`, with tables, heading styles and pictures. |
| 53 | public static func docx(html: String, directory: URL?) throws -> Data { | 54 | public static func docx(html: String, directory: URL?) throws -> Data { |
| 55 | let (marked, images) = markingHeadingsAndImages(html, directory: directory) | ||
| 54 | #if os(macOS) | 56 | #if os(macOS) |
| 55 | return try docx(attributed(html: html, directory: directory)) | 57 | return DocxWriter.data(from: try attributed(html: marked, directory: directory), images: images) |
| 56 | #else | 58 | #else |
| 57 | let (page, tables) = extractingTables(html) | 59 | let (page, tables) = extractingTables(marked) |
| 58 | return DocxWriter.data(from: try attributed(html: page, directory: directory), tables: tables) | 60 | return DocxWriter.data(from: try attributed(html: page, directory: directory), tables: tables, images: images) |
| 59 | #endif | 61 | #endif |
| 60 | } | 62 | } |
| 61 | 63 | ||
| 64 | /// `html` with each heading's text starting with `DocxWriter.headingMarker` (`<h1>` the | ||
| 65 | /// title, `<h2>` to `<h7>` Word's levels 1 to 6), and each local image replaced by | ||
| 66 | /// `DocxWriter.imageMarker` for the pictures returned: what the system's HTML import | ||
| 67 | /// leaves out or, on iOS, can't say. | ||
| 68 | static func markingHeadingsAndImages(_ html: String, directory: URL?) -> (html: String, images: [DocxWriter.Image]) { | ||
| 69 | var out = html.replacing(#/(?i)<h([1-7])\b([^>]*)>/#) { match in | ||
| 70 | let level = Int(match.1)! - 1 | ||
| 71 | return "<h\(match.1)\(match.2)>" + DocxWriter.headingMarker(min(level, 6)) | ||
| 72 | } | ||
| 73 | var images: [DocxWriter.Image] = [] | ||
| 74 | out = out.replacing(#/(?i)<img\b[^>]*>/#) { match in | ||
| 75 | let tag = String(match.0) | ||
| 76 | guard let src = tag.firstMatch(of: #/(?i)\bsrc="([^"]*)"/#).map({ decode(String($0.1)) }), | ||
| 77 | let image = image(src, width: tag.firstMatch(of: #/(?i)\bwidth="(\d+)/#).flatMap { Int($0.1) }, directory: directory) else { return tag } | ||
| 78 | images.append(image) | ||
| 79 | return DocxWriter.imageMarker(images.count - 1) | ||
| 80 | } | ||
| 81 | return (out, images) | ||
| 82 | } | ||
| 83 | |||
| 84 | /// A local image as Word takes it: PNG, JPEG or GIF as they are, other formats ImageIO | ||
| 85 | /// reads as PNG. `width` in pixels scales it, as `#+ATTR_HTML: :width` does on the page. | ||
| 86 | static func image(_ src: String, width: Int?, directory: URL?) -> DocxWriter.Image? { | ||
| 87 | let url: URL | ||
| 88 | if src.hasPrefix("file://") { | ||
| 89 | guard let file = URL(string: src) else { return nil } | ||
| 90 | url = file | ||
| 91 | } else if src.contains("://") || src.hasPrefix("data:") { | ||
| 92 | return nil | ||
| 93 | } else { | ||
| 94 | let path = src.removingPercentEncoding ?? src | ||
| 95 | if path.hasPrefix("/") { url = URL(fileURLWithPath: path) } else if let directory { url = directory.appendingPathComponent(path) } else { return nil } | ||
| 96 | } | ||
| 97 | guard let data = try? Data(contentsOf: url), let source = CGImageSourceCreateWithData(data as CFData, nil), | ||
| 98 | let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], | ||
| 99 | let pixelWidth = properties[kCGImagePropertyPixelWidth] as? Int, let pixelHeight = properties[kCGImagePropertyPixelHeight] as? Int, | ||
| 100 | pixelWidth > 0, pixelHeight > 0 else { return nil } | ||
| 101 | let (w, h) = width.map { ($0, pixelHeight * $0 / pixelWidth) } ?? (pixelWidth, pixelHeight) | ||
| 102 | switch CGImageSourceGetType(source) as String? { | ||
| 103 | case "public.png": return DocxWriter.Image(data: data, ext: "png", width: w, height: h) | ||
| 104 | case "public.jpeg": return DocxWriter.Image(data: data, ext: "jpeg", width: w, height: h) | ||
| 105 | case "com.compuserve.gif": return DocxWriter.Image(data: data, ext: "gif", width: w, height: h) | ||
| 106 | default: | ||
| 107 | let png = NSMutableData() | ||
| 108 | guard let image = CGImageSourceCreateImageAtIndex(source, 0, nil), | ||
| 109 | let destination = CGImageDestinationCreateWithData(png, "public.png" as CFString, 1, nil) else { return nil } | ||
| 110 | CGImageDestinationAddImage(destination, image, nil) | ||
| 111 | guard CGImageDestinationFinalize(destination) else { return nil } | ||
| 112 | return DocxWriter.Image(data: png as Data, ext: "png", width: w, height: h) | ||
| 113 | } | ||
| 114 | } | ||
| 115 | |||
| 62 | /// `html` with each `<table>` replaced by a paragraph holding `DocxWriter.marker`, and the | 116 | /// `html` with each `<table>` replaced by a paragraph holding `DocxWriter.marker`, and the |
| 63 | /// tables as Word XML, header cells bold. | 117 | /// tables as Word XML, header cells bold. |
| 64 | static func extractingTables(_ html: String) -> (html: String, tables: [String]) { | 118 | static func extractingTables(_ html: String) -> (html: String, tables: [String]) { |
Sources/OrgApp/UserConfig.swift +6
| @@ -314,6 +314,12 @@ public enum UserConfig { | |||
| 314 | Setting(section: "orgstar", key: "option-as-meta", defaultsKey: "optionAsMeta", | 314 | Setting(section: "orgstar", key: "option-as-meta", defaultsKey: "optionAsMeta", |
| 315 | kind: .integerChoice([("left", 1), ("right", 2), ("both", 3), ("none", 0)]), fallback: .string("left"), | 315 | kind: .integerChoice([("left", 1), ("right", 2), ("both", 3), ("none", 0)]), fallback: .string("left"), |
| 316 | comment: "left, right, both or none", legacy: "general.option-as-meta"), | 316 | comment: "left, right, both or none", legacy: "general.option-as-meta"), |
| 317 | Setting(section: "orgstar", key: "pdf-margin", defaultsKey: "pdfMargin", kind: .integer, fallback: .integer(50), | ||
| 318 | comment: "PDF export's page margins, in points", legacy: ""), | ||
| 319 | Setting(section: "orgstar", key: "pdf-font", defaultsKey: "pdfFont", kind: .string, fallback: .string(""), | ||
| 320 | comment: "a font family for PDF export's text; \"\" for the export's own", legacy: ""), | ||
| 321 | Setting(section: "orgstar", key: "pdf-page-numbers", defaultsKey: "pdfPageNumbers", kind: .bool, fallback: .bool(true), | ||
| 322 | comment: "number PDF export's pages", legacy: ""), | ||
| 317 | Setting(section: "orgstar", key: "tab-bar", defaultsKey: "showTabBar", kind: .bool, fallback: .bool(false), | 323 | Setting(section: "orgstar", key: "tab-bar", defaultsKey: "showTabBar", kind: .bool, fallback: .bool(false), |
| 318 | comment: "a tab for each open buffer above the editor (View ▸ Show Tab Bar)", legacy: ""), | 324 | comment: "a tab for each open buffer above the editor (View ▸ Show Tab Bar)", legacy: ""), |
| 319 | Setting(section: "orgstar", key: "show-markup", defaultsKey: "showMarkup", kind: .bool, fallback: .bool(false), | 325 | Setting(section: "orgstar", key: "show-markup", defaultsKey: "showMarkup", kind: .bool, fallback: .bool(false), |
Sources/Orgstar/ContentView.swift +2 −2
| @@ -606,8 +606,8 @@ struct ContentView: View { | |||
| 606 | do { | 606 | do { |
| 607 | let data: Data | 607 | let data: Data |
| 608 | switch format { | 608 | switch format { |
| 609 | case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory) | 609 | case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions()) |
| 610 | case "docx": data = try RichTextExport.docx(RichTextExport.attributed(html: html, directory: directory)) | 610 | case "docx": data = try RichTextExport.docx(html: html, directory: directory) |
| 611 | case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory)) | 611 | case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory)) |
| 612 | default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8) | 612 | default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8) |
| 613 | } | 613 | } |
Sources/Orgstar/ExportSheet.swift +12
| @@ -12,6 +12,9 @@ struct ExportSheet: View { | |||
| 12 | @AppStorage("exportFormat") private var format = "html" | 12 | @AppStorage("exportFormat") private var format = "html" |
| 13 | @AppStorage("exportOpenAfter") private var openAfter = false | 13 | @AppStorage("exportOpenAfter") private var openAfter = false |
| 14 | @AppStorage("exportBodyOnly") private var bodyOnly = false | 14 | @AppStorage("exportBodyOnly") private var bodyOnly = false |
| 15 | @AppStorage("pdfMargin") private var pdfMargin = 50 | ||
| 16 | @AppStorage("pdfFont") private var pdfFont = "" | ||
| 17 | @AppStorage("pdfPageNumbers") private var pdfPageNumbers = true | ||
| 15 | @State private var subtree = false | 18 | @State private var subtree = false |
| 16 | @State private var destination: URL? | 19 | @State private var destination: URL? |
| 17 | @Environment(\.dismiss) private var dismiss | 20 | @Environment(\.dismiss) private var dismiss |
| @@ -42,6 +45,15 @@ struct ExportSheet: View { | |||
| 42 | Toggle("Body only", isOn: $bodyOnly) | 45 | Toggle("Body only", isOn: $bodyOnly) |
| 43 | .disabled(!allowsBodyOnly) | 46 | .disabled(!allowsBodyOnly) |
| 44 | .help("Leave out the title and page wrapper, as Org's body-only export") | 47 | .help("Leave out the title and page wrapper, as Org's body-only export") |
| 48 | if format == "print-pdf" { | ||
| 49 | Stepper("Margins: \(pdfMargin) pt", value: $pdfMargin, in: 18...144, step: 6) | ||
| 50 | Picker("Font", selection: $pdfFont) { | ||
| 51 | Text("The export's own").tag("") | ||
| 52 | Divider() | ||
| 53 | ForEach(NSFontManager.shared.availableFontFamilies, id: \.self) { Text($0).tag($0) } | ||
| 54 | } | ||
| 55 | Toggle("Page numbers", isOn: $pdfPageNumbers) | ||
| 56 | } | ||
| 45 | LabeledContent("Destination") { | 57 | LabeledContent("Destination") { |
| 46 | HStack { | 58 | HStack { |
| 47 | Text(chosen.path(percentEncoded: false)).lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary) | 59 | Text(chosen.path(percentEncoded: false)).lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary) |
Sources/OrgstarMobile/ExportMenu.swift +1 −1
| @@ -94,7 +94,7 @@ struct OrgExport: Transferable { | |||
| 94 | let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage()) | 94 | let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage()) |
| 95 | let directory = URL(fileURLWithPath: path).deletingLastPathComponent() | 95 | let directory = URL(fileURLWithPath: path).deletingLastPathComponent() |
| 96 | let data: Data = switch format { | 96 | let data: Data = switch format { |
| 97 | case .pdf: try await PDFExport.pdf(html: html, directory: directory) | 97 | case .pdf: try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions()) |
| 98 | case .rtf: try await RichTextExport.rtf(html: html, directory: directory) | 98 | case .rtf: try await RichTextExport.rtf(html: html, directory: directory) |
| 99 | default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8) | 99 | default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8) |
| 100 | } | 100 | } |
Tests/OrgAppTests/PDFExportTests.swift +13
| @@ -17,5 +17,18 @@ struct PDFExportTests { | |||
| 17 | #expect(text.contains("Long") && text.contains("Section 40") && text.contains("echo done")) | 17 | #expect(text.contains("Long") && text.contains("Section 40") && text.contains("echo done")) |
| 18 | let page = try #require(document.page(at: 0)).bounds(for: .mediaBox) | 18 | let page = try #require(document.page(at: 0)).bounds(for: .mediaBox) |
| 19 | #expect(page.width < page.height) | 19 | #expect(page.width < page.height) |
| 20 | // Page numbers, centred under the text, as annotations so the export's links stay. | ||
| 21 | let numbers = (0..<document.pageCount).compactMap { document.page(at: $0)?.annotations.first { $0.type == "FreeText" }?.contents } | ||
| 22 | #expect(numbers == (1...document.pageCount).map(String.init)) | ||
| 23 | } | ||
| 24 | |||
| 25 | @Test func marginsFontAndNoNumbers() async throws { | ||
| 26 | let html = HTMLExport.page("#+TITLE: Short\nOne paragraph.\n", fallbackTitle: "t") | ||
| 27 | let data = try await PDFExport.pdf(html: html, directory: nil, options: PDFExport.Options(margin: 100, font: "Georgia", pageNumbers: false)) | ||
| 28 | let document = try #require(PDFDocument(data: data)) | ||
| 29 | #expect(document.page(at: 0)?.annotations.contains { $0.type == "FreeText" } == false) | ||
| 30 | let css = PDFExport.css(PDFExport.Options(margin: 100, font: "Georgia", pageNumbers: false)) | ||
| 31 | #expect(css.contains("font-family: \"Georgia\"")) | ||
| 32 | #expect(!PDFExport.css(PDFExport.Options()).contains("font-family")) | ||
| 20 | } | 33 | } |
| 21 | } | 34 | } |
Tests/OrgAppTests/RichTextExportTests.swift +23
| @@ -52,6 +52,29 @@ struct RichTextExportTests { | |||
| 52 | #expect(RichTextExport.decode("a &lt; éA "") == "a < éA \"") | 52 | #expect(RichTextExport.decode("a &lt; éA "") == "a < éA \"") |
| 53 | } | 53 | } |
| 54 | 54 | ||
| 55 | /// Headings get Word's heading styles, so its navigation pane and contents fields see them, | ||
| 56 | /// and image links come through as pictures. | ||
| 57 | @Test func wordHeadingStylesAndImages() throws { | ||
| 58 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-docx-\(UUID().uuidString)") | ||
| 59 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) | ||
| 60 | defer { try? FileManager.default.removeItem(at: folder) } | ||
| 61 | let rep = try #require(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 40, pixelsHigh: 20, bitsPerSample: 8, samplesPerPixel: 4, | ||
| 62 | hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)) | ||
| 63 | try #require(rep.representation(using: .png, properties: [:])).write(to: folder.appendingPathComponent("red.png")) | ||
| 64 | let html = HTMLExport.page("#+TITLE: Report\n* Results\nText.\n** Detail\n[[file:red.png]]\n", fallbackTitle: "t") | ||
| 65 | let data = try RichTextExport.docx(html: html, directory: folder) | ||
| 66 | let xml = String(decoding: data, as: UTF8.self) | ||
| 67 | #expect(xml.contains("word/styles.xml") && xml.contains("w:styleId=\"Heading1\"") && xml.contains("<w:name w:val=\"heading 1\"/>")) | ||
| 68 | #expect(xml.contains("<w:pStyle w:val=\"Title\"/>")) | ||
| 69 | #expect(xml.contains("<w:pStyle w:val=\"Heading1\"/>") && xml.contains("<w:pStyle w:val=\"Heading2\"/>")) | ||
| 70 | #expect(!xml.contains("\u{E002}") && !xml.contains("\u{E004}")) | ||
| 71 | #expect(xml.contains("word/media/image1.png") && xml.contains("<w:drawing>") && xml.contains("r:embed=\"img1\"")) | ||
| 72 | // 40 by 20 pixels at 96 to the inch. | ||
| 73 | #expect(xml.contains("cx=\"381000\" cy=\"190500\"")) | ||
| 74 | let back = try NSAttributedString(data: data, options: [:], documentAttributes: nil).string | ||
| 75 | #expect(back.contains("Results") && back.contains("Detail") && back.contains("Text.")) | ||
| 76 | } | ||
| 77 | |||
| 55 | @Test func wordPagesAreLetterOrA4() { | 78 | @Test func wordPagesAreLetterOrA4() { |
| 56 | #expect(PDFExport.usesLetter("US") && !PDFExport.usesLetter("DE") && !PDFExport.usesLetter(nil)) | 79 | #expect(PDFExport.usesLetter("US") && !PDFExport.usesLetter("DE") && !PDFExport.usesLetter(nil)) |
| 57 | #expect(DocxWriter.section(letter: true).contains("<w:pgSz w:w=\"12240\" w:h=\"15840\"/>")) | 80 | #expect(DocxWriter.section(letter: true).contains("<w:pgSz w:w=\"12240\" w:h=\"15840\"/>")) |
docs/manual/guide/12-export.org +8 −2
| @@ -37,9 +37,10 @@ All fourteen commands are in File ▸ Export and in the command palette. They wr | |||
| 37 | - *Scope*: the whole file, or the subtree at the caret (Org's =C-s= in the dispatcher). A subtree is exported as a document of its own: its heading is the title, its text the body, and its child headings move up a level. iCalendar is the exception: there the subtree's heading is an entry like any other. The file's =#+= keywords still apply, and the heading's =EXPORT_TITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_EMAIL=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS=, =EXPORT_EXCLUDE_TAGS=, =EXPORT_HTML_HEAD= and =EXPORT_HTML_HEAD_EXTRA= properties override them. Its planning line and property drawer are left out. The choice is available when the caret is under a heading. | 37 | - *Scope*: the whole file, or the subtree at the caret (Org's =C-s= in the dispatcher). A subtree is exported as a document of its own: its heading is the title, its text the body, and its child headings move up a level. iCalendar is the exception: there the subtree's heading is an entry like any other. The file's =#+= keywords still apply, and the heading's =EXPORT_TITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_EMAIL=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS=, =EXPORT_EXCLUDE_TAGS=, =EXPORT_HTML_HEAD= and =EXPORT_HTML_HEAD_EXTRA= properties override them. Its planning line and property drawer are left out. The choice is available when the caret is under a heading. |
| 38 | - *Body only*: leave out the title and the page around the text (Org's =C-b=). HTML is then the table of contents, the text and the footnotes, without =<html>=, =<head>= or the title; Markdown has no title heading. Not available for PDF, Word, RTF, plain text, ODT and iCalendar. | 38 | - *Body only*: leave out the title and the page around the text (Org's =C-b=). HTML is then the table of contents, the text and the footnotes, without =<html>=, =<head>= or the title; Markdown has no title heading. Not available for PDF, Word, RTF, plain text, ODT and iCalendar. |
| 39 | - *Destination*: where =#+EXPORT_FILE_NAME:= says, or the subtree's =EXPORT_FILE_NAME= property for a subtree, else beside the Org file. *Choose…* picks another place and name. Changing the format changes the extension. | 39 | - *Destination*: where =#+EXPORT_FILE_NAME:= says, or the subtree's =EXPORT_FILE_NAME= property for a subtree, else beside the Org file. *Choose…* picks another place and name. Changing the format changes the extension. |
| 40 | - *Margins*, *Font* and *Page numbers*, for PDF: see /PDF export/. | ||
| 40 | - *Open after export*: opens the file in its default app when the export finishes. | 41 | - *Open after export*: opens the file in its default app when the export finishes. |
| 41 | 42 | ||
| 42 | The dialog remembers the format and the *Open after export* setting. | 43 | The dialog remembers the format and the *Open after export* setting. The PDF settings are =config.toml= settings, and apply to every PDF export. |
| 43 | 44 | ||
| 44 | ** On iOS | 45 | ** On iOS |
| 45 | 46 | ||
| @@ -208,12 +209,17 @@ Export to PDF makes the HTML export into a PDF, laid out and split into pages by | |||
| 208 | - Colors are always the light ones, whatever the system's appearance. | 209 | - Colors are always the light ones, whatever the system's appearance. |
| 209 | - Pages are US Letter where that is the usual size and A4 elsewhere; on the Mac, the paper size set for printing. | 210 | - Pages are US Letter where that is the usual size and A4 elsewhere; on the Mac, the paper size set for printing. |
| 210 | - Code blocks, tables, figures and quotes are kept on one page when they fit, and a heading is not left at the bottom of a page. | 211 | - Code blocks, tables, figures and quotes are kept on one page when they fit, and a heading is not left at the bottom of a page. |
| 212 | - Margins are 50 points on every side (=pdf-margin= under =[orgstar]= in =config.toml=; Margins in the Export dialog). | ||
| 213 | - The text is in the export's own font, or the family =pdf-font= names (Font in the dialog). Code stays monospaced. | ||
| 214 | - Each page's number is centred in its bottom margin (=pdf-page-numbers=; Page numbers in the dialog). The numbers are annotations on the pages, so the table of contents and other links keep working. | ||
| 211 | 215 | ||
| 212 | For typeset output with LaTeX's classes and packages, use Export to PDF with Emacs instead (see /Exporting through Emacs/). | 216 | For typeset output with LaTeX's classes and packages, use Export to PDF with Emacs instead (see /Exporting through Emacs/). |
| 213 | 217 | ||
| 214 | * Word, RTF and plain text | 218 | * Word, RTF and plain text |
| 215 | 219 | ||
| 216 | Export to Word, Export to RTF and Export to Plain Text make the HTML export into a document of that kind, as the system reads HTML: headings, emphasis, links, colored keywords and code, lists, and tables. Word files (=.docx=) are written by orgstar itself, so tables come through as Word tables; RTF keeps them too on the Mac. On iOS, where the system's HTML reader keeps no tables, Word's tables are made from the HTML export's tables, with header cells bold and the cells' text without its styles; RTF and plain text there have the cells' text but no table. Plain text is the same text without its styles: list bullets and table cells are kept, separated by tabs. Fonts are Helvetica Neue for text and Menlo for code, and the colors are the light ones. Images are not included. | 220 | Export to Word, Export to RTF and Export to Plain Text make the HTML export into a document of that kind, as the system reads HTML: headings, emphasis, links, colored keywords and code, lists, and tables. Word files (=.docx=) are written by orgstar itself, so tables come through as Word tables; RTF keeps them too on the Mac. On iOS, where the system's HTML reader keeps no tables, Word's tables are made from the HTML export's tables, with header cells bold and the cells' text without its styles; RTF and plain text there have the cells' text but no table. Plain text is the same text without its styles: list bullets and table cells are kept, separated by tabs. Fonts are Helvetica Neue for text and Menlo for code, and the colors are the light ones. |
| 221 | |||
| 222 | In Word files, the title has Word's Title style and headings have its Heading 1 to Heading 6 styles, so Word's navigation pane, outline view and contents fields find them. Images from =file:= links come through as pictures, as wide as their pixels at 96 to the inch, scaled to =#+ATTR_HTML: :width= when it is set, and no wider than the page. PNG, JPEG and GIF go in as they are; other formats the system can read, such as HEIC, WebP and TIFF, go in as PNG. SVG and images at web addresses are left out. RTF and plain text have no images. | ||
| 217 | 223 | ||
| 218 | For Org's own ASCII layout, with underlined headings and drawn tables, use Export to Plain Text with Emacs. | 224 | For Org's own ASCII layout, with underlined headings and drawn tables, use Export to Plain Text with Emacs. |
| 219 | 225 | ||
docs/manual/guide/13-configuration.org +4
| @@ -165,6 +165,7 @@ These settings have no control in the Settings window. Some are in the View menu | |||
| 165 | | =org-cycle-hide-block-startup= | | | 165 | | =org-cycle-hide-block-startup= | | |
| 166 | | =electric-pair-mode= | | | 166 | | =electric-pair-mode= | | |
| 167 | | =display-line-numbers-type= | View ▸ Show Line Numbers (=⇧⌘L=), View ▸ Line Numbers | | 167 | | =display-line-numbers-type= | View ▸ Show Line Numbers (=⇧⌘L=), View ▸ Line Numbers | |
| 168 | | =pdf-margin=, =pdf-font=, =pdf-page-numbers= | File ▸ Export ▸ Export… (the dialog's PDF settings) | | ||
| 168 | | =tab-bar= | View ▸ Show Tab Bar | | 169 | | =tab-bar= | View ▸ Show Tab Bar | |
| 169 | | =show-markup= | View ▸ Show Markup (=⇧⌘M=) | | 170 | | =show-markup= | View ▸ Show Markup (=⇧⌘M=) | |
| 170 | | =ignored-folders= | | | 171 | | =ignored-folders= | | |
| @@ -377,6 +378,9 @@ Any other key in =[theme]= is a color; see Themes below. | |||
| 377 | | =save= | string | ="automatic"= | =automatic= (one second after typing stops) or =explicit= (only with =⌘S=). | | 378 | | =save= | string | ="automatic"= | =automatic= (one second after typing stops) or =explicit= (only with =⌘S=). | |
| 378 | | =keymap= | string | ="emacs"= | =emacs=, =mac= or =doom=. Your own bindings go in =keymap.toml=. | | 379 | | =keymap= | string | ="emacs"= | =emacs=, =mac= or =doom=. Your own bindings go in =keymap.toml=. | |
| 379 | | =option-as-meta= | string | ="left"= | Which Option key is Meta: =left=, =right=, =both= or =none=. | | 380 | | =option-as-meta= | string | ="left"= | Which Option key is Meta: =left=, =right=, =both= or =none=. | |
| 381 | | =pdf-margin= | integer | =50= | PDF export's page margins, in points. | | ||
| 382 | | =pdf-font= | string | =""= | A font family for PDF export's text; =""= keeps the export's own. | | ||
| 383 | | =pdf-page-numbers= | boolean | =true= | Number PDF export's pages. | | ||
| 380 | | =tab-bar= | boolean | =false= | A tab for each open buffer above the editor. | | 384 | | =tab-bar= | boolean | =false= | A tab for each open buffer above the editor. | |
| 381 | | =show-markup= | boolean | =false= | Show link brackets and emphasis markers. | | 385 | | =show-markup= | boolean | =false= | Show link brackets and emphasis markers. | |
| 382 | | =show-hidden-files= | boolean | =true= | List dotfiles and dot folders in your folders. | | 386 | | =show-hidden-files= | boolean | =true= | List dotfiles and dot folders in your folders. | |
docs/manual/guide/14-ios.org +2 −1
| @@ -328,7 +328,7 @@ The app icon's badge counts the entries in the agenda's Overdue section that are | |||
| 328 | 328 | ||
| 329 | Export (in the reader's toolbar and the editor's More menu) offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text and iCalendar, and Copy as Rich Text. Each opens the share sheet with a file named after the org file, which you can send to another app or keep with Save to Files. The export reads the file's setup files and follows its export keywords, as the Mac's export does. | 329 | Export (in the reader's toolbar and the editor's More menu) offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text and iCalendar, and Copy as Rich Text. Each opens the share sheet with a file named after the org file, which you can send to another app or keep with Save to Files. The export reads the file's setup files and follows its export keywords, as the Mac's export does. |
| 330 | 330 | ||
| 331 | ODT, LaTeX, ASCII and PDF through LaTeX aren't available on iOS. See [[file:12-export.org][Export]]. | 331 | PDF export follows =pdf-margin=, =pdf-font= and =pdf-page-numbers= in =config.toml=, and Word files get heading styles and the file's images, as on the Mac. ODT, LaTeX, ASCII and PDF through LaTeX aren't available on iOS. See [[file:12-export.org][Export]]. |
| 332 | 332 | ||
| 333 | * Code blocks and tables | 333 | * Code blocks and tables |
| 334 | 334 | ||
| @@ -402,6 +402,7 @@ These settings from =config.toml= apply on iOS: | |||
| 402 | - =org-todo-keywords=, =org-list-allow-alphabetical= | 402 | - =org-todo-keywords=, =org-list-allow-alphabetical= |
| 403 | - =org-tags-column=, =org-insert-heading-respect-content=, =org-M-RET-may-split-line=, =fill-column= | 403 | - =org-tags-column=, =org-insert-heading-respect-content=, =org-M-RET-may-split-line=, =fill-column= |
| 404 | - =org-hide-emphasis-markers= and =org-pretty-entities=, for what hidden markup shows and for how tag and table alignment and filling measure text, as on the Mac | 404 | - =org-hide-emphasis-markers= and =org-pretty-entities=, for what hidden markup shows and for how tag and table alignment and filling measure text, as on the Mac |
| 405 | - =pdf-margin=, =pdf-font=, =pdf-page-numbers= | ||
| 405 | - =show-markup=, =org-startup-indented=, =org-hide-leading-stars=, =org-startup-with-inline-images=, =org-startup-with-latex-preview=, =org-startup-align-all-tables=, =org-startup-truncated=, =org-cycle-hide-drawer-startup=, =org-cycle-hide-block-startup= | 406 | - =show-markup=, =org-startup-indented=, =org-hide-leading-stars=, =org-startup-with-inline-images=, =org-startup-with-latex-preview=, =org-startup-align-all-tables=, =org-startup-truncated=, =org-cycle-hide-drawer-startup=, =org-cycle-hide-block-startup= |
| 406 | - =[theme]= (=font=, =body-font=, =font-size=, =line-spacing=, =text-width=, =heading-size-step=, =theme-file= and colours), =[theme.light]=, =[theme.dark]=, =[theme.todo]=, =[theme.category]= | 407 | - =[theme]= (=font=, =body-font=, =font-size=, =line-spacing=, =text-width=, =heading-size-step=, =theme-file= and colours), =[theme.light]=, =[theme.dark]=, =[theme.todo]=, =[theme.category]= |
| 407 | - =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer= | 408 | - =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer= |