Todd 8e630657bf examples: add Word template example
Add an example that shows how to use a Word document
as a template and pull its styles for use in a new document.
2017-08-30 17:25:49 -05:00

57 lines
1.6 KiB
Go

package main
import (
"fmt"
"log"
"baliance.com/gooxml/document"
)
var lorem = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum`
func main() {
// When Word saves a document, it removes all unused styles. This means to
// copy the styles from an existing document, you must first create a
// document that contains text in each style of interest. As an example,
// see the template.docx in this directory. It contains a paragraph set in
// each style that Word supports by default.
doc, err := document.OpenTemplate("template.docx")
if err != nil {
log.Fatalf("error opening Windows Word 2016 document: %s", err)
}
// We can now print out all styles in the document, verifying that they
// exist.
for _, s := range doc.Styles.ParagraphStyles() {
fmt.Println("style", s.Name(), "has ID of", s.StyleID())
}
// And create documents setting their style to the style ID (not style name).
para := doc.AddParagraph()
para.SetStyle("Title")
para.AddRun().AddText("My Document Title")
para = doc.AddParagraph()
para.SetStyle("Subtitle")
para.AddRun().AddText("Document Subtitle")
para = doc.AddParagraph()
para.SetStyle("Heading1")
para.AddRun().AddText("Major Section")
para = doc.AddParagraph()
para = doc.AddParagraph()
for i := 0; i < 4; i++ {
para.AddRun().AddText(lorem)
}
para = doc.AddParagraph()
para.SetStyle("Heading2")
para.AddRun().AddText("Minor Section")
para = doc.AddParagraph()
for i := 0; i < 4; i++ {
para.AddRun().AddText(lorem)
}
doc.SaveToFile("use-template.docx")
}