template.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package gofpdf
  2. /*
  3. * Copyright (c) 2015 Kurt Jung (Gmail: kurt.w.jung),
  4. * Marcus Downing, Jan Slabon (Setasign)
  5. *
  6. * Permission to use, copy, modify, and distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  13. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  15. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  16. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. */
  18. import (
  19. "encoding/gob"
  20. "sort"
  21. )
  22. // CreateTemplate defines a new template using the current page size.
  23. func (f *Fpdf) CreateTemplate(fn func(*Tpl)) Template {
  24. return newTpl(PointType{0, 0}, f.curPageSize, f.defOrientation, f.unitStr, f.fontDirStr, fn, f)
  25. }
  26. // CreateTemplateCustom starts a template, using the given bounds.
  27. func (f *Fpdf) CreateTemplateCustom(corner PointType, size SizeType, fn func(*Tpl)) Template {
  28. return newTpl(corner, size, f.defOrientation, f.unitStr, f.fontDirStr, fn, f)
  29. }
  30. // CreateTemplate creates a template that is not attached to any document.
  31. //
  32. // This function is deprecated; it incorrectly assumes that a page with a width
  33. // smaller than its height is oriented in portrait mode, otherwise it assumes
  34. // landscape mode. This causes problems when placing the template in a master
  35. // document where this condition does not apply. CreateTpl() is a similar
  36. // function that lets you specify the orientation to avoid this problem.
  37. func CreateTemplate(corner PointType, size SizeType, unitStr, fontDirStr string, fn func(*Tpl)) Template {
  38. orientationStr := "p"
  39. if size.Wd > size.Ht {
  40. orientationStr = "l"
  41. }
  42. return CreateTpl(corner, size, orientationStr, unitStr, fontDirStr, fn)
  43. }
  44. // CreateTpl creates a template not attached to any document
  45. func CreateTpl(corner PointType, size SizeType, orientationStr, unitStr, fontDirStr string, fn func(*Tpl)) Template {
  46. return newTpl(corner, size, orientationStr, unitStr, fontDirStr, fn, nil)
  47. }
  48. // UseTemplate adds a template to the current page or another template,
  49. // using the size and position at which it was originally written.
  50. func (f *Fpdf) UseTemplate(t Template) {
  51. if t == nil {
  52. f.SetErrorf("template is nil")
  53. return
  54. }
  55. corner, size := t.Size()
  56. f.UseTemplateScaled(t, corner, size)
  57. }
  58. // UseTemplateScaled adds a template to the current page or another template,
  59. // using the given page coordinates.
  60. func (f *Fpdf) UseTemplateScaled(t Template, corner PointType, size SizeType) {
  61. if t == nil {
  62. f.SetErrorf("template is nil")
  63. return
  64. }
  65. // You have to add at least a page first
  66. if f.page <= 0 {
  67. f.SetErrorf("cannot use a template without first adding a page")
  68. return
  69. }
  70. // make a note of the fact that we actually use this template, as well as any other templates,
  71. // images or fonts it uses
  72. f.templates[t.ID()] = t
  73. for _, tt := range t.Templates() {
  74. f.templates[tt.ID()] = tt
  75. }
  76. for name, ti := range t.Images() {
  77. name = sprintf("t%s-%s", t.ID(), name)
  78. f.images[name] = ti
  79. }
  80. // template data
  81. _, templateSize := t.Size()
  82. scaleX := size.Wd / templateSize.Wd
  83. scaleY := size.Ht / templateSize.Ht
  84. tx := corner.X * f.k
  85. ty := (f.curPageSize.Ht - corner.Y - size.Ht) * f.k
  86. f.outf("q %.4f 0 0 %.4f %.4f %.4f cm", scaleX, scaleY, tx, ty) // Translate
  87. f.outf("/TPL%s Do Q", t.ID())
  88. }
  89. // Template is an object that can be written to, then used and re-used any number of times within a document.
  90. type Template interface {
  91. ID() string
  92. Size() (PointType, SizeType)
  93. Bytes() []byte
  94. Images() map[string]*ImageInfoType
  95. Templates() []Template
  96. NumPages() int
  97. FromPage(int) (Template, error)
  98. FromPages() []Template
  99. Serialize() ([]byte, error)
  100. gob.GobDecoder
  101. gob.GobEncoder
  102. }
  103. func (f *Fpdf) templateFontCatalog() {
  104. var keyList []string
  105. var font fontDefType
  106. var key string
  107. f.out("/Font <<")
  108. for key = range f.fonts {
  109. keyList = append(keyList, key)
  110. }
  111. if f.catalogSort {
  112. sort.Strings(keyList)
  113. }
  114. for _, key = range keyList {
  115. font = f.fonts[key]
  116. f.outf("/F%s %d 0 R", font.i, font.N)
  117. }
  118. f.out(">>")
  119. }
  120. // putTemplates writes the templates to the PDF
  121. func (f *Fpdf) putTemplates() {
  122. filter := ""
  123. if f.compress {
  124. filter = "/Filter /FlateDecode "
  125. }
  126. templates := sortTemplates(f.templates, f.catalogSort)
  127. var t Template
  128. for _, t = range templates {
  129. corner, size := t.Size()
  130. f.newobj()
  131. f.templateObjects[t.ID()] = f.n
  132. f.outf("<<%s/Type /XObject", filter)
  133. f.out("/Subtype /Form")
  134. f.out("/Formtype 1")
  135. f.outf("/BBox [%.2f %.2f %.2f %.2f]", corner.X*f.k, corner.Y*f.k, (corner.X+size.Wd)*f.k, (corner.Y+size.Ht)*f.k)
  136. if corner.X != 0 || corner.Y != 0 {
  137. f.outf("/Matrix [1 0 0 1 %.5f %.5f]", -corner.X*f.k*2, corner.Y*f.k*2)
  138. }
  139. // Template's resource dictionary
  140. f.out("/Resources ")
  141. f.out("<</ProcSet [/PDF /Text /ImageB /ImageC /ImageI]")
  142. f.templateFontCatalog()
  143. tImages := t.Images()
  144. tTemplates := t.Templates()
  145. if len(tImages) > 0 || len(tTemplates) > 0 {
  146. f.out("/XObject <<")
  147. {
  148. var key string
  149. var keyList []string
  150. var ti *ImageInfoType
  151. for key = range tImages {
  152. keyList = append(keyList, key)
  153. }
  154. if gl.catalogSort {
  155. sort.Strings(keyList)
  156. }
  157. for _, key = range keyList {
  158. // for _, ti := range tImages {
  159. ti = tImages[key]
  160. f.outf("/I%s %d 0 R", ti.i, ti.n)
  161. }
  162. }
  163. for _, tt := range tTemplates {
  164. id := tt.ID()
  165. if objID, ok := f.templateObjects[id]; ok {
  166. f.outf("/TPL%s %d 0 R", id, objID)
  167. }
  168. }
  169. f.out(">>")
  170. }
  171. f.out(">>")
  172. // Write the template's byte stream
  173. buffer := t.Bytes()
  174. // fmt.Println("Put template bytes", string(buffer[:]))
  175. if f.compress {
  176. buffer = sliceCompress(buffer)
  177. }
  178. f.outf("/Length %d >>", len(buffer))
  179. f.putstream(buffer)
  180. f.out("endobj")
  181. }
  182. }
  183. func templateKeyList(mp map[string]Template, sort bool) (keyList []string) {
  184. var key string
  185. for key = range mp {
  186. keyList = append(keyList, key)
  187. }
  188. if sort {
  189. gensort(len(keyList),
  190. func(a, b int) bool {
  191. return keyList[a] < keyList[b]
  192. },
  193. func(a, b int) {
  194. keyList[a], keyList[b] = keyList[b], keyList[a]
  195. })
  196. }
  197. return
  198. }
  199. // sortTemplates puts templates in a suitable order based on dependices
  200. func sortTemplates(templates map[string]Template, catalogSort bool) []Template {
  201. chain := make([]Template, 0, len(templates)*2)
  202. // build a full set of dependency chains
  203. var keyList []string
  204. var key string
  205. var t Template
  206. keyList = templateKeyList(templates, catalogSort)
  207. for _, key = range keyList {
  208. t = templates[key]
  209. tlist := templateChainDependencies(t)
  210. for _, tt := range tlist {
  211. if tt != nil {
  212. chain = append(chain, tt)
  213. }
  214. }
  215. }
  216. // reduce that to make a simple list
  217. sorted := make([]Template, 0, len(templates))
  218. chain:
  219. for _, t := range chain {
  220. for _, already := range sorted {
  221. if t == already {
  222. continue chain
  223. }
  224. }
  225. sorted = append(sorted, t)
  226. }
  227. return sorted
  228. }
  229. // templateChainDependencies is a recursive function for determining the full chain of template dependencies
  230. func templateChainDependencies(template Template) []Template {
  231. requires := template.Templates()
  232. chain := make([]Template, len(requires)*2)
  233. for _, req := range requires {
  234. chain = append(chain, templateChainDependencies(req)...)
  235. }
  236. chain = append(chain, template)
  237. return chain
  238. }
  239. // < 0002640 31 20 31 32 20 30 20 52 0a 2f 54 50 4c 32 20 31 |1 12 0 R./TPL2 1|
  240. // < 0002650 35 20 30 20 52 0a 2f 54 50 4c 31 20 31 34 20 30 |5 0 R./TPL1 14 0|
  241. // > 0002640 31 20 31 32 20 30 20 52 0a 2f 54 50 4c 31 20 31 |1 12 0 R./TPL1 1|
  242. // > 0002650 34 20 30 20 52 0a 2f 54 50 4c 32 20 31 35 20 30 |4 0 R./TPL2 15 0|