picture.go 16 KB

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