picture.go 16 KB

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