-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.go
More file actions
446 lines (389 loc) · 12.8 KB
/
main.go
File metadata and controls
446 lines (389 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*
MIT License
Copyright (c) 2025 Misael Monterroca
Copyright (c) 2020-2023 fumiama (original go-docx)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package main
import (
"fmt"
"log"
"strings"
docx "github.com/mmonterroca/docxgo"
"github.com/mmonterroca/docxgo/domain"
)
func main() {
// Create a new document
doc := docx.NewDocument()
// Example 1: Add page numbers to footer
if err := addPageNumbers(doc); err != nil {
log.Fatalf("Failed to add page numbers: %v", err)
}
// Example 2: Add Table of Contents
if err := addTableOfContents(doc); err != nil {
log.Fatalf("Failed to add TOC: %v", err)
}
// Example 3: Add content with headings
if err := addContent(doc); err != nil {
log.Fatalf("Failed to add content: %v", err)
}
// Example 4: Add hyperlinks
if err := addHyperlinks(doc); err != nil {
log.Fatalf("Failed to add hyperlinks: %v", err)
}
// Save the document
if err := doc.SaveAs("fields_example.docx"); err != nil {
log.Fatalf("Failed to save document: %v", err)
}
fmt.Println("Document created successfully: fields_example.docx")
fmt.Println("\nNote: Open the document in Word and press F9 to update all fields.")
}
// addPageNumbers adds page numbers to the default footer
func addPageNumbers(doc domain.Document) error {
// Get the default section
section, err := doc.DefaultSection()
if err != nil {
return fmt.Errorf("get default section: %w", err)
}
// Get the default footer
footer, err := section.Footer(domain.FooterDefault)
if err != nil {
return fmt.Errorf("get footer: %w", err)
}
// Add a paragraph to the footer
para, err := footer.AddParagraph()
if err != nil {
return fmt.Errorf("add paragraph: %w", err)
}
// Set center alignment
para.SetAlignment(domain.AlignmentCenter)
// Add text before page number
run1, err := para.AddRun()
if err != nil {
return fmt.Errorf("add run: %w", err)
}
run1.AddText("Page ")
// Add page number field
run2, err := para.AddRun()
if err != nil {
return fmt.Errorf("add run: %w", err)
}
pageField := docx.NewPageNumberField()
run2.AddField(pageField)
// Add text after page number
run3, err := para.AddRun()
if err != nil {
return fmt.Errorf("add run: %w", err)
}
run3.AddText(" of ")
// Add total page count field
run4, err := para.AddRun()
if err != nil {
return fmt.Errorf("add run: %w", err)
}
pageCountField := docx.NewPageCountField()
run4.AddField(pageCountField)
return nil
}
// addTableOfContents adds a TOC at the beginning of the document
func addTableOfContents(doc domain.Document) error {
// Add TOC heading
heading, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add heading: %w", err)
}
heading.SetStyle("Heading1")
run, err := heading.AddRun()
if err != nil {
return fmt.Errorf("add run: %w", err)
}
run.AddText("Table of Contents")
// Add TOC paragraph
tocPara, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add TOC paragraph: %w", err)
}
// Create TOC field with custom options
tocOptions := map[string]string{
"levels": "1-3", // Include heading levels 1-3
"hyperlinks": "true", // Enable hyperlinks
}
tocField := docx.NewTOCField(tocOptions)
// Add TOC field to paragraph
tocRun, err := tocPara.AddRun()
if err != nil {
return fmt.Errorf("add TOC run: %w", err)
}
tocRun.AddField(tocField)
// Add page break after TOC
doc.AddPageBreak()
return nil
}
// addContent adds sample content with headings
func addContent(doc domain.Document) error {
sections := []struct {
heading string
content string
level string
}{
{
heading: "Introduction",
content: "This document demonstrates the use of fields in Word documents. Fields are dynamic elements that can display automatically calculated values such as page numbers, dates, or cross-references.",
level: "Heading1",
},
{
heading: "Page Numbering",
content: "The footer contains page numbers that are automatically calculated. The format used is 'Page X of Y', where X is the current page and Y is the total number of pages.",
level: "Heading2",
},
{
heading: "Table of Contents",
content: "The TOC at the beginning is generated from the heading styles in the document. In Word, you can update it by right-clicking and selecting 'Update Field', or by pressing F9.",
level: "Heading2",
},
{
heading: "Hyperlinks",
content: "Hyperlinks are also implemented as fields. They allow linking to external URLs or internal bookmarks.",
level: "Heading2",
},
{
heading: "Advanced Features",
content: "Additional field types supported include STYLEREF for running headers, SEQ for sequence numbering, and custom fields for specialized needs.",
level: "Heading1",
},
{
heading: "Cross-References",
content: "Cross-references can be created using REF fields, allowing you to reference other parts of the document by bookmark name.",
level: "Heading2",
},
{
heading: "Date and Time",
content: "DATE and TIME fields automatically insert the current date or time, with optional formatting switches.",
level: "Heading2",
},
}
var lastHeading1 string
const sequenceBookmarkName = "_RefFigureSequence1"
const sequenceBookmarkID = "200"
sequenceNumber := "1"
for _, section := range sections {
// Add heading
heading, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add heading: %w", err)
}
heading.SetStyle(section.level)
run, err := heading.AddRun()
if err != nil {
return fmt.Errorf("add run: %w", err)
}
run.AddText(section.heading)
if section.level == "Heading1" {
lastHeading1 = section.heading
}
// Add content
para, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add paragraph: %w", err)
}
contentRun, err := para.AddRun()
if err != nil {
return fmt.Errorf("add content run: %w", err)
}
contentRun.AddText(section.content)
if section.heading == "Date and Time" {
datePara, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add date paragraph: %w", err)
}
dateLabelRun, err := datePara.AddRun()
if err != nil {
return fmt.Errorf("add date label run: %w", err)
}
dateLabelRun.AddText("Current date: ")
dateFieldRun, err := datePara.AddRun()
if err != nil {
return fmt.Errorf("add date field run: %w", err)
}
dateField := docx.NewField(domain.FieldTypeDate)
if err := dateField.SetCode(`DATE \@ "MMMM d, yyyy"`); err != nil {
return fmt.Errorf("configure date field: %w", err)
}
if err := dateFieldRun.AddField(dateField); err != nil {
return fmt.Errorf("add date field: %w", err)
}
timePara, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add time paragraph: %w", err)
}
timeLabelRun, err := timePara.AddRun()
if err != nil {
return fmt.Errorf("add time label run: %w", err)
}
timeLabelRun.AddText("Current time: ")
timeFieldRun, err := timePara.AddRun()
if err != nil {
return fmt.Errorf("add time field run: %w", err)
}
timeField := docx.NewField(domain.FieldTypeTime)
if err := timeField.SetCode(`TIME \@ "HH:mm"`); err != nil {
return fmt.Errorf("configure time field: %w", err)
}
if err := timeFieldRun.AddField(timeField); err != nil {
return fmt.Errorf("add time field: %w", err)
}
timePara.SetSpacingAfter(200)
} else if section.heading == "Advanced Features" {
stylePara, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add style-ref paragraph: %w", err)
}
styleRun, err := stylePara.AddRun()
if err != nil {
return fmt.Errorf("add style-ref label run: %w", err)
}
styleRun.AddText("Running header (STYLEREF Heading 1): ")
styleFieldRun, err := stylePara.AddRun()
if err != nil {
return fmt.Errorf("add style-ref field run: %w", err)
}
styleField := docx.NewStyleRefField("Heading 1")
if err := styleField.SetCode(`STYLEREF "Heading 1" \* MERGEFORMAT`); err != nil {
return fmt.Errorf("configure style-ref field: %w", err)
}
if setter, ok := styleField.(interface{ SetResult(string) }); ok {
display := lastHeading1
if strings.TrimSpace(display) == "" {
display = "Heading 1 (update fields)"
}
setter.SetResult(display)
}
if err := styleFieldRun.AddField(styleField); err != nil {
return fmt.Errorf("add style-ref field: %w", err)
}
seqPara, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add sequence paragraph: %w", err)
}
if err := seqPara.SetStyle("Caption"); err != nil {
return fmt.Errorf("set caption style: %w", err)
}
seqLabelRun, err := seqPara.AddRun()
if err != nil {
return fmt.Errorf("add sequence label run: %w", err)
}
seqLabelRun.AddText("Figure ")
seqFieldRun, err := seqPara.AddRun()
if err != nil {
return fmt.Errorf("add sequence field run: %w", err)
}
seqField := docx.NewField(domain.FieldTypeSeq)
if err := seqField.SetCode(`SEQ Figure \* ARABIC`); err != nil {
return fmt.Errorf("configure sequence field: %w", err)
}
if setter, ok := seqField.(interface{ SetResult(string) }); ok {
setter.SetResult(sequenceNumber)
}
if err := seqFieldRun.AddField(seqField); err != nil {
return fmt.Errorf("add sequence field: %w", err)
}
seqTitleRun, err := seqPara.AddRun()
if err != nil {
return fmt.Errorf("add sequence title run: %w", err)
}
seqTitleRun.AddText(" – Sample sequence field")
if bookmarkable, ok := seqPara.(interface{ SetBookmark(string, string) }); ok {
bookmarkable.SetBookmark(sequenceBookmarkID, sequenceBookmarkName)
}
seqPara.SetSpacingAfter(200)
} else if section.heading == "Cross-References" {
refPara, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add cross-reference paragraph: %w", err)
}
refIntroRun, err := refPara.AddRun()
if err != nil {
return fmt.Errorf("add cross-reference intro run: %w", err)
}
refIntroRun.AddText("See ")
refFieldRun, err := refPara.AddRun()
if err != nil {
return fmt.Errorf("add cross-reference field run: %w", err)
}
refField := docx.NewField(domain.FieldTypeRef)
if err := refField.SetCode(fmt.Sprintf("REF %s \\h", sequenceBookmarkName)); err != nil {
return fmt.Errorf("configure cross-reference field: %w", err)
}
if setter, ok := refField.(interface{ SetResult(string) }); ok {
setter.SetResult(fmt.Sprintf("Figure %s", sequenceNumber))
}
if err := refFieldRun.AddField(refField); err != nil {
return fmt.Errorf("add cross-reference field: %w", err)
}
refSuffixRun, err := refPara.AddRun()
if err != nil {
return fmt.Errorf("add cross-reference suffix run: %w", err)
}
refSuffixRun.AddText(" for the sequence field output above.")
refPara.SetSpacingAfter(200)
}
// Add spacing
para.SetSpacingAfter(200) // 200 twips
}
return nil
}
// addHyperlinks adds example hyperlinks to the document
func addHyperlinks(doc domain.Document) error {
// Add section heading
heading, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add heading: %w", err)
}
heading.SetStyle("Heading1")
run, err := heading.AddRun()
if err != nil {
return fmt.Errorf("add run: %w", err)
}
run.AddText("Useful Links")
// Add paragraph with hyperlinks
para, err := doc.AddParagraph()
if err != nil {
return fmt.Errorf("add paragraph: %w", err)
}
// Text before link
textRun, err := para.AddRun()
if err != nil {
return fmt.Errorf("add text run: %w", err)
}
textRun.AddText("For more information, visit ")
// Hyperlink
linkRun, err := para.AddRun()
if err != nil {
return fmt.Errorf("add link run: %w", err)
}
linkRun.SetColor(docx.Blue)
linkRun.SetUnderline(domain.UnderlineSingle)
hyperlinkField := docx.NewHyperlinkField("https://github.com/mmonterroca/docxgo", "go-docx repository")
linkRun.AddField(hyperlinkField)
// Text after link
textRun2, err := para.AddRun()
if err != nil {
return fmt.Errorf("add text run: %w", err)
}
textRun2.AddText(" on GitHub.")
return nil
}