sheet.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package pdf
  2. /*
  3. sheet.go - Build a PDF from a Sheets workbook with REAL text.
  4. Formula evaluation and number formatting live in the web client, so
  5. the client posts a "print model": per sheet, the used-range grid of
  6. formatted display strings plus the visual styles that affect print
  7. (bold/italic/underline, font and fill colors, alignment) and the
  8. column widths in CSS pixels. The server lays that grid out on A4
  9. landscape pages, scaling the columns down when the sheet is wider
  10. than the printable area and splitting rows across pages. Every sheet
  11. is an entry of the PDF's outline (bookmarks), at its name heading.
  12. */
  13. import (
  14. "encoding/json"
  15. "errors"
  16. "strconv"
  17. "strings"
  18. "github.com/go-pdf/fpdf"
  19. )
  20. // SheetPrintCell is one formatted cell in the print model
  21. type SheetPrintCell struct {
  22. T string `json:"t"` // display text
  23. B bool `json:"b,omitempty"` // bold
  24. I bool `json:"i,omitempty"` // italic
  25. U bool `json:"u,omitempty"` // underline
  26. Fc string `json:"fc,omitempty"` // font color (#rrggbb)
  27. Bg string `json:"bg,omitempty"` // fill color (#rrggbb)
  28. Al string `json:"al,omitempty"` // l | c | r
  29. }
  30. // SheetPrintSheet is one sheet's used-range grid
  31. type SheetPrintSheet struct {
  32. Name string `json:"name"`
  33. ColW []float64 `json:"colW"` // column widths, css px
  34. RowH []float64 `json:"rowH,omitempty"` // row heights, css px
  35. Rows [][]*SheetPrintCell `json:"rows"`
  36. }
  37. // SheetPrintModel is the whole workbook print model
  38. type SheetPrintModel struct {
  39. Sheets []*SheetPrintSheet `json:"sheets"`
  40. }
  41. // ParseSheetPrintJSON decodes the print model posted by sheets.js
  42. func ParseSheetPrintJSON(jsonStr string) (*SheetPrintModel, error) {
  43. m := SheetPrintModel{}
  44. if err := json.Unmarshal([]byte(jsonStr), &m); err != nil {
  45. return nil, errors.New("invalid print model JSON: " + err.Error())
  46. }
  47. if len(m.Sheets) == 0 {
  48. return nil, errors.New("print model has no sheets")
  49. }
  50. return &m, nil
  51. }
  52. const (
  53. // cell font before any page down-scaling
  54. sheetBaseFontPt = 9.0
  55. // left + right inset inside a cell (half of it on each side)
  56. sheetCellPadMM = 1.6
  57. // extra room added when widening a column, so grown text does not end
  58. // up flush against the divider
  59. sheetColAirMM = 1.2
  60. // A column may grow this many times past the width the client asked
  61. // for, and take at most this share of the page, so one very long cell
  62. // cannot squeeze every other column into an unreadable sliver.
  63. sheetColGrowMax = 3.0
  64. sheetColPageFrac = 0.4
  65. )
  66. // sheetFitColumns widens columns so their contents actually fit.
  67. //
  68. // The client measures its columns in the browser's UI font; the same text is
  69. // drawn here in Helvetica at 9pt, so a value that sat comfortably in its
  70. // column on screen can come out a hair too wide - and fpdf does not clip, it
  71. // just paints over the next column. Rather than truncate data the user can
  72. // see on screen, grow the column to its widest cell (bounded by the constants
  73. // above). Growing is safe: BuildSheet scales widths and the font by the
  74. // same factor afterwards, so a column that fits its content here still fits
  75. // once the table is shrunk onto the page.
  76. func sheetFitColumns(pdf *fpdf.Fpdf, tr func(string) string, sheet *SheetPrintSheet,
  77. widths []float64, usableW float64) {
  78. for _, row := range sheet.Rows {
  79. for c := 0; c < len(widths) && c < len(row); c++ {
  80. cell := row[c]
  81. if cell == nil || cell.T == "" {
  82. continue
  83. }
  84. pdf.SetFont("Arial", pdfStyleStr(cell.B, cell.I, cell.U), sheetBaseFontPt)
  85. need := pdf.GetStringWidth(tr(cell.T)) + sheetCellPadMM + sheetColAirMM
  86. if need <= widths[c] {
  87. continue
  88. }
  89. limit := max(widths[c]*sheetColGrowMax, widths[c])
  90. if pageCap := usableW * sheetColPageFrac; limit > pageCap {
  91. limit = max(pageCap, widths[c])
  92. }
  93. widths[c] = min(need, limit)
  94. }
  95. }
  96. }
  97. // BuildSheet renders the print model into PDF bytes
  98. func BuildSheet(m *SheetPrintModel) ([]byte, error) {
  99. const marginMM = 12.0
  100. pdf := fpdf.New("L", "mm", "A4", "")
  101. pdf.SetMargins(marginMM, marginMM, marginMM)
  102. pdf.SetAutoPageBreak(false, marginMM)
  103. tr := pdfTr(pdf)
  104. pageW, pageH := pdf.GetPageSize()
  105. usableW := pageW - 2*marginMM
  106. for i, sheet := range m.Sheets {
  107. pdf.AddPage()
  108. // every sheet is an entry of the PDF outline, at its name heading
  109. name := strings.Join(strings.Fields(sheet.Name), " ")
  110. if name == "" {
  111. name = "Sheet " + strconv.Itoa(i+1)
  112. }
  113. pdf.Bookmark(pdfTextString(name), 0, marginMM)
  114. // sheet name heading
  115. pdf.SetFont("Arial", "B", 12)
  116. pdf.SetTextColor(31, 35, 40)
  117. pdf.SetXY(marginMM, marginMM)
  118. pdf.CellFormat(usableW, 6, tr(sheet.Name), "", 1, "L", false, 0, "")
  119. pdf.SetY(pdf.GetY() + 2)
  120. if len(sheet.Rows) == 0 {
  121. continue
  122. }
  123. cols := 0
  124. for _, row := range sheet.Rows {
  125. if len(row) > cols {
  126. cols = len(row)
  127. }
  128. }
  129. if cols == 0 {
  130. continue
  131. }
  132. // column widths: px -> mm, widened to fit their contents, then
  133. // scaled down together with the font when the table is too wide
  134. widths := make([]float64, cols)
  135. for i := 0; i < cols; i++ {
  136. w := 100.0 * pxToMM
  137. if i < len(sheet.ColW) && sheet.ColW[i] > 0 {
  138. w = sheet.ColW[i] * pxToMM
  139. }
  140. widths[i] = w
  141. }
  142. sheetFitColumns(pdf, tr, sheet, widths, usableW)
  143. total := 0.0
  144. for _, w := range widths {
  145. total += w
  146. }
  147. scale := 1.0
  148. if total > usableW {
  149. scale = usableW / total
  150. for i := range widths {
  151. widths[i] *= scale
  152. }
  153. }
  154. fontPt := sheetBaseFontPt * scale
  155. if fontPt < 5 {
  156. // the font stopped shrinking with the columns, so cells can
  157. // overflow again - pdfFitText below is what keeps them apart
  158. fontPt = 5
  159. }
  160. for r, row := range sheet.Rows {
  161. rowH := 24.0 * pxToMM * scale
  162. if r < len(sheet.RowH) && sheet.RowH[r] > 0 {
  163. rowH = sheet.RowH[r] * pxToMM * scale
  164. }
  165. minH := fontPt*0.3528 + 1.6
  166. if rowH < minH {
  167. rowH = minH
  168. }
  169. if pdf.GetY()+rowH > pageH-marginMM {
  170. pdf.AddPage()
  171. pdf.SetY(marginMM)
  172. }
  173. x := marginMM
  174. y := pdf.GetY()
  175. pdf.SetDrawColor(190, 194, 200)
  176. pdf.SetLineWidth(0.15)
  177. for c := 0; c < cols; c++ {
  178. var cell *SheetPrintCell
  179. if c < len(row) {
  180. cell = row[c]
  181. }
  182. fill := false
  183. if cell != nil && cell.Bg != "" {
  184. fill = pdfSetFillHex(pdf, cell.Bg)
  185. }
  186. pdf.Rect(x, y, widths[c], rowH, map[bool]string{true: "FD", false: "D"}[fill])
  187. if cell != nil && cell.T != "" {
  188. pdf.SetFont("Arial", pdfStyleStr(cell.B, cell.I, cell.U), fontPt)
  189. pdfSetTextHex(pdf, cell.Fc, 31, 35, 40)
  190. align := map[string]string{"c": "C", "r": "R"}[cell.Al]
  191. if align == "" {
  192. align = "L"
  193. }
  194. // last resort: a cell that still does not fit (the font
  195. // hit its 5pt floor) is trimmed rather than drawn over
  196. // the next column, since fpdf itself never clips
  197. innerW := widths[c] - sheetCellPadMM
  198. pdf.SetXY(x+sheetCellPadMM/2, y)
  199. pdf.CellFormat(innerW, rowH, pdfFitText(pdf, tr, cell.T, innerW), "", 0, align, false, 0, "")
  200. }
  201. x += widths[c]
  202. }
  203. pdf.SetY(y + rowH)
  204. }
  205. }
  206. if pdf.Err() {
  207. return nil, pdf.Error()
  208. }
  209. return pdfOutput(pdf)
  210. }