pythonpdfreportlab

Draw grid lines behind text reportlab pdf


I want to create a grid like this. On top of this grid would be behind some texts or images. I have already created the text and images on the pdf, but I do not know how to create this grid behind them.

Any point in the right direction would be very helpful. A small complete solution would be more helpful. enter image description here


Solution

  • enter image description here

    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import A4
    from reportlab.lib.units import mm
    
    
    def grid_setup(mc):
        mc.setLineWidth(0.25)
        mc.setStrokeColor("red")
        mc.setStrokeAlpha(0.4)
    
        offset = 3 * mm
        grids = 13
    
        y_start = 260 * mm
        y_delta = 21 * mm
        y_left = 1 * mm
        y_right = 209 * mm
    
        x_start = 1 * mm
        x_delta = 20.5 * mm
        x_top = y_start
        x_bottom = y_start - (grids - 1) * y_delta - offset
    
        mc.line(y_left, 285 * mm, y_right, 285 * mm)
        mc.line(y_left, 275 * mm, y_right, 275 * mm)
    
        for x in range(grids):
            mc.line(y_left, y_start, y_right, y_start)
            mc.line(y_left, y_start - offset, y_right, y_start - offset)
            y_start -= y_delta
    
            mc.line(x_start, x_top, x_start, x_bottom)
            mc.line(x_start + offset, x_top, x_start + offset, x_bottom)
            x_start += x_delta
    
    
    if __name__ == "__main__":
        my_canvas = canvas.Canvas("page.pdf", pagesize=A4)
        grid_setup(my_canvas)
        my_canvas.drawString(10 * mm, 278 * mm, "Stackoverflow")
        my_canvas.save()