package pdf /* sheet.go - Build a PDF from a Sheets workbook with REAL text. Formula evaluation and number formatting live in the web client, so the client posts a "print model": per sheet, the used-range grid of formatted display strings plus the visual styles that affect print (bold/italic/underline, font and fill colors, alignment) and the column widths in CSS pixels. The server lays that grid out on A4 landscape pages, scaling the columns down when the sheet is wider than the printable area and splitting rows across pages. Every sheet is an entry of the PDF's outline (bookmarks), at its name heading. */ import ( "encoding/json" "errors" "strconv" "strings" "github.com/go-pdf/fpdf" ) // SheetPrintCell is one formatted cell in the print model type SheetPrintCell struct { T string `json:"t"` // display text B bool `json:"b,omitempty"` // bold I bool `json:"i,omitempty"` // italic U bool `json:"u,omitempty"` // underline Fc string `json:"fc,omitempty"` // font color (#rrggbb) Bg string `json:"bg,omitempty"` // fill color (#rrggbb) Al string `json:"al,omitempty"` // l | c | r } // SheetPrintSheet is one sheet's used-range grid type SheetPrintSheet struct { Name string `json:"name"` ColW []float64 `json:"colW"` // column widths, css px RowH []float64 `json:"rowH,omitempty"` // row heights, css px Rows [][]*SheetPrintCell `json:"rows"` } // SheetPrintModel is the whole workbook print model type SheetPrintModel struct { Sheets []*SheetPrintSheet `json:"sheets"` } // ParseSheetPrintJSON decodes the print model posted by sheets.js func ParseSheetPrintJSON(jsonStr string) (*SheetPrintModel, error) { m := SheetPrintModel{} if err := json.Unmarshal([]byte(jsonStr), &m); err != nil { return nil, errors.New("invalid print model JSON: " + err.Error()) } if len(m.Sheets) == 0 { return nil, errors.New("print model has no sheets") } return &m, nil } const ( // cell font before any page down-scaling sheetBaseFontPt = 9.0 // left + right inset inside a cell (half of it on each side) sheetCellPadMM = 1.6 // extra room added when widening a column, so grown text does not end // up flush against the divider sheetColAirMM = 1.2 // A column may grow this many times past the width the client asked // for, and take at most this share of the page, so one very long cell // cannot squeeze every other column into an unreadable sliver. sheetColGrowMax = 3.0 sheetColPageFrac = 0.4 ) // sheetFitColumns widens columns so their contents actually fit. // // The client measures its columns in the browser's UI font; the same text is // drawn here in Helvetica at 9pt, so a value that sat comfortably in its // column on screen can come out a hair too wide - and fpdf does not clip, it // just paints over the next column. Rather than truncate data the user can // see on screen, grow the column to its widest cell (bounded by the constants // above). Growing is safe: BuildSheet scales widths and the font by the // same factor afterwards, so a column that fits its content here still fits // once the table is shrunk onto the page. func sheetFitColumns(pdf *fpdf.Fpdf, tr func(string) string, sheet *SheetPrintSheet, widths []float64, usableW float64) { for _, row := range sheet.Rows { for c := 0; c < len(widths) && c < len(row); c++ { cell := row[c] if cell == nil || cell.T == "" { continue } pdf.SetFont("Arial", pdfStyleStr(cell.B, cell.I, cell.U), sheetBaseFontPt) need := pdf.GetStringWidth(tr(cell.T)) + sheetCellPadMM + sheetColAirMM if need <= widths[c] { continue } limit := max(widths[c]*sheetColGrowMax, widths[c]) if pageCap := usableW * sheetColPageFrac; limit > pageCap { limit = max(pageCap, widths[c]) } widths[c] = min(need, limit) } } } // BuildSheet renders the print model into PDF bytes func BuildSheet(m *SheetPrintModel) ([]byte, error) { const marginMM = 12.0 pdf := fpdf.New("L", "mm", "A4", "") pdf.SetMargins(marginMM, marginMM, marginMM) pdf.SetAutoPageBreak(false, marginMM) tr := pdfTr(pdf) pageW, pageH := pdf.GetPageSize() usableW := pageW - 2*marginMM for i, sheet := range m.Sheets { pdf.AddPage() // every sheet is an entry of the PDF outline, at its name heading name := strings.Join(strings.Fields(sheet.Name), " ") if name == "" { name = "Sheet " + strconv.Itoa(i+1) } pdf.Bookmark(pdfTextString(name), 0, marginMM) // sheet name heading pdf.SetFont("Arial", "B", 12) pdf.SetTextColor(31, 35, 40) pdf.SetXY(marginMM, marginMM) pdf.CellFormat(usableW, 6, tr(sheet.Name), "", 1, "L", false, 0, "") pdf.SetY(pdf.GetY() + 2) if len(sheet.Rows) == 0 { continue } cols := 0 for _, row := range sheet.Rows { if len(row) > cols { cols = len(row) } } if cols == 0 { continue } // column widths: px -> mm, widened to fit their contents, then // scaled down together with the font when the table is too wide widths := make([]float64, cols) for i := 0; i < cols; i++ { w := 100.0 * pxToMM if i < len(sheet.ColW) && sheet.ColW[i] > 0 { w = sheet.ColW[i] * pxToMM } widths[i] = w } sheetFitColumns(pdf, tr, sheet, widths, usableW) total := 0.0 for _, w := range widths { total += w } scale := 1.0 if total > usableW { scale = usableW / total for i := range widths { widths[i] *= scale } } fontPt := sheetBaseFontPt * scale if fontPt < 5 { // the font stopped shrinking with the columns, so cells can // overflow again - pdfFitText below is what keeps them apart fontPt = 5 } for r, row := range sheet.Rows { rowH := 24.0 * pxToMM * scale if r < len(sheet.RowH) && sheet.RowH[r] > 0 { rowH = sheet.RowH[r] * pxToMM * scale } minH := fontPt*0.3528 + 1.6 if rowH < minH { rowH = minH } if pdf.GetY()+rowH > pageH-marginMM { pdf.AddPage() pdf.SetY(marginMM) } x := marginMM y := pdf.GetY() pdf.SetDrawColor(190, 194, 200) pdf.SetLineWidth(0.15) for c := 0; c < cols; c++ { var cell *SheetPrintCell if c < len(row) { cell = row[c] } fill := false if cell != nil && cell.Bg != "" { fill = pdfSetFillHex(pdf, cell.Bg) } pdf.Rect(x, y, widths[c], rowH, map[bool]string{true: "FD", false: "D"}[fill]) if cell != nil && cell.T != "" { pdf.SetFont("Arial", pdfStyleStr(cell.B, cell.I, cell.U), fontPt) pdfSetTextHex(pdf, cell.Fc, 31, 35, 40) align := map[string]string{"c": "C", "r": "R"}[cell.Al] if align == "" { align = "L" } // last resort: a cell that still does not fit (the font // hit its 5pt floor) is trimmed rather than drawn over // the next column, since fpdf itself never clips innerW := widths[c] - sheetCellPadMM pdf.SetXY(x+sheetCellPadMM/2, y) pdf.CellFormat(innerW, rowH, pdfFitText(pdf, tr, cell.T, innerW), "", 0, align, false, 0, "") } x += widths[c] } pdf.SetY(y + rowH) } } if pdf.Err() { return nil, pdf.Error() } return pdfOutput(pdf) }