1
0
mirror of https://github.com/fumiama/go-docx.git synced 2026-06-07 16:50:24 +08:00

feat: Docx implements io.WriterTo

This commit is contained in:
源文雨
2023-02-09 15:22:47 +08:00
parent f995e72acd
commit 56810d8288
5 changed files with 62 additions and 4 deletions

View File

@@ -1,5 +1,7 @@
package docxlib
import "strings"
// AddText adds text to paragraph
func (p *Paragraph) AddText(text string) *Run {
t := &Text{
@@ -15,3 +17,30 @@ func (p *Paragraph) AddText(text string) *Run {
return run
}
func (p *Paragraph) String() string {
sb := strings.Builder{}
for _, c := range p.Children {
switch {
case c.Link != nil:
id := c.Link.ID
text := c.Link.Run.InstrText
link, err := p.file.Refer(id)
sb.WriteString(text)
sb.WriteByte('(')
if err != nil {
sb.WriteString(id)
} else {
sb.WriteString(link)
}
sb.WriteByte(')')
case c.Run != nil:
sb.WriteString("run") //TODO: implement
case c.Properties != nil:
sb.WriteString("prop") //TODO: implement
default:
continue
}
}
return sb.String()
}

View File

@@ -35,7 +35,7 @@ func main() {
if err != nil {
panic(err)
}
err = w.Write(f)
_, err = w.WriteTo(f)
if err != nil {
panic(err)
}

View File

@@ -2,6 +2,7 @@ package docxlib
import (
"archive/zip"
"bytes"
"errors"
"io"
)
@@ -18,6 +19,11 @@ type Docx struct {
DocRelation Relationships
rId uintptr
buf *bytes.Buffer
isbufempty bool
io.Reader
io.WriterTo
}
// New generates a new empty docx file that we can manipulate and
@@ -65,11 +71,27 @@ func Parse(reader io.ReaderAt, size int64) (doc *Docx, err error) {
}
// Write allows to save a docx to a writer
func (f *Docx) Write(writer io.Writer) (err error) {
func (f *Docx) WriteTo(writer io.Writer) (_ int64, err error) {
zipWriter := zip.NewWriter(writer)
defer zipWriter.Close()
return f.pack(zipWriter)
return 0, f.pack(zipWriter)
}
// Read allows to save a docx to buf
func (f *Docx) Read(p []byte) (n int, err error) {
if !f.isbufempty {
n, err = f.buf.Read(p)
if err == io.EOF {
f.buf.Reset()
f.isbufempty = true
return
}
}
zipWriter := zip.NewWriter(f.buf)
defer zipWriter.Close()
f.isbufempty = false
return f.buf.Read(p)
}
// Refer gets the url for a reference

View File

@@ -1,6 +1,9 @@
package docxlib
import "encoding/xml"
import (
"bytes"
"encoding/xml"
)
func newEmptyFile() *Docx {
return &Docx{
@@ -39,5 +42,6 @@ func newEmptyFile() *Docx {
},
},
rId: 3,
buf: bytes.NewBuffer(make([]byte, 0, 1024*1024*4)),
}
}

View File

@@ -3,6 +3,7 @@ package docxlib
// This contains internal functions needed to unpack (read) a zip file
import (
"archive/zip"
"bytes"
"encoding/xml"
"io"
)
@@ -27,6 +28,8 @@ func unpack(zipReader *zip.Reader) (docx *Docx, err error) {
}
}
}
//TODO: find last rId
docx.buf = bytes.NewBuffer(make([]byte, 0, 1024*1024*4))
return
}