picture.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. // Copyright 2016 - 2021 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to
  6. // and read from XLSX / XLSM / XLTM files. Supports reading and writing
  7. // spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports
  8. // complex components by high compatibility, and provided streaming API for
  9. // generating or reading data from a worksheet with huge amounts of data. This
  10. // library needs Go version 1.15 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "encoding/json"
  15. "encoding/xml"
  16. "errors"
  17. "fmt"
  18. "image"
  19. "io"
  20. "io/ioutil"
  21. "os"
  22. "path"
  23. "path/filepath"
  24. "strconv"
  25. "strings"
  26. )
  27. // parseFormatPictureSet provides a function to parse the format settings of
  28. // the picture with default value.
  29. func parseFormatPictureSet(formatSet string) (*formatPicture, error) {
  30. format := formatPicture{
  31. FPrintsWithSheet: true,
  32. FLocksWithSheet: false,
  33. NoChangeAspect: false,
  34. Autofit: false,
  35. OffsetX: 0,
  36. OffsetY: 0,
  37. XScale: 1.0,
  38. YScale: 1.0,
  39. }
  40. err := json.Unmarshal(parseFormatSet(formatSet), &format)
  41. return &format, err
  42. }
  43. // AddPicture provides the method to add picture in a sheet by given picture
  44. // format set (such as offset, scale, aspect ratio setting and print settings)
  45. // and file path. For example:
  46. //
  47. // package main
  48. //
  49. // import (
  50. // _ "image/gif"
  51. // _ "image/jpeg"
  52. // _ "image/png"
  53. //
  54. // "github.com/360EntSecGroup-Skylar/excelize/v2"
  55. // )
  56. //
  57. // func main() {
  58. // f := excelize.NewFile()
  59. // // Insert a picture.
  60. // if err := f.AddPicture("Sheet1", "A2", "image.jpg", ""); err != nil {
  61. // fmt.Println(err)
  62. // }
  63. // // Insert a picture scaling in the cell with location hyperlink.
  64. // if err := f.AddPicture("Sheet1", "D2", "image.png", `{"x_scale": 0.5, "y_scale": 0.5, "hyperlink": "#Sheet2!D8", "hyperlink_type": "Location"}`); err != nil {
  65. // fmt.Println(err)
  66. // }
  67. // // Insert a picture offset in the cell with external hyperlink, printing and positioning support.
  68. // if err := f.AddPicture("Sheet1", "H2", "image.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, "positioning": "oneCell"}`); err != nil {
  69. // fmt.Println(err)
  70. // }
  71. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  72. // fmt.Println(err)
  73. // }
  74. // }
  75. //
  76. // LinkType defines two types of hyperlink "External" for web site or
  77. // "Location" for moving to one of cell in this workbook. When the
  78. // "hyperlink_type" is "Location", coordinates need to start with "#".
  79. //
  80. // Positioning defines two types of the position of a picture in an Excel
  81. // spreadsheet, "oneCell" (Move but don't size with cells) or "absolute"
  82. // (Don't move or size with cells). If you don't set this parameter, default
  83. // positioning is move and size with cells.
  84. func (f *File) AddPicture(sheet, cell, picture, format string) error {
  85. var err error
  86. // Check picture exists first.
  87. if _, err = os.Stat(picture); os.IsNotExist(err) {
  88. return err
  89. }
  90. ext, ok := supportImageTypes[path.Ext(picture)]
  91. if !ok {
  92. return errors.New("unsupported image extension")
  93. }
  94. file, _ := ioutil.ReadFile(picture)
  95. _, name := filepath.Split(picture)
  96. return f.AddPictureFromBytes(sheet, cell, format, name, ext, file)
  97. }
  98. // AddPictureFromBytes provides the method to add picture in a sheet by given
  99. // picture format set (such as offset, scale, aspect ratio setting and print
  100. // settings), file base name, extension name and file bytes. For example:
  101. //
  102. // package main
  103. //
  104. // import (
  105. // "fmt"
  106. // _ "image/jpeg"
  107. // "io/ioutil"
  108. //
  109. // "github.com/360EntSecGroup-Skylar/excelize/v2"
  110. // )
  111. //
  112. // func main() {
  113. // f := excelize.NewFile()
  114. //
  115. // file, err := ioutil.ReadFile("image.jpg")
  116. // if err != nil {
  117. // fmt.Println(err)
  118. // }
  119. // if err := f.AddPictureFromBytes("Sheet1", "A2", "", "Excel Logo", ".jpg", file); err != nil {
  120. // fmt.Println(err)
  121. // }
  122. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  123. // fmt.Println(err)
  124. // }
  125. // }
  126. //
  127. func (f *File) AddPictureFromBytes(sheet, cell, format, name, extension string, file []byte) error {
  128. var drawingHyperlinkRID int
  129. var hyperlinkType string
  130. ext, ok := supportImageTypes[extension]
  131. if !ok {
  132. return errors.New("unsupported image extension")
  133. }
  134. formatSet, err := parseFormatPictureSet(format)
  135. if err != nil {
  136. return err
  137. }
  138. img, _, err := image.DecodeConfig(bytes.NewReader(file))
  139. if err != nil {
  140. return err
  141. }
  142. // Read sheet data.
  143. ws, err := f.workSheetReader(sheet)
  144. if err != nil {
  145. return err
  146. }
  147. // Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  148. drawingID := f.countDrawings() + 1
  149. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  150. drawingID, drawingXML = f.prepareDrawing(ws, drawingID, sheet, drawingXML)
  151. drawingRels := "xl/drawings/_rels/drawing" + strconv.Itoa(drawingID) + ".xml.rels"
  152. mediaStr := ".." + strings.TrimPrefix(f.addMedia(file, ext), "xl")
  153. drawingRID := f.addRels(drawingRels, SourceRelationshipImage, mediaStr, hyperlinkType)
  154. // Add picture with hyperlink.
  155. if formatSet.Hyperlink != "" && formatSet.HyperlinkType != "" {
  156. if formatSet.HyperlinkType == "External" {
  157. hyperlinkType = formatSet.HyperlinkType
  158. }
  159. drawingHyperlinkRID = f.addRels(drawingRels, SourceRelationshipHyperLink, formatSet.Hyperlink, hyperlinkType)
  160. }
  161. err = f.addDrawingPicture(sheet, drawingXML, cell, name, img.Width, img.Height, drawingRID, drawingHyperlinkRID, formatSet)
  162. if err != nil {
  163. return err
  164. }
  165. f.addContentTypePart(drawingID, "drawings")
  166. f.addSheetNameSpace(sheet, SourceRelationship)
  167. return err
  168. }
  169. // deleteSheetRelationships provides a function to delete relationships in
  170. // xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  171. // relationship index.
  172. func (f *File) deleteSheetRelationships(sheet, rID string) {
  173. name, ok := f.sheetMap[trimSheetName(sheet)]
  174. if !ok {
  175. name = strings.ToLower(sheet) + ".xml"
  176. }
  177. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  178. sheetRels := f.relsReader(rels)
  179. if sheetRels == nil {
  180. sheetRels = &xlsxRelationships{}
  181. }
  182. for k, v := range sheetRels.Relationships {
  183. if v.ID == rID {
  184. sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
  185. }
  186. }
  187. f.Relationships[rels] = sheetRels
  188. }
  189. // addSheetLegacyDrawing provides a function to add legacy drawing element to
  190. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  191. func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
  192. xlsx, _ := f.workSheetReader(sheet)
  193. xlsx.LegacyDrawing = &xlsxLegacyDrawing{
  194. RID: "rId" + strconv.Itoa(rID),
  195. }
  196. }
  197. // addSheetDrawing provides a function to add drawing element to
  198. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  199. func (f *File) addSheetDrawing(sheet string, rID int) {
  200. xlsx, _ := f.workSheetReader(sheet)
  201. xlsx.Drawing = &xlsxDrawing{
  202. RID: "rId" + strconv.Itoa(rID),
  203. }
  204. }
  205. // addSheetPicture provides a function to add picture element to
  206. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  207. func (f *File) addSheetPicture(sheet string, rID int) {
  208. xlsx, _ := f.workSheetReader(sheet)
  209. xlsx.Picture = &xlsxPicture{
  210. RID: "rId" + strconv.Itoa(rID),
  211. }
  212. }
  213. // countDrawings provides a function to get drawing files count storage in the
  214. // folder xl/drawings.
  215. func (f *File) countDrawings() int {
  216. c1, c2 := 0, 0
  217. for k := range f.XLSX {
  218. if strings.Contains(k, "xl/drawings/drawing") {
  219. c1++
  220. }
  221. }
  222. for rel := range f.Drawings {
  223. if strings.Contains(rel, "xl/drawings/drawing") {
  224. c2++
  225. }
  226. }
  227. if c1 < c2 {
  228. return c2
  229. }
  230. return c1
  231. }
  232. // addDrawingPicture provides a function to add picture by given sheet,
  233. // drawingXML, cell, file name, width, height relationship index and format
  234. // sets.
  235. func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID, hyperlinkRID int, formatSet *formatPicture) error {
  236. col, row, err := CellNameToCoordinates(cell)
  237. if err != nil {
  238. return err
  239. }
  240. if formatSet.Autofit {
  241. width, height, col, row, err = f.drawingResize(sheet, cell, float64(width), float64(height), formatSet)
  242. if err != nil {
  243. return err
  244. }
  245. } else {
  246. width = int(float64(width) * formatSet.XScale)
  247. height = int(float64(height) * formatSet.YScale)
  248. }
  249. col--
  250. row--
  251. colStart, rowStart, colEnd, rowEnd, x2, y2 :=
  252. f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height)
  253. content, cNvPrID := f.drawingParser(drawingXML)
  254. twoCellAnchor := xdrCellAnchor{}
  255. twoCellAnchor.EditAs = formatSet.Positioning
  256. from := xlsxFrom{}
  257. from.Col = colStart
  258. from.ColOff = formatSet.OffsetX * EMU
  259. from.Row = rowStart
  260. from.RowOff = formatSet.OffsetY * EMU
  261. to := xlsxTo{}
  262. to.Col = colEnd
  263. to.ColOff = x2 * EMU
  264. to.Row = rowEnd
  265. to.RowOff = y2 * EMU
  266. twoCellAnchor.From = &from
  267. twoCellAnchor.To = &to
  268. pic := xlsxPic{}
  269. pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect
  270. pic.NvPicPr.CNvPr.ID = cNvPrID
  271. pic.NvPicPr.CNvPr.Descr = file
  272. pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
  273. if hyperlinkRID != 0 {
  274. pic.NvPicPr.CNvPr.HlinkClick = &xlsxHlinkClick{
  275. R: SourceRelationship.Value,
  276. RID: "rId" + strconv.Itoa(hyperlinkRID),
  277. }
  278. }
  279. pic.BlipFill.Blip.R = SourceRelationship.Value
  280. pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
  281. pic.SpPr.PrstGeom.Prst = "rect"
  282. twoCellAnchor.Pic = &pic
  283. twoCellAnchor.ClientData = &xdrClientData{
  284. FLocksWithSheet: formatSet.FLocksWithSheet,
  285. FPrintsWithSheet: formatSet.FPrintsWithSheet,
  286. }
  287. content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
  288. f.Drawings[drawingXML] = content
  289. return err
  290. }
  291. // countMedia provides a function to get media files count storage in the
  292. // folder xl/media/image.
  293. func (f *File) countMedia() int {
  294. count := 0
  295. for k := range f.XLSX {
  296. if strings.Contains(k, "xl/media/image") {
  297. count++
  298. }
  299. }
  300. return count
  301. }
  302. // addMedia provides a function to add a picture into folder xl/media/image by
  303. // given file and extension name. Duplicate images are only actually stored once
  304. // and drawings that use it will reference the same image.
  305. func (f *File) addMedia(file []byte, ext string) string {
  306. count := f.countMedia()
  307. for name, existing := range f.XLSX {
  308. if !strings.HasPrefix(name, "xl/media/image") {
  309. continue
  310. }
  311. if bytes.Equal(file, existing) {
  312. return name
  313. }
  314. }
  315. media := "xl/media/image" + strconv.Itoa(count+1) + ext
  316. f.XLSX[media] = file
  317. return media
  318. }
  319. // setContentTypePartImageExtensions provides a function to set the content
  320. // type for relationship parts and the Main Document part.
  321. func (f *File) setContentTypePartImageExtensions() {
  322. var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false, "tiff": false}
  323. content := f.contentTypesReader()
  324. for _, v := range content.Defaults {
  325. _, ok := imageTypes[v.Extension]
  326. if ok {
  327. imageTypes[v.Extension] = true
  328. }
  329. }
  330. for k, v := range imageTypes {
  331. if !v {
  332. content.Defaults = append(content.Defaults, xlsxDefault{
  333. Extension: k,
  334. ContentType: "image/" + k,
  335. })
  336. }
  337. }
  338. }
  339. // setContentTypePartVMLExtensions provides a function to set the content type
  340. // for relationship parts and the Main Document part.
  341. func (f *File) setContentTypePartVMLExtensions() {
  342. vml := false
  343. content := f.contentTypesReader()
  344. for _, v := range content.Defaults {
  345. if v.Extension == "vml" {
  346. vml = true
  347. }
  348. }
  349. if !vml {
  350. content.Defaults = append(content.Defaults, xlsxDefault{
  351. Extension: "vml",
  352. ContentType: ContentTypeVML,
  353. })
  354. }
  355. }
  356. // addContentTypePart provides a function to add content type part
  357. // relationships in the file [Content_Types].xml by given index.
  358. func (f *File) addContentTypePart(index int, contentType string) {
  359. setContentType := map[string]func(){
  360. "comments": f.setContentTypePartVMLExtensions,
  361. "drawings": f.setContentTypePartImageExtensions,
  362. }
  363. partNames := map[string]string{
  364. "chart": "/xl/charts/chart" + strconv.Itoa(index) + ".xml",
  365. "chartsheet": "/xl/chartsheets/sheet" + strconv.Itoa(index) + ".xml",
  366. "comments": "/xl/comments" + strconv.Itoa(index) + ".xml",
  367. "drawings": "/xl/drawings/drawing" + strconv.Itoa(index) + ".xml",
  368. "table": "/xl/tables/table" + strconv.Itoa(index) + ".xml",
  369. "pivotTable": "/xl/pivotTables/pivotTable" + strconv.Itoa(index) + ".xml",
  370. "pivotCache": "/xl/pivotCache/pivotCacheDefinition" + strconv.Itoa(index) + ".xml",
  371. "sharedStrings": "/xl/sharedStrings.xml",
  372. }
  373. contentTypes := map[string]string{
  374. "chart": ContentTypeDrawingML,
  375. "chartsheet": ContentTypeSpreadSheetMLChartsheet,
  376. "comments": ContentTypeSpreadSheetMLComments,
  377. "drawings": ContentTypeDrawing,
  378. "table": ContentTypeSpreadSheetMLTable,
  379. "pivotTable": ContentTypeSpreadSheetMLPivotTable,
  380. "pivotCache": ContentTypeSpreadSheetMLPivotCacheDefinition,
  381. "sharedStrings": ContentTypeSpreadSheetMLSharedStrings,
  382. }
  383. s, ok := setContentType[contentType]
  384. if ok {
  385. s()
  386. }
  387. content := f.contentTypesReader()
  388. for _, v := range content.Overrides {
  389. if v.PartName == partNames[contentType] {
  390. return
  391. }
  392. }
  393. content.Overrides = append(content.Overrides, xlsxOverride{
  394. PartName: partNames[contentType],
  395. ContentType: contentTypes[contentType],
  396. })
  397. }
  398. // getSheetRelationshipsTargetByID provides a function to get Target attribute
  399. // value in xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  400. // relationship index.
  401. func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
  402. name, ok := f.sheetMap[trimSheetName(sheet)]
  403. if !ok {
  404. name = strings.ToLower(sheet) + ".xml"
  405. }
  406. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  407. sheetRels := f.relsReader(rels)
  408. if sheetRels == nil {
  409. sheetRels = &xlsxRelationships{}
  410. }
  411. for _, v := range sheetRels.Relationships {
  412. if v.ID == rID {
  413. return v.Target
  414. }
  415. }
  416. return ""
  417. }
  418. // GetPicture provides a function to get picture base name and raw content
  419. // embed in XLSX by given worksheet and cell name. This function returns the
  420. // file name in XLSX and file contents as []byte data types. For example:
  421. //
  422. // f, err := excelize.OpenFile("Book1.xlsx")
  423. // if err != nil {
  424. // fmt.Println(err)
  425. // return
  426. // }
  427. // file, raw, err := f.GetPicture("Sheet1", "A2")
  428. // if err != nil {
  429. // fmt.Println(err)
  430. // return
  431. // }
  432. // if err := ioutil.WriteFile(file, raw, 0644); err != nil {
  433. // fmt.Println(err)
  434. // }
  435. //
  436. func (f *File) GetPicture(sheet, cell string) (string, []byte, error) {
  437. col, row, err := CellNameToCoordinates(cell)
  438. if err != nil {
  439. return "", nil, err
  440. }
  441. col--
  442. row--
  443. ws, err := f.workSheetReader(sheet)
  444. if err != nil {
  445. return "", nil, err
  446. }
  447. if ws.Drawing == nil {
  448. return "", nil, err
  449. }
  450. target := f.getSheetRelationshipsTargetByID(sheet, ws.Drawing.RID)
  451. drawingXML := strings.Replace(target, "..", "xl", -1)
  452. _, ok := f.XLSX[drawingXML]
  453. if !ok {
  454. return "", nil, err
  455. }
  456. drawingRelationships := strings.Replace(
  457. strings.Replace(target, "../drawings", "xl/drawings/_rels", -1), ".xml", ".xml.rels", -1)
  458. return f.getPicture(row, col, drawingXML, drawingRelationships)
  459. }
  460. // DeletePicture provides a function to delete charts in spreadsheet by given
  461. // worksheet and cell name. Note that the image file won't be deleted from the
  462. // document currently.
  463. func (f *File) DeletePicture(sheet, cell string) (err error) {
  464. col, row, err := CellNameToCoordinates(cell)
  465. if err != nil {
  466. return
  467. }
  468. col--
  469. row--
  470. ws, err := f.workSheetReader(sheet)
  471. if err != nil {
  472. return
  473. }
  474. if ws.Drawing == nil {
  475. return
  476. }
  477. drawingXML := strings.Replace(f.getSheetRelationshipsTargetByID(sheet, ws.Drawing.RID), "..", "xl", -1)
  478. return f.deleteDrawing(col, row, drawingXML, "Pic")
  479. }
  480. // getPicture provides a function to get picture base name and raw content
  481. // embed in spreadsheet by given coordinates and drawing relationships.
  482. func (f *File) getPicture(row, col int, drawingXML, drawingRelationships string) (ret string, buf []byte, err error) {
  483. var (
  484. wsDr *xlsxWsDr
  485. ok bool
  486. deWsDr *decodeWsDr
  487. drawRel *xlsxRelationship
  488. deTwoCellAnchor *decodeTwoCellAnchor
  489. )
  490. wsDr, _ = f.drawingParser(drawingXML)
  491. if ret, buf = f.getPictureFromWsDr(row, col, drawingRelationships, wsDr); len(buf) > 0 {
  492. return
  493. }
  494. deWsDr = new(decodeWsDr)
  495. if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(drawingXML)))).
  496. Decode(deWsDr); err != nil && err != io.EOF {
  497. err = fmt.Errorf("xml decode error: %s", err)
  498. return
  499. }
  500. err = nil
  501. for _, anchor := range deWsDr.TwoCellAnchor {
  502. deTwoCellAnchor = new(decodeTwoCellAnchor)
  503. if err = f.xmlNewDecoder(strings.NewReader("<decodeTwoCellAnchor>" + anchor.Content + "</decodeTwoCellAnchor>")).
  504. Decode(deTwoCellAnchor); err != nil && err != io.EOF {
  505. err = fmt.Errorf("xml decode error: %s", err)
  506. return
  507. }
  508. if err = nil; deTwoCellAnchor.From != nil && deTwoCellAnchor.Pic != nil {
  509. if deTwoCellAnchor.From.Col == col && deTwoCellAnchor.From.Row == row {
  510. drawRel = f.getDrawingRelationships(drawingRelationships, deTwoCellAnchor.Pic.BlipFill.Blip.Embed)
  511. if _, ok = supportImageTypes[filepath.Ext(drawRel.Target)]; ok {
  512. ret, buf = filepath.Base(drawRel.Target), f.XLSX[strings.Replace(drawRel.Target, "..", "xl", -1)]
  513. return
  514. }
  515. }
  516. }
  517. }
  518. return
  519. }
  520. // getPictureFromWsDr provides a function to get picture base name and raw
  521. // content in worksheet drawing by given coordinates and drawing
  522. // relationships.
  523. func (f *File) getPictureFromWsDr(row, col int, drawingRelationships string, wsDr *xlsxWsDr) (ret string, buf []byte) {
  524. var (
  525. ok bool
  526. anchor *xdrCellAnchor
  527. drawRel *xlsxRelationship
  528. )
  529. for _, anchor = range wsDr.TwoCellAnchor {
  530. if anchor.From != nil && anchor.Pic != nil {
  531. if anchor.From.Col == col && anchor.From.Row == row {
  532. if drawRel = f.getDrawingRelationships(drawingRelationships,
  533. anchor.Pic.BlipFill.Blip.Embed); drawRel != nil {
  534. if _, ok = supportImageTypes[filepath.Ext(drawRel.Target)]; ok {
  535. ret, buf = filepath.Base(drawRel.Target), f.XLSX[strings.Replace(drawRel.Target, "..", "xl", -1)]
  536. return
  537. }
  538. }
  539. }
  540. }
  541. }
  542. return
  543. }
  544. // getDrawingRelationships provides a function to get drawing relationships
  545. // from xl/drawings/_rels/drawing%s.xml.rels by given file name and
  546. // relationship ID.
  547. func (f *File) getDrawingRelationships(rels, rID string) *xlsxRelationship {
  548. if drawingRels := f.relsReader(rels); drawingRels != nil {
  549. for _, v := range drawingRels.Relationships {
  550. if v.ID == rID {
  551. return &v
  552. }
  553. }
  554. }
  555. return nil
  556. }
  557. // drawingsWriter provides a function to save xl/drawings/drawing%d.xml after
  558. // serialize structure.
  559. func (f *File) drawingsWriter() {
  560. for path, d := range f.Drawings {
  561. if d != nil {
  562. v, _ := xml.Marshal(d)
  563. f.saveFileList(path, v)
  564. }
  565. }
  566. }
  567. // drawingResize calculate the height and width after resizing.
  568. func (f *File) drawingResize(sheet string, cell string, width, height float64, formatSet *formatPicture) (w, h, c, r int, err error) {
  569. var mergeCells []MergeCell
  570. mergeCells, err = f.GetMergeCells(sheet)
  571. if err != nil {
  572. return
  573. }
  574. var rng []int
  575. var inMergeCell bool
  576. if c, r, err = CellNameToCoordinates(cell); err != nil {
  577. return
  578. }
  579. cellWidth, cellHeight := f.getColWidth(sheet, c), f.getRowHeight(sheet, r)
  580. for _, mergeCell := range mergeCells {
  581. if inMergeCell {
  582. continue
  583. }
  584. if inMergeCell, err = f.checkCellInArea(cell, mergeCell[0]); err != nil {
  585. return
  586. }
  587. if inMergeCell {
  588. rng, _ = areaRangeToCoordinates(mergeCell.GetStartAxis(), mergeCell.GetEndAxis())
  589. _ = sortCoordinates(rng)
  590. }
  591. }
  592. if inMergeCell {
  593. cellWidth, cellHeight = 0, 0
  594. c, r = rng[0], rng[1]
  595. for col := rng[0] - 1; col < rng[2]; col++ {
  596. cellWidth += f.getColWidth(sheet, col)
  597. }
  598. for row := rng[1] - 1; row < rng[3]; row++ {
  599. cellHeight += f.getRowHeight(sheet, row)
  600. }
  601. }
  602. if float64(cellWidth) < width {
  603. asp := float64(cellWidth) / width
  604. width, height = float64(cellWidth), height*asp
  605. }
  606. if float64(cellHeight) < height {
  607. asp := float64(cellHeight) / height
  608. height, width = float64(cellHeight), width*asp
  609. }
  610. width, height = width-float64(formatSet.OffsetX), height-float64(formatSet.OffsetY)
  611. w, h = int(width*formatSet.XScale), int(height*formatSet.YScale)
  612. return
  613. }