def.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. /*
  2. * Copyright (c) 2013-2014 Kurt Jung (Gmail: kurt.w.jung)
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. package gofpdf
  17. import (
  18. "bytes"
  19. "crypto/sha1"
  20. "encoding/gob"
  21. "encoding/json"
  22. "fmt"
  23. "io"
  24. "time"
  25. )
  26. // Version of FPDF from which this package is derived
  27. const (
  28. cnFpdfVersion = "1.7"
  29. )
  30. type blendModeType struct {
  31. strokeStr, fillStr, modeStr string
  32. objNum int
  33. }
  34. type gradientType struct {
  35. tp int // 2: linear, 3: radial
  36. clr1Str, clr2Str string
  37. x1, y1, x2, y2, r float64
  38. objNum int
  39. }
  40. const (
  41. // OrientationPortrait represents the portrait orientation.
  42. OrientationPortrait = "portrait"
  43. // OrientationLandscape represents the landscape orientation.
  44. OrientationLandscape = "landscape"
  45. )
  46. const (
  47. // UnitPoint represents the size unit point
  48. UnitPoint = "pt"
  49. // UnitMillimeter represents the size unit millimeter
  50. UnitMillimeter = "mm"
  51. // UnitCentimeter represents the size unit centimeter
  52. UnitCentimeter = "cm"
  53. // UnitInch represents the size unit inch
  54. UnitInch = "inch"
  55. )
  56. const (
  57. // PageSizeA3 represents DIN/ISO A3 page size
  58. PageSizeA3 = "A3"
  59. // PageSizeA4 represents DIN/ISO A4 page size
  60. PageSizeA4 = "A4"
  61. // PageSizeA5 represents DIN/ISO A5 page size
  62. PageSizeA5 = "A5"
  63. // PageSizeLetter represents US Letter page size
  64. PageSizeLetter = "Letter"
  65. // PageSizeLegal represents US Legal page size
  66. PageSizeLegal = "Legal"
  67. )
  68. const (
  69. // BorderNone set no border
  70. BorderNone = ""
  71. // BorderFull sets a full border
  72. BorderFull = "1"
  73. // BorderLeft sets the border on the left side
  74. BorderLeft = "L"
  75. // BorderTop sets the border at the top
  76. BorderTop = "T"
  77. // BorderRight sets the border on the right side
  78. BorderRight = "R"
  79. // BorderBottom sets the border on the bottom
  80. BorderBottom = "B"
  81. )
  82. const (
  83. // LineBreakNone disables linebreak
  84. LineBreakNone = 0
  85. // LineBreakNormal enables normal linebreak
  86. LineBreakNormal = 1
  87. // LineBreakBelow enables linebreak below
  88. LineBreakBelow = 2
  89. )
  90. const (
  91. // AlignLeft left aligns the cell
  92. AlignLeft = "L"
  93. // AlignRight right aligns the cell
  94. AlignRight = "R"
  95. // AlignCenter centers the cell
  96. AlignCenter = "C"
  97. // AlignTop aligns the cell to the top
  98. AlignTop = "T"
  99. // AlignBottom aligns the cell to the bottom
  100. AlignBottom = "B"
  101. // AlignMiddle aligns the cell to the middle
  102. AlignMiddle = "M"
  103. // AlignBaseline aligns the cell to the baseline
  104. AlignBaseline = "B"
  105. )
  106. type colorMode int
  107. const (
  108. colorModeRGB colorMode = iota
  109. colorModeSpot
  110. colorModeCMYK
  111. )
  112. type colorType struct {
  113. r, g, b float64
  114. ir, ig, ib int
  115. mode colorMode
  116. spotStr string // name of current spot color
  117. gray bool
  118. str string
  119. }
  120. // SpotColorType specifies a named spot color value
  121. type spotColorType struct {
  122. id, objID int
  123. val cmykColorType
  124. }
  125. // CMYKColorType specifies an ink-based CMYK color value
  126. type cmykColorType struct {
  127. c, m, y, k byte // 0% to 100%
  128. }
  129. // SizeType fields Wd and Ht specify the horizontal and vertical extents of a
  130. // document element such as a page.
  131. type SizeType struct {
  132. Wd, Ht float64
  133. }
  134. // PointType fields X and Y specify the horizontal and vertical coordinates of
  135. // a point, typically used in drawing.
  136. type PointType struct {
  137. X, Y float64
  138. }
  139. // XY returns the X and Y components of the receiver point.
  140. func (p PointType) XY() (float64, float64) {
  141. return p.X, p.Y
  142. }
  143. // ImageInfoType contains size, color and other information about an image.
  144. // Changes to this structure should be reflected in its GobEncode and GobDecode
  145. // methods.
  146. type ImageInfoType struct {
  147. data []byte // Raw image data
  148. smask []byte // Soft Mask, an 8bit per-pixel transparency mask
  149. n int // Image object number
  150. w float64 // Width
  151. h float64 // Height
  152. cs string // Color space
  153. pal []byte // Image color palette
  154. bpc int // Bits Per Component
  155. f string // Image filter
  156. dp string // DecodeParms
  157. trns []int // Transparency mask
  158. scale float64 // Document scale factor
  159. dpi float64 // Dots-per-inch found from image file (png only)
  160. i string // SHA-1 checksum of the above values.
  161. }
  162. func generateImageID(info *ImageInfoType) (string, error) {
  163. b, err := info.GobEncode()
  164. return fmt.Sprintf("%x", sha1.Sum(b)), err
  165. }
  166. // GobEncode encodes the receiving image to a byte slice.
  167. func (info *ImageInfoType) GobEncode() (buf []byte, err error) {
  168. fields := []interface{}{info.data, info.smask, info.n, info.w, info.h, info.cs,
  169. info.pal, info.bpc, info.f, info.dp, info.trns, info.scale, info.dpi}
  170. w := new(bytes.Buffer)
  171. encoder := gob.NewEncoder(w)
  172. for j := 0; j < len(fields) && err == nil; j++ {
  173. err = encoder.Encode(fields[j])
  174. }
  175. if err == nil {
  176. buf = w.Bytes()
  177. }
  178. return
  179. }
  180. // GobDecode decodes the specified byte buffer (generated by GobEncode) into
  181. // the receiving image.
  182. func (info *ImageInfoType) GobDecode(buf []byte) (err error) {
  183. fields := []interface{}{&info.data, &info.smask, &info.n, &info.w, &info.h,
  184. &info.cs, &info.pal, &info.bpc, &info.f, &info.dp, &info.trns, &info.scale, &info.dpi}
  185. r := bytes.NewBuffer(buf)
  186. decoder := gob.NewDecoder(r)
  187. for j := 0; j < len(fields) && err == nil; j++ {
  188. err = decoder.Decode(fields[j])
  189. }
  190. info.i, err = generateImageID(info)
  191. return
  192. }
  193. // PointConvert returns the value of pt, expressed in points (1/72 inch), as a
  194. // value expressed in the unit of measure specified in New(). Since font
  195. // management in Fpdf uses points, this method can help with line height
  196. // calculations and other methods that require user units.
  197. func (f *Fpdf) PointConvert(pt float64) (u float64) {
  198. return pt / f.k
  199. }
  200. // PointToUnitConvert is an alias for PointConvert.
  201. func (f *Fpdf) PointToUnitConvert(pt float64) (u float64) {
  202. return pt / f.k
  203. }
  204. // UnitToPointConvert returns the value of u, expressed in the unit of measure
  205. // specified in New(), as a value expressed in points (1/72 inch). Since font
  206. // management in Fpdf uses points, this method can help with setting font sizes
  207. // based on the sizes of other non-font page elements.
  208. func (f *Fpdf) UnitToPointConvert(u float64) (pt float64) {
  209. return u * f.k
  210. }
  211. // Extent returns the width and height of the image in the units of the Fpdf
  212. // object.
  213. func (info *ImageInfoType) Extent() (wd, ht float64) {
  214. return info.Width(), info.Height()
  215. }
  216. // Width returns the width of the image in the units of the Fpdf object.
  217. func (info *ImageInfoType) Width() float64 {
  218. return info.w / (info.scale * info.dpi / 72)
  219. }
  220. // Height returns the height of the image in the units of the Fpdf object.
  221. func (info *ImageInfoType) Height() float64 {
  222. return info.h / (info.scale * info.dpi / 72)
  223. }
  224. // SetDpi sets the dots per inch for an image. PNG images MAY have their dpi
  225. // set automatically, if the image specifies it. DPI information is not
  226. // currently available automatically for JPG and GIF images, so if it's
  227. // important to you, you can set it here. It defaults to 72 dpi.
  228. func (info *ImageInfoType) SetDpi(dpi float64) {
  229. info.dpi = dpi
  230. }
  231. type fontFileType struct {
  232. length1, length2 int64
  233. n int
  234. embedded bool
  235. content []byte
  236. fontType string
  237. }
  238. type linkType struct {
  239. x, y, wd, ht float64
  240. link int // Auto-generated internal link ID or...
  241. linkStr string // ...application-provided external link string
  242. }
  243. type intLinkType struct {
  244. page int
  245. y float64
  246. }
  247. // outlineType is used for a sidebar outline of bookmarks
  248. type outlineType struct {
  249. text string
  250. level, parent, first, last, next, prev int
  251. y float64
  252. p int
  253. }
  254. // InitType is used with NewCustom() to customize an Fpdf instance.
  255. // OrientationStr, UnitStr, SizeStr and FontDirStr correspond to the arguments
  256. // accepted by New(). If the Wd and Ht fields of Size are each greater than
  257. // zero, Size will be used to set the default page size rather than SizeStr. Wd
  258. // and Ht are specified in the units of measure indicated by UnitStr.
  259. type InitType struct {
  260. OrientationStr string
  261. UnitStr string
  262. SizeStr string
  263. Size SizeType
  264. FontDirStr string
  265. }
  266. // FontLoader is used to read fonts (JSON font specification and zlib compressed font binaries)
  267. // from arbitrary locations (e.g. files, zip files, embedded font resources).
  268. //
  269. // Open provides an io.Reader for the specified font file (.json or .z). The file name
  270. // never includes a path. Open returns an error if the specified file cannot be opened.
  271. type FontLoader interface {
  272. Open(name string) (io.Reader, error)
  273. }
  274. // Pdf defines the interface used for various methods. It is implemented by the
  275. // main FPDF instance as well as templates.
  276. type Pdf interface {
  277. AddFont(familyStr, styleStr, fileStr string)
  278. AddFontFromBytes(familyStr, styleStr string, jsonFileBytes, zFileBytes []byte)
  279. AddFontFromReader(familyStr, styleStr string, r io.Reader)
  280. AddLayer(name string, visible bool) (layerID int)
  281. AddLink() int
  282. AddPage()
  283. AddPageFormat(orientationStr string, size SizeType)
  284. AddSpotColor(nameStr string, c, m, y, k byte)
  285. AliasNbPages(aliasStr string)
  286. ArcTo(x, y, rx, ry, degRotate, degStart, degEnd float64)
  287. Arc(x, y, rx, ry, degRotate, degStart, degEnd float64, styleStr string)
  288. BeginLayer(id int)
  289. Beziergon(points []PointType, styleStr string)
  290. Bookmark(txtStr string, level int, y float64)
  291. CellFormat(w, h float64, txtStr, borderStr string, ln int, alignStr string, fill bool, link int, linkStr string)
  292. Cellf(w, h float64, fmtStr string, args ...interface{})
  293. Cell(w, h float64, txtStr string)
  294. Circle(x, y, r float64, styleStr string)
  295. ClearError()
  296. ClipCircle(x, y, r float64, outline bool)
  297. ClipEllipse(x, y, rx, ry float64, outline bool)
  298. ClipEnd()
  299. ClipPolygon(points []PointType, outline bool)
  300. ClipRect(x, y, w, h float64, outline bool)
  301. ClipRoundedRect(x, y, w, h, r float64, outline bool)
  302. ClipText(x, y float64, txtStr string, outline bool)
  303. Close()
  304. ClosePath()
  305. CreateTemplateCustom(corner PointType, size SizeType, fn func(*Tpl)) Template
  306. CreateTemplate(fn func(*Tpl)) Template
  307. CurveBezierCubicTo(cx0, cy0, cx1, cy1, x, y float64)
  308. CurveBezierCubic(x0, y0, cx0, cy0, cx1, cy1, x1, y1 float64, styleStr string)
  309. CurveCubic(x0, y0, cx0, cy0, x1, y1, cx1, cy1 float64, styleStr string)
  310. CurveTo(cx, cy, x, y float64)
  311. Curve(x0, y0, cx, cy, x1, y1 float64, styleStr string)
  312. DrawPath(styleStr string)
  313. Ellipse(x, y, rx, ry, degRotate float64, styleStr string)
  314. EndLayer()
  315. Err() bool
  316. Error() error
  317. GetAlpha() (alpha float64, blendModeStr string)
  318. GetAutoPageBreak() (auto bool, margin float64)
  319. GetCellMargin() float64
  320. GetConversionRatio() float64
  321. GetDrawColor() (int, int, int)
  322. GetDrawSpotColor() (name string, c, m, y, k byte)
  323. GetFillColor() (int, int, int)
  324. GetFillSpotColor() (name string, c, m, y, k byte)
  325. GetFontDesc(familyStr, styleStr string) FontDescType
  326. GetFontSize() (ptSize, unitSize float64)
  327. GetImageInfo(imageStr string) (info *ImageInfoType)
  328. GetLineWidth() float64
  329. GetMargins() (left, top, right, bottom float64)
  330. GetPageSizeStr(sizeStr string) (size SizeType)
  331. GetPageSize() (width, height float64)
  332. GetStringWidth(s string) float64
  333. GetTextColor() (int, int, int)
  334. GetTextSpotColor() (name string, c, m, y, k byte)
  335. GetX() float64
  336. GetXY() (float64, float64)
  337. GetY() float64
  338. HTMLBasicNew() (html HTMLBasicType)
  339. Image(imageNameStr string, x, y, w, h float64, flow bool, tp string, link int, linkStr string)
  340. ImageOptions(imageNameStr string, x, y, w, h float64, flow bool, options ImageOptions, link int, linkStr string)
  341. ImageTypeFromMime(mimeStr string) (tp string)
  342. LinearGradient(x, y, w, h float64, r1, g1, b1, r2, g2, b2 int, x1, y1, x2, y2 float64)
  343. LineTo(x, y float64)
  344. Line(x1, y1, x2, y2 float64)
  345. LinkString(x, y, w, h float64, linkStr string)
  346. Link(x, y, w, h float64, link int)
  347. Ln(h float64)
  348. MoveTo(x, y float64)
  349. MultiCell(w, h float64, txtStr, borderStr, alignStr string, fill bool)
  350. Ok() bool
  351. OpenLayerPane()
  352. OutputAndClose(w io.WriteCloser) error
  353. OutputFileAndClose(fileStr string) error
  354. Output(w io.Writer) error
  355. PageCount() int
  356. PageNo() int
  357. PageSize(pageNum int) (wd, ht float64, unitStr string)
  358. PointConvert(pt float64) (u float64)
  359. PointToUnitConvert(pt float64) (u float64)
  360. Polygon(points []PointType, styleStr string)
  361. RadialGradient(x, y, w, h float64, r1, g1, b1, r2, g2, b2 int, x1, y1, x2, y2, r float64)
  362. RawWriteBuf(r io.Reader)
  363. RawWriteStr(str string)
  364. Rect(x, y, w, h float64, styleStr string)
  365. RegisterAlias(alias, replacement string)
  366. RegisterImage(fileStr, tp string) (info *ImageInfoType)
  367. RegisterImageOptions(fileStr string, options ImageOptions) (info *ImageInfoType)
  368. RegisterImageOptionsReader(imgName string, options ImageOptions, r io.Reader) (info *ImageInfoType)
  369. RegisterImageReader(imgName, tp string, r io.Reader) (info *ImageInfoType)
  370. SetAcceptPageBreakFunc(fnc func() bool)
  371. SetAlpha(alpha float64, blendModeStr string)
  372. SetAuthor(authorStr string, isUTF8 bool)
  373. SetAutoPageBreak(auto bool, margin float64)
  374. SetCatalogSort(flag bool)
  375. SetCellMargin(margin float64)
  376. SetCompression(compress bool)
  377. SetCreationDate(tm time.Time)
  378. SetCreator(creatorStr string, isUTF8 bool)
  379. SetDashPattern(dashArray []float64, dashPhase float64)
  380. SetDisplayMode(zoomStr, layoutStr string)
  381. SetDrawColor(r, g, b int)
  382. SetDrawSpotColor(nameStr string, tint byte)
  383. SetError(err error)
  384. SetErrorf(fmtStr string, args ...interface{})
  385. SetFillColor(r, g, b int)
  386. SetFillSpotColor(nameStr string, tint byte)
  387. SetFont(familyStr, styleStr string, size float64)
  388. SetFontLoader(loader FontLoader)
  389. SetFontLocation(fontDirStr string)
  390. SetFontSize(size float64)
  391. SetFontStyle(styleStr string)
  392. SetFontUnitSize(size float64)
  393. SetFooterFunc(fnc func())
  394. SetFooterFuncLpi(fnc func(lastPage bool))
  395. SetHeaderFunc(fnc func())
  396. SetHeaderFuncMode(fnc func(), homeMode bool)
  397. SetHomeXY()
  398. SetJavascript(script string)
  399. SetKeywords(keywordsStr string, isUTF8 bool)
  400. SetLeftMargin(margin float64)
  401. SetLineCapStyle(styleStr string)
  402. SetLineJoinStyle(styleStr string)
  403. SetLineWidth(width float64)
  404. SetLink(link int, y float64, page int)
  405. SetMargins(left, top, right float64)
  406. SetPageBoxRec(t string, pb PageBox)
  407. SetPageBox(t string, x, y, wd, ht float64)
  408. SetPage(pageNum int)
  409. SetProtection(actionFlag byte, userPassStr, ownerPassStr string)
  410. SetRightMargin(margin float64)
  411. SetSubject(subjectStr string, isUTF8 bool)
  412. SetTextColor(r, g, b int)
  413. SetTextSpotColor(nameStr string, tint byte)
  414. SetTitle(titleStr string, isUTF8 bool)
  415. SetTopMargin(margin float64)
  416. SetUnderlineThickness(thickness float64)
  417. SetXmpMetadata(xmpStream []byte)
  418. SetX(x float64)
  419. SetXY(x, y float64)
  420. SetY(y float64)
  421. SplitLines(txt []byte, w float64) [][]byte
  422. String() string
  423. SVGBasicWrite(sb *SVGBasicType, scale float64)
  424. Text(x, y float64, txtStr string)
  425. TransformBegin()
  426. TransformEnd()
  427. TransformMirrorHorizontal(x float64)
  428. TransformMirrorLine(angle, x, y float64)
  429. TransformMirrorPoint(x, y float64)
  430. TransformMirrorVertical(y float64)
  431. TransformRotate(angle, x, y float64)
  432. TransformScale(scaleWd, scaleHt, x, y float64)
  433. TransformScaleX(scaleWd, x, y float64)
  434. TransformScaleXY(s, x, y float64)
  435. TransformScaleY(scaleHt, x, y float64)
  436. TransformSkew(angleX, angleY, x, y float64)
  437. TransformSkewX(angleX, x, y float64)
  438. TransformSkewY(angleY, x, y float64)
  439. Transform(tm TransformMatrix)
  440. TransformTranslate(tx, ty float64)
  441. TransformTranslateX(tx float64)
  442. TransformTranslateY(ty float64)
  443. UnicodeTranslatorFromDescriptor(cpStr string) (rep func(string) string)
  444. UnitToPointConvert(u float64) (pt float64)
  445. UseTemplateScaled(t Template, corner PointType, size SizeType)
  446. UseTemplate(t Template)
  447. WriteAligned(width, lineHeight float64, textStr, alignStr string)
  448. Writef(h float64, fmtStr string, args ...interface{})
  449. Write(h float64, txtStr string)
  450. WriteLinkID(h float64, displayStr string, linkID int)
  451. WriteLinkString(h float64, displayStr, targetStr string)
  452. }
  453. // PageBox defines the coordinates and extent of the various page box types
  454. type PageBox struct {
  455. SizeType
  456. PointType
  457. }
  458. // Fpdf is the principal structure for creating a single PDF document
  459. type Fpdf struct {
  460. isCurrentUTF8 bool // is current font used in utf-8 mode
  461. isRTL bool // is is right to left mode enabled
  462. page int // current page number
  463. n int // current object number
  464. offsets []int // array of object offsets
  465. templates map[string]Template // templates used in this document
  466. templateObjects map[string]int // template object IDs within this document
  467. importedObjs map[string][]byte // imported template objects (gofpdi)
  468. importedObjPos map[string]map[int]string // imported template objects hashes and their positions (gofpdi)
  469. importedTplObjs map[string]string // imported template names and IDs (hashed) (gofpdi)
  470. importedTplIDs map[string]int // imported template ids hash to object id int (gofpdi)
  471. buffer fmtBuffer // buffer holding in-memory PDF
  472. pages []*bytes.Buffer // slice[page] of page content; 1-based
  473. state int // current document state
  474. compress bool // compression flag
  475. k float64 // scale factor (number of points in user unit)
  476. defOrientation string // default orientation
  477. curOrientation string // current orientation
  478. stdPageSizes map[string]SizeType // standard page sizes
  479. defPageSize SizeType // default page size
  480. defPageBoxes map[string]PageBox // default page size
  481. curPageSize SizeType // current page size
  482. pageSizes map[int]SizeType // used for pages with non default sizes or orientations
  483. pageBoxes map[int]map[string]PageBox // used to define the crop, trim, bleed and art boxes
  484. unitStr string // unit of measure for all rendered objects except fonts
  485. wPt, hPt float64 // dimensions of current page in points
  486. w, h float64 // dimensions of current page in user unit
  487. lMargin float64 // left margin
  488. tMargin float64 // top margin
  489. rMargin float64 // right margin
  490. bMargin float64 // page break margin
  491. cMargin float64 // cell margin
  492. x, y float64 // current position in user unit
  493. lasth float64 // height of last printed cell
  494. lineWidth float64 // line width in user unit
  495. fontpath string // path containing fonts
  496. fontLoader FontLoader // used to load font files from arbitrary locations
  497. coreFonts map[string]bool // array of core font names
  498. fonts map[string]fontDefType // array of used fonts
  499. fontFiles map[string]fontFileType // array of font files
  500. diffs []string // array of encoding differences
  501. fontFamily string // current font family
  502. fontStyle string // current font style
  503. underline bool // underlining flag
  504. strikeout bool // strike out flag
  505. currentFont fontDefType // current font info
  506. fontSizePt float64 // current font size in points
  507. fontSize float64 // current font size in user unit
  508. ws float64 // word spacing
  509. images map[string]*ImageInfoType // array of used images
  510. aliasMap map[string]string // map of alias->replacement
  511. pageLinks [][]linkType // pageLinks[page][link], both 1-based
  512. links []intLinkType // array of internal links
  513. attachments []Attachment // slice of content to embed globally
  514. pageAttachments [][]annotationAttach // 1-based array of annotation for file attachments (per page)
  515. outlines []outlineType // array of outlines
  516. outlineRoot int // root of outlines
  517. autoPageBreak bool // automatic page breaking
  518. acceptPageBreak func() bool // returns true to accept page break
  519. pageBreakTrigger float64 // threshold used to trigger page breaks
  520. inHeader bool // flag set when processing header
  521. headerFnc func() // function provided by app and called to write header
  522. headerHomeMode bool // set position to home after headerFnc is called
  523. inFooter bool // flag set when processing footer
  524. footerFnc func() // function provided by app and called to write footer
  525. footerFncLpi func(bool) // function provided by app and called to write footer with last page flag
  526. zoomMode string // zoom display mode
  527. layoutMode string // layout display mode
  528. xmp []byte // XMP metadata
  529. producer string // producer
  530. title string // title
  531. subject string // subject
  532. author string // author
  533. keywords string // keywords
  534. creator string // creator
  535. creationDate time.Time // override for document CreationDate value
  536. modDate time.Time // override for document ModDate value
  537. aliasNbPagesStr string // alias for total number of pages
  538. pdfVersion string // PDF version number
  539. fontDirStr string // location of font definition files
  540. capStyle int // line cap style: butt 0, round 1, square 2
  541. joinStyle int // line segment join style: miter 0, round 1, bevel 2
  542. dashArray []float64 // dash array
  543. dashPhase float64 // dash phase
  544. blendList []blendModeType // slice[idx] of alpha transparency modes, 1-based
  545. blendMap map[string]int // map into blendList
  546. blendMode string // current blend mode
  547. alpha float64 // current transpacency
  548. gradientList []gradientType // slice[idx] of gradient records
  549. clipNest int // Number of active clipping contexts
  550. transformNest int // Number of active transformation contexts
  551. err error // Set if error occurs during life cycle of instance
  552. protect protectType // document protection structure
  553. layer layerRecType // manages optional layers in document
  554. catalogSort bool // sort resource catalogs in document
  555. nJs int // JavaScript object number
  556. javascript *string // JavaScript code to include in the PDF
  557. colorFlag bool // indicates whether fill and text colors are different
  558. color struct {
  559. // Composite values of colors
  560. draw, fill, text colorType
  561. }
  562. spotColorMap map[string]spotColorType // Map of named ink-based colors
  563. userUnderlineThickness float64 // A custom user underline thickness multiplier.
  564. }
  565. type encType struct {
  566. uv int
  567. name string
  568. }
  569. type encListType [256]encType
  570. type fontBoxType struct {
  571. Xmin, Ymin, Xmax, Ymax int
  572. }
  573. // Font flags for FontDescType.Flags as defined in the pdf specification.
  574. const (
  575. // FontFlagFixedPitch is set if all glyphs have the same width (as
  576. // opposed to proportional or variable-pitch fonts, which have
  577. // different widths).
  578. FontFlagFixedPitch = 1 << 0
  579. // FontFlagSerif is set if glyphs have serifs, which are short
  580. // strokes drawn at an angle on the top and bottom of glyph stems.
  581. // (Sans serif fonts do not have serifs.)
  582. FontFlagSerif = 1 << 1
  583. // FontFlagSymbolic is set if font contains glyphs outside the
  584. // Adobe standard Latin character set. This flag and the
  585. // Nonsymbolic flag shall not both be set or both be clear.
  586. FontFlagSymbolic = 1 << 2
  587. // FontFlagScript is set if glyphs resemble cursive handwriting.
  588. FontFlagScript = 1 << 3
  589. // FontFlagNonsymbolic is set if font uses the Adobe standard
  590. // Latin character set or a subset of it.
  591. FontFlagNonsymbolic = 1 << 5
  592. // FontFlagItalic is set if glyphs have dominant vertical strokes
  593. // that are slanted.
  594. FontFlagItalic = 1 << 6
  595. // FontFlagAllCap is set if font contains no lowercase letters;
  596. // typically used for display purposes, such as for titles or
  597. // headlines.
  598. FontFlagAllCap = 1 << 16
  599. // SmallCap is set if font contains both uppercase and lowercase
  600. // letters. The uppercase letters are similar to those in the
  601. // regular version of the same typeface family. The glyphs for the
  602. // lowercase letters have the same shapes as the corresponding
  603. // uppercase letters, but they are sized and their proportions
  604. // adjusted so that they have the same size and stroke weight as
  605. // lowercase glyphs in the same typeface family.
  606. SmallCap = 1 << 18
  607. // ForceBold determines whether bold glyphs shall be painted with
  608. // extra pixels even at very small text sizes by a conforming
  609. // reader. If the ForceBold flag is set, features of bold glyphs
  610. // may be thickened at small text sizes.
  611. ForceBold = 1 << 18
  612. )
  613. // FontDescType (font descriptor) specifies metrics and other
  614. // attributes of a font, as distinct from the metrics of individual
  615. // glyphs (as defined in the pdf specification).
  616. type FontDescType struct {
  617. // The maximum height above the baseline reached by glyphs in this
  618. // font (for example for "S"). The height of glyphs for accented
  619. // characters shall be excluded.
  620. Ascent int
  621. // The maximum depth below the baseline reached by glyphs in this
  622. // font. The value shall be a negative number.
  623. Descent int
  624. // The vertical coordinate of the top of flat capital letters,
  625. // measured from the baseline (for example "H").
  626. CapHeight int
  627. // A collection of flags defining various characteristics of the
  628. // font. (See the FontFlag* constants.)
  629. Flags int
  630. // A rectangle, expressed in the glyph coordinate system, that
  631. // shall specify the font bounding box. This should be the smallest
  632. // rectangle enclosing the shape that would result if all of the
  633. // glyphs of the font were placed with their origins coincident
  634. // and then filled.
  635. FontBBox fontBoxType
  636. // The angle, expressed in degrees counterclockwise from the
  637. // vertical, of the dominant vertical strokes of the font. (The
  638. // 9-o’clock position is 90 degrees, and the 3-o’clock position
  639. // is –90 degrees.) The value shall be negative for fonts that
  640. // slope to the right, as almost all italic fonts do.
  641. ItalicAngle int
  642. // The thickness, measured horizontally, of the dominant vertical
  643. // stems of glyphs in the font.
  644. StemV int
  645. // The width to use for character codes whose widths are not
  646. // specified in a font dictionary’s Widths array. This shall have
  647. // a predictable effect only if all such codes map to glyphs whose
  648. // actual widths are the same as the value of the MissingWidth
  649. // entry. (Default value: 0.)
  650. MissingWidth int
  651. }
  652. type fontDefType struct {
  653. Tp string // "Core", "TrueType", ...
  654. Name string // "Courier-Bold", ...
  655. Desc FontDescType // Font descriptor
  656. Up int // Underline position
  657. Ut int // Underline thickness
  658. Cw []int // Character width by ordinal
  659. Enc string // "cp1252", ...
  660. Diff string // Differences from reference encoding
  661. File string // "Redressed.z"
  662. Size1, Size2 int // Type1 values
  663. OriginalSize int // Size of uncompressed font file
  664. N int // Set by font loader
  665. DiffN int // Position of diff in app array, set by font loader
  666. i string // 1-based position in font list, set by font loader, not this program
  667. utf8File *utf8FontFile // UTF-8 font
  668. usedRunes map[int]int // Array of used runes
  669. }
  670. // generateFontID generates a font Id from the font definition
  671. func generateFontID(fdt fontDefType) (string, error) {
  672. // file can be different if generated in different instance
  673. fdt.File = ""
  674. b, err := json.Marshal(&fdt)
  675. return fmt.Sprintf("%x", sha1.Sum(b)), err
  676. }
  677. type fontInfoType struct {
  678. Data []byte
  679. File string
  680. OriginalSize int
  681. FontName string
  682. Bold bool
  683. IsFixedPitch bool
  684. UnderlineThickness int
  685. UnderlinePosition int
  686. Widths []int
  687. Size1, Size2 uint32
  688. Desc FontDescType
  689. }