Word export with heading styles and images; PDF margins, font and page numbers !341

merged merged by cmc on 2026-10-14 04:31 UTC · krz/orgstar:docx-pdf into main

13 files changed, +298 −40

Layout: unified · split

Sources/OrgApp/DocxWriter.swift +107 −20
@@ -15,27 +15,52 @@ typealias DocxColor = UIColor
1515/// its `marker` alone.
1616enum DocxWriter {
1717 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}" }
1822
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 {
2035 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)
2238 let document = """
2339 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2440 <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" \
25 xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>\(body)\
26 \(section(letter: PDFExport.usesLetter()))\
41 xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" \
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))\
2746 </w:body></w:document>
2847 """
29 let relationships = links.enumerated().map { index, url in
30 "<Relationship Id=\"link\(index + 1)\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\" Target=\"\(escape(url))\" TargetMode=\"External\"/>"
31 }.joined()
48 let relationships = "<Relationship Id=\"styles\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles\" Target=\"styles.xml\"/>"
49 + links.enumerated().map { index, url in
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()
3256 var zip = ZipWriter()
3357 zip.add("[Content_Types].xml", """
3458 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
3559 <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\
3660 <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)\
3862 <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"/>\
3964 </Types>
4065 """)
4166 zip.add("_rels/.rels", """
@@ -49,9 +74,48 @@ enum DocxWriter {
4974 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\(relationships)</Relationships>
5075 """)
5176 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) }
5279 return zip.data()
5380 }
5481
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
55119 /// The page: Letter or A4, as PDF export has it. Without a size, readers pick their own, and
56120 /// Quick Look and Pages pick a narrow one.
57121 static func section(letter: Bool) -> String {
@@ -76,7 +140,7 @@ enum DocxWriter {
76140 return out + "</w:tbl>"
77141 }
78142
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 {
80144 let string = text.string as NSString
81145 var out = ""
82146 #if os(macOS)
@@ -101,7 +165,7 @@ enum DocxWriter {
101165 continue
102166 }
103167 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)
105169 #if os(macOS)
106170 if let cell = style?.textBlocks.compactMap({ $0 as? NSTextTableBlock }).last {
107171 if table?.block !== cell.table {
@@ -120,27 +184,35 @@ enum DocxWriter {
120184 return out
121185 }
122186
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.
124191 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 }
125196 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)\"")/>" }
126203 switch style.alignment {
127204 case .center: properties += "<w:jc w:val=\"center\"/>"
128205 case .right: properties += "<w:jc w:val=\"right\"/>"
129206 default: break
130207 }
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 }
137208 }
138209 var runs = ""
139210 text.enumerateAttributes(in: range, options: []) { attributes, runRange, _ in
140211 var piece = (text.string as NSString).substring(with: runRange)
141212 piece = piece.trimmingCharacters(in: CharacterSet(charactersIn: "\n\r"))
213 piece = piece.replacing(/\u{E002}\d\u{E003}/, with: "")
142214 guard !piece.isEmpty else { return }
143 var run = run(piece, attributes)
215 var run = run(piece, attributes, images: images, maxWidth: maxWidth)
144216 let link = (attributes[.link] as? URL)?.absoluteString ?? (attributes[.link] as? String)
145217 if let link {
146218 links.append(link)
@@ -151,7 +223,7 @@ enum DocxWriter {
151223 return "<w:p><w:pPr>\(properties)</w:pPr>\(runs)</w:p>"
152224 }
153225
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 {
155227 var properties = ""
156228 if let font = attributes[.font] as? DocxFont {
157229 let traits = self.traits(font)
@@ -175,8 +247,20 @@ enum DocxWriter {
175247 if !textRun.isEmpty { content += "<w:t xml:space=\"preserve\">\(escape(textRun))</w:t>" }
176248 textRun = ""
177249 }
250 // A picture's marker: its index between the two marker characters.
251 var picture: String?
178252 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 }
179262 switch character {
263 case "\u{E004}": flush(); picture = ""
180264 case "\t": flush(); content += "<w:tab/>"
181265 case "\u{2028}", "\n": flush(); content += "<w:br/>"
182266 default: textRun.append(character)
@@ -225,7 +309,10 @@ struct ZipWriter {
225309 private var archive = Data()
226310
227311 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) {
229316 let nameData = Data(name.utf8)
230317 let crc = Self.crc32(data)
231318 let offset = UInt32(archive.count)
Sources/OrgApp/OrgPreferences.swift +6
@@ -74,6 +74,12 @@ public enum OrgPreferences {
7474 return spec
7575 }
7676
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
7783 /// `show-markup`: link brackets and emphasis markers shown.
7884 public static func showMarkup(_ defaults: UserDefaults = .standard) -> Bool { bool("showMarkup", defaults) }
7985
Sources/OrgApp/PDFExport.swift +56 −10
@@ -1,4 +1,5 @@
11import Foundation
2import PDFKit
23import WebKit
34#if os(macOS)
45import AppKit
@@ -18,6 +19,50 @@ public enum PDFExport {
1819 public let description: String
1920 }
2021
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
2166 /// Rules added for paper: the page's own width, light colors, and no breaks inside code,
2267 /// tables and figures or right after a heading.
2368 static let printCSS = """
@@ -33,8 +78,8 @@ public enum PDFExport {
3378
3479 /// The page `html` (an `HTMLExport.page`) as a PDF. `directory` is the Org file's folder,
3580 /// where relative image links are read from.
36 public static func pdf(html: String, directory: URL?) async throws -> Data {
37 let page = html.replacingOccurrences(of: "</head>", with: printCSS + "\n</head>")
81 public static func pdf(html: String, directory: URL?, options: Options = Options()) async throws -> Data {
82 let page = html.replacingOccurrences(of: "</head>", with: css(options) + "\n</head>")
3883 let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 800, height: 1100))
3984 let loader = Loader()
4085 webView.navigationDelegate = loader
@@ -58,20 +103,21 @@ public enum PDFExport {
58103 "if (window.MathJax && MathJax.startup && MathJax.startup.promise) { await MathJax.startup.promise; }",
59104 contentWorld: .page
60105 )
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
62108 }
63109
64110 #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 {
66112 let output = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString).pdf")
67113 defer { try? FileManager.default.removeItem(at: output) }
68114 let info = (NSPrintInfo.shared.copy() as? NSPrintInfo) ?? NSPrintInfo()
69115 info.jobDisposition = .save
70116 info.dictionary()[NSPrintInfo.AttributeKey.jobSavingURL] = output
71 info.topMargin = 50
72 info.bottomMargin = 50
73 info.leftMargin = 50
74 info.rightMargin = 50
117 info.topMargin = margin
118 info.bottomMargin = margin
119 info.leftMargin = margin
120 info.rightMargin = margin
75121 info.horizontalPagination = .fit
76122 info.verticalPagination = .automatic
77123 info.isHorizontallyCentered = false
@@ -103,13 +149,13 @@ public enum PDFExport {
103149 }
104150 }
105151 #else
106 private static func render(_ webView: WKWebView) async throws -> Data {
152 private static func render(_ webView: WKWebView, margin: CGFloat) async throws -> Data {
107153 let letter = usesLetter()
108154 let paper = CGRect(x: 0, y: 0, width: letter ? 612 : 595.2, height: letter ? 792 : 841.8)
109155 let renderer = UIPrintPageRenderer()
110156 renderer.addPrintFormatter(webView.viewPrintFormatter(), startingAtPageAt: 0)
111157 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")
113159 let data = NSMutableData()
114160 UIGraphicsBeginPDFContextToData(data, paper, nil)
115161 renderer.prepare(forDrawingPages: NSRange(location: 0, length: renderer.numberOfPages))
Sources/OrgApp/RichTextExport.swift +58 −4
@@ -1,4 +1,5 @@
11import Foundation
2import ImageIO
23#if os(macOS)
34import AppKit
45#else
@@ -49,16 +50,69 @@ public enum RichTextExport {
4950 }
5051 #endif
5152
52 /// The HTML export as Word's `.docx`, tables included.
53 /// The HTML export as Word's `.docx`, with tables, heading styles and pictures.
5354 public static func docx(html: String, directory: URL?) throws -> Data {
55 let (marked, images) = markingHeadingsAndImages(html, directory: directory)
5456 #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)
5658 #else
57 let (page, tables) = extractingTables(html)
58 return DocxWriter.data(from: try attributed(html: page, directory: directory), tables: tables)
59 let (page, tables) = extractingTables(marked)
60 return DocxWriter.data(from: try attributed(html: page, directory: directory), tables: tables, images: images)
5961 #endif
6062 }
6163
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
62116 /// `html` with each `<table>` replaced by a paragraph holding `DocxWriter.marker`, and the
63117 /// tables as Word XML, header cells bold.
64118 static func extractingTables(_ html: String) -> (html: String, tables: [String]) {
Sources/OrgApp/UserConfig.swift +6
@@ -314,6 +314,12 @@ public enum UserConfig {
314314 Setting(section: "orgstar", key: "option-as-meta", defaultsKey: "optionAsMeta",
315315 kind: .integerChoice([("left", 1), ("right", 2), ("both", 3), ("none", 0)]), fallback: .string("left"),
316316 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: ""),
317323 Setting(section: "orgstar", key: "tab-bar", defaultsKey: "showTabBar", kind: .bool, fallback: .bool(false),
318324 comment: "a tab for each open buffer above the editor (View ▸ Show Tab Bar)", legacy: ""),
319325 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 {
606606 do {
607607 let data: Data
608608 switch format {
609 case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory)
610 case "docx": data = try RichTextExport.docx(RichTextExport.attributed(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(html: html, directory: directory)
611611 case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
612612 default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
613613 }
Sources/Orgstar/ExportSheet.swift +12
@@ -12,6 +12,9 @@ struct ExportSheet: View {
1212 @AppStorage("exportFormat") private var format = "html"
1313 @AppStorage("exportOpenAfter") private var openAfter = false
1414 @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
1518 @State private var subtree = false
1619 @State private var destination: URL?
1720 @Environment(\.dismiss) private var dismiss
@@ -42,6 +45,15 @@ struct ExportSheet: View {
4245 Toggle("Body only", isOn: $bodyOnly)
4346 .disabled(!allowsBodyOnly)
4447 .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 }
4557 LabeledContent("Destination") {
4658 HStack {
4759 Text(chosen.path(percentEncoded: false)).lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary)
Sources/OrgstarMobile/ExportMenu.swift +1 −1
@@ -94,7 +94,7 @@ struct OrgExport: Transferable {
9494 let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
9595 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
9696 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())
9898 case .rtf: try await RichTextExport.rtf(html: html, directory: directory)
9999 default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8)
100100 }
Tests/OrgAppTests/PDFExportTests.swift +13
@@ -17,5 +17,18 @@ struct PDFExportTests {
1717 #expect(text.contains("Long") && text.contains("Section 40") && text.contains("echo done"))
1818 let page = try #require(document.page(at: 0)).bounds(for: .mediaBox)
1919 #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"))
2033 }
2134}
Tests/OrgAppTests/RichTextExportTests.swift +23
@@ -52,6 +52,29 @@ struct RichTextExportTests {
5252 #expect(RichTextExport.decode("a &amp;lt; &#233;&#x41; &quot;") == "a &lt; éA \"")
5353 }
5454
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
5578 @Test func wordPagesAreLetterOrA4() {
5679 #expect(PDFExport.usesLetter("US") && !PDFExport.usesLetter("DE") && !PDFExport.usesLetter(nil))
5780 #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
3737- *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.
3838- *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.
3939- *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/.
4041- *Open after export*: opens the file in its default app when the export finishes.
4142
42The dialog remembers the format and the *Open after export* setting.
43The dialog remembers the format and the *Open after export* setting. The PDF settings are =config.toml= settings, and apply to every PDF export.
4344
4445** On iOS
4546
@@ -208,12 +209,17 @@ Export to PDF makes the HTML export into a PDF, laid out and split into pages by
208209- Colors are always the light ones, whatever the system's appearance.
209210- Pages are US Letter where that is the usual size and A4 elsewhere; on the Mac, the paper size set for printing.
210211- 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.
211215
212216For typeset output with LaTeX's classes and packages, use Export to PDF with Emacs instead (see /Exporting through Emacs/).
213217
214218* Word, RTF and plain text
215219
216Export 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.
220Export 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
222In 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.
217223
218224For Org's own ASCII layout, with underlined headings and drawn tables, use Export to Plain Text with Emacs.
219225
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
165165| =org-cycle-hide-block-startup= | |
166166| =electric-pair-mode= | |
167167| =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) |
168169| =tab-bar= | View ▸ Show Tab Bar |
169170| =show-markup= | View ▸ Show Markup (=⇧⌘M=) |
170171| =ignored-folders= | |
@@ -377,6 +378,9 @@ Any other key in =[theme]= is a color; see Themes below.
377378| =save= | string | ="automatic"= | =automatic= (one second after typing stops) or =explicit= (only with =⌘S=). |
378379| =keymap= | string | ="emacs"= | =emacs=, =mac= or =doom=. Your own bindings go in =keymap.toml=. |
379380| =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. |
380384| =tab-bar= | boolean | =false= | A tab for each open buffer above the editor. |
381385| =show-markup= | boolean | =false= | Show link brackets and emphasis markers. |
382386| =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
328328
329329Export (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.
330330
331ODT, LaTeX, ASCII and PDF through LaTeX aren't available on iOS. See [[file:12-export.org][Export]].
331PDF 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]].
332332
333333* Code blocks and tables
334334
@@ -402,6 +402,7 @@ These settings from =config.toml= apply on iOS:
402402- =org-todo-keywords=, =org-list-allow-alphabetical=
403403- =org-tags-column=, =org-insert-heading-respect-content=, =org-M-RET-may-split-line=, =fill-column=
404404- =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=
405406- =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=
406407- =[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]=
407408- =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer=