picture.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package excelize
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "encoding/xml"
  6. "errors"
  7. "fmt"
  8. "image"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. )
  16. // parseFormatPictureSet provides function to parse the format settings of the
  17. // picture with default value.
  18. func parseFormatPictureSet(formatSet string) *formatPicture {
  19. format := formatPicture{
  20. FPrintsWithSheet: true,
  21. FLocksWithSheet: false,
  22. NoChangeAspect: false,
  23. OffsetX: 0,
  24. OffsetY: 0,
  25. XScale: 1.0,
  26. YScale: 1.0,
  27. }
  28. json.Unmarshal([]byte(formatSet), &format)
  29. return &format
  30. }
  31. // AddPicture provides the method to add picture in a sheet by given picture
  32. // format set (such as offset, scale, aspect ratio setting and print settings)
  33. // and file path. For example:
  34. //
  35. // package main
  36. //
  37. // import (
  38. // "fmt"
  39. // "os"
  40. // _ "image/gif"
  41. // _ "image/jpeg"
  42. // _ "image/png"
  43. //
  44. // "github.com/Luxurioust/excelize"
  45. // )
  46. //
  47. // func main() {
  48. // xlsx := excelize.CreateFile()
  49. // // Insert a picture.
  50. // err := xlsx.AddPicture("Sheet1", "A2", "/tmp/image1.jpg", "")
  51. // if err != nil {
  52. // fmt.Println(err)
  53. // }
  54. // // Insert a picture to sheet with scaling.
  55. // err = xlsx.AddPicture("Sheet1", "D2", "/tmp/image1.png", `{"x_scale": 0.5, "y_scale": 0.5}`)
  56. // if err != nil {
  57. // fmt.Println(err)
  58. // }
  59. // // Insert a picture offset in the cell with printing support.
  60. // err = xlsx.AddPicture("Sheet1", "H2", "/tmp/image3.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`)
  61. // if err != nil {
  62. // fmt.Println(err)
  63. // }
  64. // err = xlsx.WriteTo("/tmp/Workbook.xlsx")
  65. // if err != nil {
  66. // fmt.Println(err)
  67. // os.Exit(1)
  68. // }
  69. // }
  70. //
  71. func (f *File) AddPicture(sheet, cell, picture, format string) error {
  72. var supportTypes = map[string]string{".gif": ".gif", ".jpg": ".jpeg", ".jpeg": ".jpeg", ".png": ".png"}
  73. var err error
  74. // Check picture exists first.
  75. if _, err = os.Stat(picture); os.IsNotExist(err) {
  76. return err
  77. }
  78. ext, ok := supportTypes[path.Ext(picture)]
  79. if !ok {
  80. return errors.New("Unsupported image extension")
  81. }
  82. readFile, _ := os.Open(picture)
  83. image, _, err := image.DecodeConfig(readFile)
  84. _, file := filepath.Split(picture)
  85. formatSet := parseFormatPictureSet(format)
  86. // Read sheet data.
  87. xlsx := f.workSheetReader(sheet)
  88. // Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  89. drawingID := f.countDrawings() + 1
  90. pictureID := f.countMedia() + 1
  91. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  92. sheetRelationshipsDrawingXML := "../drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  93. var drawingRID int
  94. if xlsx.Drawing != nil {
  95. // The worksheet already has a picture or chart relationships, use the relationships drawing ../drawings/drawing%d.xml.
  96. sheetRelationshipsDrawingXML = f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  97. drawingID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingXML, "../drawings/drawing"), ".xml"))
  98. drawingXML = strings.Replace(sheetRelationshipsDrawingXML, "..", "xl", -1)
  99. } else {
  100. // Add first picture for given sheet.
  101. rID := f.addSheetRelationships(sheet, SourceRelationshipDrawingML, sheetRelationshipsDrawingXML, "")
  102. f.addSheetDrawing(sheet, rID)
  103. }
  104. drawingRID = f.addDrawingRelationships(drawingID, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext)
  105. f.addDrawing(sheet, drawingXML, cell, file, image.Width, image.Height, drawingRID, formatSet)
  106. f.addMedia(picture, ext)
  107. f.addDrawingContentTypePart(drawingID)
  108. return err
  109. }
  110. // addSheetRelationships provides function to add
  111. // xl/worksheets/_rels/sheet%d.xml.rels by given sheet name, relationship type
  112. // and target.
  113. func (f *File) addSheetRelationships(sheet, relType, target, targetMode string) int {
  114. var rels = "xl/worksheets/_rels/" + strings.ToLower(sheet) + ".xml.rels"
  115. var sheetRels xlsxWorkbookRels
  116. var rID = 1
  117. var ID bytes.Buffer
  118. ID.WriteString("rId")
  119. ID.WriteString(strconv.Itoa(rID))
  120. _, ok := f.XLSX[rels]
  121. if ok {
  122. ID.Reset()
  123. xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  124. rID = len(sheetRels.Relationships) + 1
  125. ID.WriteString("rId")
  126. ID.WriteString(strconv.Itoa(rID))
  127. }
  128. sheetRels.Relationships = append(sheetRels.Relationships, xlsxWorkbookRelation{
  129. ID: ID.String(),
  130. Type: relType,
  131. Target: target,
  132. TargetMode: targetMode,
  133. })
  134. output, err := xml.Marshal(sheetRels)
  135. if err != nil {
  136. fmt.Println(err)
  137. }
  138. f.saveFileList(rels, string(output))
  139. return rID
  140. }
  141. // addSheetDrawing provides function to add drawing element to
  142. // xl/worksheets/sheet%d.xml by given sheet name and relationship index.
  143. func (f *File) addSheetDrawing(sheet string, rID int) {
  144. xlsx := f.workSheetReader(sheet)
  145. xlsx.Drawing = &xlsxDrawing{
  146. RID: "rId" + strconv.Itoa(rID),
  147. }
  148. }
  149. // addSheetPicture provides function to add picture element to
  150. // xl/worksheets/sheet%d.xml by given sheet name and relationship index.
  151. func (f *File) addSheetPicture(sheet string, rID int) {
  152. xlsx := f.workSheetReader(sheet)
  153. xlsx.Picture = &xlsxPicture{
  154. RID: "rId" + strconv.Itoa(rID),
  155. }
  156. }
  157. // countDrawings provides function to get drawing files count storage in the
  158. // folder xl/drawings.
  159. func (f *File) countDrawings() int {
  160. count := 0
  161. for k := range f.XLSX {
  162. if strings.Contains(k, "xl/drawings/drawing") {
  163. count++
  164. }
  165. }
  166. return count
  167. }
  168. // addDrawing provides function to add picture by given drawingXML, xAxis,
  169. // yAxis, file name and relationship index. In order to solve the problem that
  170. // the label structure is changed after serialization and deserialization, two
  171. // different structures: decodeWsDr and encodeWsDr are defined.
  172. func (f *File) addDrawing(sheet, drawingXML, cell, file string, width, height, rID int, formatSet *formatPicture) {
  173. cell = strings.ToUpper(cell)
  174. fromCol := string(strings.Map(letterOnlyMapF, cell))
  175. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  176. row := fromRow - 1
  177. col := titleToNumber(fromCol)
  178. width = int(float64(width) * formatSet.XScale)
  179. height = int(float64(height) * formatSet.YScale)
  180. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height)
  181. content := encodeWsDr{}
  182. content.WsDr.A = NameSpaceDrawingML
  183. content.WsDr.Xdr = NameSpaceSpreadSheetDrawing
  184. cNvPrID := 1
  185. _, ok := f.XLSX[drawingXML]
  186. if ok { // Append Model
  187. decodeWsDr := decodeWsDr{}
  188. xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
  189. cNvPrID = len(decodeWsDr.TwoCellAnchor) + 1
  190. for _, v := range decodeWsDr.OneCellAnchor {
  191. content.WsDr.OneCellAnchor = append(content.WsDr.OneCellAnchor, &xlsxCellAnchor{
  192. EditAs: v.EditAs,
  193. GraphicFrame: v.Content,
  194. })
  195. }
  196. for _, v := range decodeWsDr.TwoCellAnchor {
  197. content.WsDr.TwoCellAnchor = append(content.WsDr.TwoCellAnchor, &xlsxCellAnchor{
  198. EditAs: v.EditAs,
  199. GraphicFrame: v.Content,
  200. })
  201. }
  202. }
  203. twoCellAnchor := xlsxCellAnchor{}
  204. twoCellAnchor.EditAs = "oneCell"
  205. from := xlsxFrom{}
  206. from.Col = colStart
  207. from.ColOff = formatSet.OffsetX * EMU
  208. from.Row = rowStart
  209. from.RowOff = formatSet.OffsetY * EMU
  210. to := xlsxTo{}
  211. to.Col = colEnd
  212. to.ColOff = x2 * EMU
  213. to.Row = rowEnd
  214. to.RowOff = y2 * EMU
  215. twoCellAnchor.From = &from
  216. twoCellAnchor.To = &to
  217. pic := xlsxPic{}
  218. pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect
  219. pic.NvPicPr.CNvPr.ID = cNvPrID
  220. pic.NvPicPr.CNvPr.Descr = file
  221. pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
  222. pic.BlipFill.Blip.R = SourceRelationship
  223. pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
  224. pic.SpPr.PrstGeom.Prst = "rect"
  225. twoCellAnchor.Pic = &pic
  226. twoCellAnchor.ClientData = &xlsxClientData{
  227. FLocksWithSheet: formatSet.FLocksWithSheet,
  228. FPrintsWithSheet: formatSet.FPrintsWithSheet,
  229. }
  230. content.WsDr.TwoCellAnchor = append(content.WsDr.TwoCellAnchor, &twoCellAnchor)
  231. output, err := xml.Marshal(content)
  232. if err != nil {
  233. fmt.Println(err)
  234. }
  235. // Create replacer with pairs as arguments and replace all pairs.
  236. r := strings.NewReplacer("<encodeWsDr>", "", "</encodeWsDr>", "")
  237. result := r.Replace(string(output))
  238. f.saveFileList(drawingXML, result)
  239. }
  240. // addDrawingRelationships provides function to add image part relationships in
  241. // the file xl/drawings/_rels/drawing%d.xml.rels by given drawing index,
  242. // relationship type and target.
  243. func (f *File) addDrawingRelationships(index int, relType string, target string) int {
  244. var rels = "xl/drawings/_rels/drawing" + strconv.Itoa(index) + ".xml.rels"
  245. var drawingRels xlsxWorkbookRels
  246. var rID = 1
  247. var ID bytes.Buffer
  248. ID.WriteString("rId")
  249. ID.WriteString(strconv.Itoa(rID))
  250. _, ok := f.XLSX[rels]
  251. if ok {
  252. ID.Reset()
  253. xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  254. rID = len(drawingRels.Relationships) + 1
  255. ID.WriteString("rId")
  256. ID.WriteString(strconv.Itoa(rID))
  257. }
  258. drawingRels.Relationships = append(drawingRels.Relationships, xlsxWorkbookRelation{
  259. ID: ID.String(),
  260. Type: relType,
  261. Target: target,
  262. })
  263. output, err := xml.Marshal(drawingRels)
  264. if err != nil {
  265. fmt.Println(err)
  266. }
  267. f.saveFileList(rels, string(output))
  268. return rID
  269. }
  270. // countMedia provides function to get media files count storage in the folder
  271. // xl/media/image.
  272. func (f *File) countMedia() int {
  273. count := 0
  274. for k := range f.XLSX {
  275. if strings.Contains(k, "xl/media/image") {
  276. count++
  277. }
  278. }
  279. return count
  280. }
  281. // addMedia provides function to add picture into folder xl/media/image by given
  282. // file name and extension name.
  283. func (f *File) addMedia(file string, ext string) {
  284. count := f.countMedia()
  285. dat, _ := ioutil.ReadFile(file)
  286. media := "xl/media/image" + strconv.Itoa(count+1) + ext
  287. f.XLSX[media] = string(dat)
  288. }
  289. // setContentTypePartImageExtensions provides function to set the content type
  290. // for relationship parts and the Main Document part.
  291. func (f *File) setContentTypePartImageExtensions() {
  292. var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false}
  293. var content xlsxTypes
  294. xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
  295. for _, v := range content.Defaults {
  296. _, ok := imageTypes[v.Extension]
  297. if ok {
  298. imageTypes[v.Extension] = true
  299. }
  300. }
  301. for k, v := range imageTypes {
  302. if !v {
  303. content.Defaults = append(content.Defaults, xlsxDefault{
  304. Extension: k,
  305. ContentType: "image/" + k,
  306. })
  307. }
  308. }
  309. output, _ := xml.Marshal(content)
  310. f.saveFileList("[Content_Types].xml", string(output))
  311. }
  312. // addDrawingContentTypePart provides function to add image part relationships
  313. // in http://purl.oclc.org/ooxml/officeDocument/relationships/image and
  314. // appropriate content type.
  315. func (f *File) addDrawingContentTypePart(index int) {
  316. f.setContentTypePartImageExtensions()
  317. var content xlsxTypes
  318. xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
  319. for _, v := range content.Overrides {
  320. if v.PartName == "/xl/drawings/drawing"+strconv.Itoa(index)+".xml" {
  321. output, _ := xml.Marshal(content)
  322. f.saveFileList(`[Content_Types].xml`, string(output))
  323. return
  324. }
  325. }
  326. content.Overrides = append(content.Overrides, xlsxOverride{
  327. PartName: "/xl/drawings/drawing" + strconv.Itoa(index) + ".xml",
  328. ContentType: "application/vnd.openxmlformats-officedocument.drawing+xml",
  329. })
  330. output, _ := xml.Marshal(content)
  331. f.saveFileList("[Content_Types].xml", string(output))
  332. }
  333. // getSheetRelationshipsTargetByID provides function to get Target attribute
  334. // value in xl/worksheets/_rels/sheet%d.xml.rels by given sheet name and
  335. // relationship index.
  336. func (f *File) getSheetRelationshipsTargetByID(sheet string, rID string) string {
  337. var rels = "xl/worksheets/_rels/" + strings.ToLower(sheet) + ".xml.rels"
  338. var sheetRels xlsxWorkbookRels
  339. xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  340. for _, v := range sheetRels.Relationships {
  341. if v.ID == rID {
  342. return v.Target
  343. }
  344. }
  345. return ""
  346. }