From daf7190ea69bfaea25339b9167bb3e1e352bb849 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=BA=90=E6=96=87=E9=9B=A8?= <41315874+fumiama@users.noreply.github.com> Date: Fri, 10 Mar 2023 13:28:25 +0800 Subject: [PATCH] add api LoadBodyItems --- cmd/main/main.go | 7 ++++--- docx.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/cmd/main/main.go b/cmd/main/main.go index 04dd303..a138d59 100644 --- a/cmd/main/main.go +++ b/cmd/main/main.go @@ -223,9 +223,10 @@ func main() { } } if *splitre != "" { - i := strings.LastIndex(*fileLocation, "/") - for j, splitteddoc := range doc.SplitByParagraph(docx.SplitDocxByPlainTextRegex(regexp.MustCompile(*splitre))) { - name := (*fileLocation)[:i+1] + "unmarshal_split" + strconv.Itoa(j) + "_" + (*fileLocation)[i+1:] + a := strings.LastIndex(*fileLocation, "/") + b := strings.LastIndex(*fileLocation, ".") + for i, splitteddoc := range doc.SplitByParagraph(docx.SplitDocxByPlainTextRegex(regexp.MustCompile(*splitre))) { + name := (*fileLocation)[:a+1] + "unmarshal_" + (*fileLocation)[a+1:b] + "_split" + strconv.Itoa(i) + (*fileLocation)[b:] f, err := os.Create(name) if err != nil { panic(err) diff --git a/docx.go b/docx.go index 0319dc3..1e3e04f 100644 --- a/docx.go +++ b/docx.go @@ -24,6 +24,7 @@ package docx import ( "archive/zip" + "encoding/xml" "io" "io/fs" "sync" @@ -97,6 +98,55 @@ func Parse(reader io.ReaderAt, size int64) (doc *Docx, err error) { return } +// LoadBodyItems will load body and media to a new Docx struct. +// You should call UseTemplate to set a template later. +func LoadBodyItems(items []interface{}, media []Media) *Docx { + doc := &Docx{ + Document: Document{ + XMLName: xml.Name{ + Space: "w", + }, + XMLW: XMLNS_W, + XMLR: XMLNS_R, + XMLWP: XMLNS_WP, + XMLWPS: XMLNS_WPS, + XMLWPC: XMLNS_WPC, + XMLWPG: XMLNS_WPG, + Body: Body{Items: items}, + }, + docRelation: Relationships{ + Xmlns: XMLNS_REL, + Relationship: []Relationship{ + { + ID: "rId1", + Type: `http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles`, + Target: "styles.xml", + }, + { + ID: "rId2", + Type: `http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme`, + Target: "theme/theme1.xml", + }, + { + ID: "rId3", + Type: `http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable`, + Target: "fontTable.xml", + }, + }, + }, + media: media, + mediaNameIdx: make(map[string]int, 64), + rID: 3, + slowIDs: make(map[string]uintptr, 64), + } + doc.Document.Body.file = doc + for i, m := range media { + doc.mediaNameIdx[m.Name] = i + } + doc.slowIDs["图片"] = uintptr(len(media) + 1) + return doc +} + // WriteTo allows to save a docx to a writer func (f *Docx) WriteTo(writer io.Writer) (_ int64, err error) { zipWriter := zip.NewWriter(writer)