Advertisement
ALEXANDAR_GEORGIEV

row_height

Jul 6th, 2022
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. from reportlab.lib.randomtext import chomsky
  2. from reportlab.platypus.tables import Table, GRID_STYLE
  3. from reportlab.platypus import SimpleDocTemplate, LayoutError
  4. from reportlab.lib import pagesizes
  5. import random
  6.  
  7. def split_heights(vs, availableHeight):
  8.     res = []
  9.     for v in vs:
  10.         if sum(res) + v < availableHeight:
  11.             res.append(v)
  12.         else:
  13.             yield res
  14.             res = [v]
  15.     yield res
  16.  
  17. def split_data(data, rowHeights):
  18.     i = 0
  19.     for item in rowHeights:
  20.         chunk = []
  21.         for _ in item:
  22.             chunk.append(data[i])
  23.             i += 1
  24.         yield chunk
  25.  
  26. def phase1(data, dest):
  27.     template = SimpleDocTemplate(dest, pagesize=pagesizes.A4)
  28.     inner_table = Table(data, style=GRID_STYLE)
  29.     outer_table = Table([['Sequences', inner_table]], style=GRID_STYLE)
  30.     flowables = [outer_table]
  31.     try:
  32.         template.build(flowables)
  33.     except LayoutError as e:
  34.         rowHeights = inner_table._rowHeights
  35.         frame = template.frame
  36.         availableHeight = frame._aH
  37.         return list(split_heights(rowHeights, availableHeight))
  38.  
  39. def phase2(data, dest, rowHeights):
  40.     tables = []
  41.     for chunk in split_data(data, rowHeights):
  42.         tables.append(Table(chunk, style=GRID_STYLE))
  43.     data_ = [['Sequences', table] for table in tables]
  44.     flowables = [Table(data_, style=GRID_STYLE)]
  45.     template = SimpleDocTemplate(dest, pagesize=pagesizes.A4)
  46.     template.build(flowables)
  47.  
  48. def main():
  49.     data = [[chomsky(random.randint(2,5))] for c in range(10)]
  50.     dest = "test1.pdf"
  51.     rowHeights = phase1(data, dest)
  52.     if rowHeights is None:
  53.         return
  54.     phase2(data, dest, rowHeights)
  55.  
  56. if __name__ == "__main__":
  57.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement