picture.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. package excelize
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "encoding/xml"
  6. "errors"
  7. "image"
  8. "io/ioutil"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. )
  15. // parseFormatPictureSet provides function to parse the format settings of the
  16. // picture with default value.
  17. func parseFormatPictureSet(formatSet string) *formatPicture {
  18. format := formatPicture{
  19. FPrintsWithSheet: true,
  20. FLocksWithSheet: false,
  21. NoChangeAspect: false,
  22. OffsetX: 0,
  23. OffsetY: 0,
  24. XScale: 1.0,
  25. YScale: 1.0,
  26. }
  27. json.Unmarshal([]byte(formatSet), &format)
  28. return &format
  29. }
  30. // AddPicture provides the method to add picture in a sheet by given picture
  31. // format set (such as offset, scale, aspect ratio setting and print settings)
  32. // and file path. For example:
  33. //
  34. // package main
  35. //
  36. // import (
  37. // "fmt"
  38. // _ "image/gif"
  39. // _ "image/jpeg"
  40. // _ "image/png"
  41. //
  42. // "github.com/360EntSecGroup-Skylar/excelize"
  43. // )
  44. //
  45. // func main() {
  46. // xlsx := excelize.NewFile()
  47. // // Insert a picture.
  48. // err := xlsx.AddPicture("Sheet1", "A2", "./image1.jpg", "")
  49. // if err != nil {
  50. // fmt.Println(err)
  51. // }
  52. // // Insert a picture scaling in the cell with location hyperlink.
  53. // err = xlsx.AddPicture("Sheet1", "D2", "./image1.png", `{"x_scale": 0.5, "y_scale": 0.5, "hyperlink": "#Sheet2!D8", "hyperlink_type": "Location"}`)
  54. // if err != nil {
  55. // fmt.Println(err)
  56. // }
  57. // // Insert a picture offset in the cell with external hyperlink and printing support.
  58. // err = xlsx.AddPicture("Sheet1", "H2", "./image3.gif", `{"x_offset": 15, "y_offset": 10, "hyperlink": "https://github.com/360EntSecGroup-Skylar/excelize", "hyperlink_type": "External", "print_obj": true, "lock_aspect_ratio": false, "locked": false}`)
  59. // if err != nil {
  60. // fmt.Println(err)
  61. // }
  62. // err = xlsx.SaveAs("./Workbook.xlsx")
  63. // if err != nil {
  64. // fmt.Println(err)
  65. // }
  66. // }
  67. //
  68. // LinkType defines two types of hyperlink "External" for web site or
  69. // "Location" for moving to one of cell in this workbook. When the
  70. // "hyperlink_type" is "Location", coordinates need to start with "#".
  71. func (f *File) AddPicture(sheet, cell, picture, format string) error {
  72. var err error
  73. var drawingHyperlinkRID int
  74. var hyperlinkType string
  75. // Check picture exists first.
  76. if _, err = os.Stat(picture); os.IsNotExist(err) {
  77. return err
  78. }
  79. ext, ok := supportImageTypes[path.Ext(picture)]
  80. if !ok {
  81. return errors.New("Unsupported image extension")
  82. }
  83. readFile, _ := os.Open(picture)
  84. image, _, err := image.DecodeConfig(readFile)
  85. _, file := filepath.Split(picture)
  86. formatSet := parseFormatPictureSet(format)
  87. // Read sheet data.
  88. xlsx := f.workSheetReader(sheet)
  89. // Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  90. drawingID := f.countDrawings() + 1
  91. pictureID := f.countMedia() + 1
  92. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  93. drawingID, drawingXML = f.prepareDrawing(xlsx, drawingID, sheet, drawingXML)
  94. drawingRID := f.addDrawingRelationships(drawingID, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, hyperlinkType)
  95. // Add picture with hyperlink.
  96. if formatSet.Hyperlink != "" && formatSet.HyperlinkType != "" {
  97. if formatSet.HyperlinkType == "External" {
  98. hyperlinkType = formatSet.HyperlinkType
  99. }
  100. drawingHyperlinkRID = f.addDrawingRelationships(drawingID, SourceRelationshipHyperLink, formatSet.Hyperlink, hyperlinkType)
  101. }
  102. f.addDrawingPicture(sheet, drawingXML, cell, file, image.Width, image.Height, drawingRID, drawingHyperlinkRID, formatSet)
  103. f.addMedia(picture, ext)
  104. f.addContentTypePart(drawingID, "drawings")
  105. return err
  106. }
  107. // addSheetRelationships provides function to add
  108. // xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name, relationship
  109. // type and target.
  110. func (f *File) addSheetRelationships(sheet, relType, target, targetMode string) int {
  111. name, ok := f.sheetMap[trimSheetName(sheet)]
  112. if !ok {
  113. name = strings.ToLower(sheet) + ".xml"
  114. }
  115. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  116. var sheetRels xlsxWorkbookRels
  117. var rID = 1
  118. var ID bytes.Buffer
  119. ID.WriteString("rId")
  120. ID.WriteString(strconv.Itoa(rID))
  121. _, ok = f.XLSX[rels]
  122. if ok {
  123. ID.Reset()
  124. xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  125. rID = len(sheetRels.Relationships) + 1
  126. ID.WriteString("rId")
  127. ID.WriteString(strconv.Itoa(rID))
  128. }
  129. sheetRels.Relationships = append(sheetRels.Relationships, xlsxWorkbookRelation{
  130. ID: ID.String(),
  131. Type: relType,
  132. Target: target,
  133. TargetMode: targetMode,
  134. })
  135. output, _ := xml.Marshal(sheetRels)
  136. f.saveFileList(rels, string(output))
  137. return rID
  138. }
  139. // deleteSheetRelationships provides function to delete relationships in
  140. // xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and relationship
  141. // index.
  142. func (f *File) deleteSheetRelationships(sheet, rID string) {
  143. name, ok := f.sheetMap[trimSheetName(sheet)]
  144. if !ok {
  145. name = strings.ToLower(sheet) + ".xml"
  146. }
  147. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  148. var sheetRels xlsxWorkbookRels
  149. xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  150. for k, v := range sheetRels.Relationships {
  151. if v.ID == rID {
  152. sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
  153. }
  154. }
  155. output, _ := xml.Marshal(sheetRels)
  156. f.saveFileList(rels, string(output))
  157. }
  158. // addSheetLegacyDrawing provides function to add legacy drawing element to
  159. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  160. func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
  161. xlsx := f.workSheetReader(sheet)
  162. xlsx.LegacyDrawing = &xlsxLegacyDrawing{
  163. RID: "rId" + strconv.Itoa(rID),
  164. }
  165. }
  166. // addSheetDrawing provides function to add drawing element to
  167. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  168. func (f *File) addSheetDrawing(sheet string, rID int) {
  169. xlsx := f.workSheetReader(sheet)
  170. xlsx.Drawing = &xlsxDrawing{
  171. RID: "rId" + strconv.Itoa(rID),
  172. }
  173. }
  174. // addSheetPicture provides function to add picture element to
  175. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  176. func (f *File) addSheetPicture(sheet string, rID int) {
  177. xlsx := f.workSheetReader(sheet)
  178. xlsx.Picture = &xlsxPicture{
  179. RID: "rId" + strconv.Itoa(rID),
  180. }
  181. }
  182. // countDrawings provides function to get drawing files count storage in the
  183. // folder xl/drawings.
  184. func (f *File) countDrawings() int {
  185. count := 0
  186. for k := range f.XLSX {
  187. if strings.Contains(k, "xl/drawings/drawing") {
  188. count++
  189. }
  190. }
  191. return count
  192. }
  193. // addDrawingPicture provides function to add picture by given sheet,
  194. // drawingXML, cell, file name, width, height relationship index and format
  195. // sets.
  196. func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID, hyperlinkRID int, formatSet *formatPicture) {
  197. cell = strings.ToUpper(cell)
  198. fromCol := string(strings.Map(letterOnlyMapF, cell))
  199. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  200. row := fromRow - 1
  201. col := TitleToNumber(fromCol)
  202. width = int(float64(width) * formatSet.XScale)
  203. height = int(float64(height) * formatSet.YScale)
  204. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height)
  205. content := xlsxWsDr{}
  206. content.A = NameSpaceDrawingML
  207. content.Xdr = NameSpaceDrawingMLSpreadSheet
  208. cNvPrID := f.drawingParser(drawingXML, &content)
  209. twoCellAnchor := xdrCellAnchor{}
  210. twoCellAnchor.EditAs = "oneCell"
  211. from := xlsxFrom{}
  212. from.Col = colStart
  213. from.ColOff = formatSet.OffsetX * EMU
  214. from.Row = rowStart
  215. from.RowOff = formatSet.OffsetY * EMU
  216. to := xlsxTo{}
  217. to.Col = colEnd
  218. to.ColOff = x2 * EMU
  219. to.Row = rowEnd
  220. to.RowOff = y2 * EMU
  221. twoCellAnchor.From = &from
  222. twoCellAnchor.To = &to
  223. pic := xlsxPic{}
  224. pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect
  225. pic.NvPicPr.CNvPr.ID = f.countCharts() + f.countMedia() + 1
  226. pic.NvPicPr.CNvPr.Descr = file
  227. pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
  228. if hyperlinkRID != 0 {
  229. pic.NvPicPr.CNvPr.HlinkClick = &xlsxHlinkClick{
  230. R: SourceRelationship,
  231. RID: "rId" + strconv.Itoa(hyperlinkRID),
  232. }
  233. }
  234. pic.BlipFill.Blip.R = SourceRelationship
  235. pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
  236. pic.SpPr.PrstGeom.Prst = "rect"
  237. twoCellAnchor.Pic = &pic
  238. twoCellAnchor.ClientData = &xdrClientData{
  239. FLocksWithSheet: formatSet.FLocksWithSheet,
  240. FPrintsWithSheet: formatSet.FPrintsWithSheet,
  241. }
  242. content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
  243. output, _ := xml.Marshal(content)
  244. f.saveFileList(drawingXML, string(output))
  245. }
  246. // addDrawingRelationships provides function to add image part relationships in
  247. // the file xl/drawings/_rels/drawing%d.xml.rels by given drawing index,
  248. // relationship type and target.
  249. func (f *File) addDrawingRelationships(index int, relType, target, targetMode string) int {
  250. var rels = "xl/drawings/_rels/drawing" + strconv.Itoa(index) + ".xml.rels"
  251. var drawingRels xlsxWorkbookRels
  252. var rID = 1
  253. var ID bytes.Buffer
  254. ID.WriteString("rId")
  255. ID.WriteString(strconv.Itoa(rID))
  256. _, ok := f.XLSX[rels]
  257. if ok {
  258. ID.Reset()
  259. xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  260. rID = len(drawingRels.Relationships) + 1
  261. ID.WriteString("rId")
  262. ID.WriteString(strconv.Itoa(rID))
  263. }
  264. drawingRels.Relationships = append(drawingRels.Relationships, xlsxWorkbookRelation{
  265. ID: ID.String(),
  266. Type: relType,
  267. Target: target,
  268. TargetMode: targetMode,
  269. })
  270. output, _ := xml.Marshal(drawingRels)
  271. f.saveFileList(rels, string(output))
  272. return rID
  273. }
  274. // countMedia provides function to get media files count storage in the folder
  275. // xl/media/image.
  276. func (f *File) countMedia() int {
  277. count := 0
  278. for k := range f.XLSX {
  279. if strings.Contains(k, "xl/media/image") {
  280. count++
  281. }
  282. }
  283. return count
  284. }
  285. // addMedia provides function to add picture into folder xl/media/image by given
  286. // file name and extension name.
  287. func (f *File) addMedia(file, ext string) {
  288. count := f.countMedia()
  289. dat, _ := ioutil.ReadFile(file)
  290. media := "xl/media/image" + strconv.Itoa(count+1) + ext
  291. f.XLSX[media] = string(dat)
  292. }
  293. // setContentTypePartImageExtensions provides function to set the content type
  294. // for relationship parts and the Main Document part.
  295. func (f *File) setContentTypePartImageExtensions() {
  296. var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false}
  297. content := f.contentTypesReader()
  298. for _, v := range content.Defaults {
  299. _, ok := imageTypes[v.Extension]
  300. if ok {
  301. imageTypes[v.Extension] = true
  302. }
  303. }
  304. for k, v := range imageTypes {
  305. if !v {
  306. content.Defaults = append(content.Defaults, xlsxDefault{
  307. Extension: k,
  308. ContentType: "image/" + k,
  309. })
  310. }
  311. }
  312. }
  313. // setContentTypePartVMLExtensions provides function to set the content type
  314. // for relationship parts and the Main Document part.
  315. func (f *File) setContentTypePartVMLExtensions() {
  316. vml := false
  317. content := f.contentTypesReader()
  318. for _, v := range content.Defaults {
  319. if v.Extension == "vml" {
  320. vml = true
  321. }
  322. }
  323. if !vml {
  324. content.Defaults = append(content.Defaults, xlsxDefault{
  325. Extension: "vml",
  326. ContentType: "application/vnd.openxmlformats-officedocument.vmlDrawing",
  327. })
  328. }
  329. }
  330. // addContentTypePart provides function to add content type part relationships
  331. // in the file [Content_Types].xml by given index.
  332. func (f *File) addContentTypePart(index int, contentType string) {
  333. setContentType := map[string]func(){
  334. "comments": f.setContentTypePartVMLExtensions,
  335. "drawings": f.setContentTypePartImageExtensions,
  336. }
  337. partNames := map[string]string{
  338. "chart": "/xl/charts/chart" + strconv.Itoa(index) + ".xml",
  339. "comments": "/xl/comments" + strconv.Itoa(index) + ".xml",
  340. "drawings": "/xl/drawings/drawing" + strconv.Itoa(index) + ".xml",
  341. "table": "/xl/tables/table" + strconv.Itoa(index) + ".xml",
  342. }
  343. contentTypes := map[string]string{
  344. "chart": "application/vnd.openxmlformats-officedocument.drawingml.chart+xml",
  345. "comments": "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  346. "drawings": "application/vnd.openxmlformats-officedocument.drawing+xml",
  347. "table": "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
  348. }
  349. s, ok := setContentType[contentType]
  350. if ok {
  351. s()
  352. }
  353. content := f.contentTypesReader()
  354. for _, v := range content.Overrides {
  355. if v.PartName == partNames[contentType] {
  356. return
  357. }
  358. }
  359. content.Overrides = append(content.Overrides, xlsxOverride{
  360. PartName: partNames[contentType],
  361. ContentType: contentTypes[contentType],
  362. })
  363. }
  364. // getSheetRelationshipsTargetByID provides function to get Target attribute
  365. // value in xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  366. // relationship index.
  367. func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
  368. name, ok := f.sheetMap[trimSheetName(sheet)]
  369. if !ok {
  370. name = strings.ToLower(sheet) + ".xml"
  371. }
  372. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  373. var sheetRels xlsxWorkbookRels
  374. xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  375. for _, v := range sheetRels.Relationships {
  376. if v.ID == rID {
  377. return v.Target
  378. }
  379. }
  380. return ""
  381. }
  382. // GetPicture provides function to get picture base name and raw content embed
  383. // in XLSX by given worksheet and cell name. This function returns the file name
  384. // in XLSX and file contents as []byte data types. For example:
  385. //
  386. // xlsx, err := excelize.OpenFile("./Workbook.xlsx")
  387. // if err != nil {
  388. // fmt.Println(err)
  389. // return
  390. // }
  391. // file, raw := xlsx.GetPicture("Sheet1", "A2")
  392. // if file == "" {
  393. // return
  394. // }
  395. // err := ioutil.WriteFile(file, raw, 0644)
  396. // if err != nil {
  397. // fmt.Println(err)
  398. // }
  399. //
  400. func (f *File) GetPicture(sheet, cell string) (string, []byte) {
  401. xlsx := f.workSheetReader(sheet)
  402. if xlsx.Drawing == nil {
  403. return "", []byte{}
  404. }
  405. target := f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  406. drawingXML := strings.Replace(target, "..", "xl", -1)
  407. _, ok := f.XLSX[drawingXML]
  408. if !ok {
  409. return "", []byte{}
  410. }
  411. decodeWsDr := decodeWsDr{}
  412. xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
  413. cell = strings.ToUpper(cell)
  414. fromCol := string(strings.Map(letterOnlyMapF, cell))
  415. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  416. row := fromRow - 1
  417. col := TitleToNumber(fromCol)
  418. drawingRelationships := strings.Replace(strings.Replace(target, "../drawings", "xl/drawings/_rels", -1), ".xml", ".xml.rels", -1)
  419. for _, anchor := range decodeWsDr.TwoCellAnchor {
  420. decodeTwoCellAnchor := decodeTwoCellAnchor{}
  421. xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
  422. if decodeTwoCellAnchor.From != nil && decodeTwoCellAnchor.Pic != nil {
  423. if decodeTwoCellAnchor.From.Col == col && decodeTwoCellAnchor.From.Row == row {
  424. xlsxWorkbookRelation := f.getDrawingRelationships(drawingRelationships, decodeTwoCellAnchor.Pic.BlipFill.Blip.Embed)
  425. _, ok := supportImageTypes[filepath.Ext(xlsxWorkbookRelation.Target)]
  426. if ok {
  427. return filepath.Base(xlsxWorkbookRelation.Target), []byte(f.XLSX[strings.Replace(xlsxWorkbookRelation.Target, "..", "xl", -1)])
  428. }
  429. }
  430. }
  431. }
  432. return "", []byte{}
  433. }
  434. // getDrawingRelationships provides function to get drawing relationships from
  435. // xl/drawings/_rels/drawing%s.xml.rels by given file name and relationship ID.
  436. func (f *File) getDrawingRelationships(rels, rID string) *xlsxWorkbookRelation {
  437. _, ok := f.XLSX[rels]
  438. if !ok {
  439. return nil
  440. }
  441. var drawingRels xlsxWorkbookRels
  442. xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  443. for _, v := range drawingRels.Relationships {
  444. if v.ID == rID {
  445. return &v
  446. }
  447. }
  448. return nil
  449. }