|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "strconv" |
| 5 | + |
| 6 | + "github.com/nguyenthenguyen/docx" |
| 7 | +) |
| 8 | + |
| 9 | +// Note - this sample code does not perform error checking, etc. |
| 10 | + |
| 11 | +func main() { |
| 12 | + |
| 13 | + // Read from docx file |
| 14 | + r, err := docx.ReadDocxFile("./TestDocument.docx") |
| 15 | + // Or read from memory |
| 16 | + // r, err := docx.ReadDocxFromMemory(data io.ReaderAt, size int64) |
| 17 | + |
| 18 | + // Or read from a filesystem object: |
| 19 | + // r, err := docx.ReadDocxFromFS(file string, fs fs.FS) |
| 20 | + |
| 21 | + if err != nil { |
| 22 | + panic(err) |
| 23 | + } |
| 24 | + docx1 := r.Editable() |
| 25 | + // Replace like https://golang.org/pkg/strings/#Replace |
| 26 | + docx1.Replace("old_1_1", "new_1_1", -1) |
| 27 | + docx1.Replace("old_1_2", "new_1_2", -1) |
| 28 | + docx1.ReplaceLink("http://example.com/", "https://github.com/nguyenthenguyen/docx", 1) |
| 29 | + docx1.ReplaceHeader("out with the old", "in with the new") |
| 30 | + docx1.ReplaceFooter("Change This Footer", "new footer") |
| 31 | + docx1.WriteToFile("./new_result_1.docx") |
| 32 | + |
| 33 | + docx2 := r.Editable() |
| 34 | + docx2.Replace("old_2_1", "new_2_1", -1) |
| 35 | + docx2.Replace("old_2_2", "new_2_2", -1) |
| 36 | + docx2.WriteToFile("./new_result_2.docx") |
| 37 | + |
| 38 | + // Or write to ioWriter |
| 39 | + // docx2.Write(ioWriter io.Writer) |
| 40 | + |
| 41 | + docx3 := r.Editable() |
| 42 | + //Currently only swaps apples for apples i.e. png to png, and not png to jpeg etc. |
| 43 | + docx3.ReplaceImage("word/media/image1.png", "./new.png") |
| 44 | + |
| 45 | + // replace the last image |
| 46 | + imageIndex := docx3.ImagesLen() |
| 47 | + docx3.ReplaceImage("word/media/image"+strconv.Itoa(imageIndex)+".png", "./new.png") |
| 48 | + docx3.WriteToFile("./new_result_3.docx") |
| 49 | + |
| 50 | + r.Close() |
| 51 | +} |
0 commit comments