Skip to content

Instantly share code, notes, and snippets.

@marcosinger
Created March 26, 2020 14:24
Show Gist options
  • Save marcosinger/6e53bb60c3d81ecb571cb41fc313b527 to your computer and use it in GitHub Desktop.
Save marcosinger/6e53bb60c3d81ecb571cb41fc313b527 to your computer and use it in GitHub Desktop.
Helper to align tables based on its content using the gofpdf library
func wrappedTable(document *gofpdf.Fpdf, encodingFunc report.EncodingFunc,
rows [][]string, cols []float64, marginCell float64, border bool) []position {
var (
padding = 10.0
paddingCell = 2. // padding of top/bottom of cell
rowsPositions []position
)
_, pageh := document.GetPageSize()
mleft, _, _, mbottom := document.GetMargins()
for rowIndex, row := range rows {
height := 0.
_, lineHt := document.GetFontSize()
for i, txt := range row {
lines := document.SplitLines([]byte(txt), cols[i])
h := float64(len(lines))*lineHt + paddingCell*float64(len(lines))
if h > height {
height = h
}
}
// add a new page if the height of the row doesn't fit on the page
if document.GetY()+height > pageh-mbottom {
document.AddPage()
document.SetX(mleft)
}
curx, y := document.GetXY()
x := curx
for i, txt := range row {
width := cols[i]
if border {
document.Rect(x, y, width, height, "")
}
encodedTxt := encodingFunc(txt)
document.MultiCell(width, lineHt+paddingCell, encodedTxt, "", "L", false)
x += width
document.SetXY(x, y)
}
rowsPositions = append(rowsPositions, position{
row: rowIndex,
posX: docWidth - curx + padding, // position next to the last column
posY: y,
})
cury := y + height + marginCell
document.SetXY(curx, cury)
}
return rowsPositions
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment