embed.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package mappers
  2. import (
  3. "crypto/md5"
  4. "encoding/binary"
  5. "github.com/kpmy/odf/xmlns"
  6. "github.com/kpmy/odf/xmlns/draw"
  7. "github.com/kpmy/odf/xmlns/svg"
  8. "github.com/kpmy/odf/xmlns/text"
  9. "github.com/kpmy/odf/xmlns/xlink"
  10. "io"
  11. "math/rand"
  12. "strconv"
  13. "time"
  14. )
  15. //Draw holds image data and it's mimetype
  16. type Draw struct {
  17. rd io.Reader
  18. mime xmlns.Mime
  19. }
  20. //NewDraw constructor
  21. func NewDraw(source io.Reader, _mime xmlns.Mime) *Draw {
  22. return &Draw{rd: source, mime: _mime}
  23. }
  24. func nextUrl() (ret string) {
  25. t := time.Now().UnixNano()
  26. seed := rand.Int63()
  27. h := md5.New()
  28. binary.Write(h, binary.LittleEndian, t)
  29. binary.Write(h, binary.LittleEndian, seed)
  30. data := h.Sum(nil)
  31. for _, x := range data {
  32. ret = ret + strconv.FormatInt(int64(x), 16)
  33. }
  34. return
  35. }
  36. //Reader implements generators.Embeddable
  37. func (d *Draw) Reader() io.Reader {
  38. return d.rd
  39. }
  40. func (d *Draw) MimeType() xmlns.Mime {
  41. return d.mime
  42. }
  43. //WriteTo writes image (link to image) to document model, don't forget to pass Draw as Embeddable to package generator
  44. func (d *Draw) WriteTo(fm *Formatter, name string, w, h interface{}) string {
  45. fm.defaultParaMapper.makePara()
  46. wr := fm.m.NewWriter()
  47. wr.Pos(fm.defaultParaMapper.rider.Pos())
  48. wr.WritePos(New(draw.Frame))
  49. wr.Attr(draw.Name, name).Attr(text.AnchorType, text.Paragraph).Attr(svg.Width, w).Attr(svg.Height, h)
  50. wr.WritePos(New(draw.Image))
  51. url := "Pictures/" + nextUrl()
  52. wr.Attr(xlink.Href, url).Attr(xlink.Type, xlink.Simple).Attr(xlink.Show, xlink.Embed).Attr(xlink.Actuate, xlink.OnLoad)
  53. return url
  54. }