Skip to content

Instantly share code, notes, and snippets.

@CnrLwlss
Created January 4, 2024 09:51
Show Gist options
  • Save CnrLwlss/d4963a2803e3bcd07f149dd1fef435e4 to your computer and use it in GitHub Desktop.
Save CnrLwlss/d4963a2803e3bcd07f149dd1fef435e4 to your computer and use it in GitHub Desktop.
Writes a single page pdf of width w mm and height h mm (defaults are A4) with a nrow x ncol grid traced out on it, to file outf. Grid is a thin line (thickness is lwd) coloured grey (default is very light grey) with dashing specified by dash length dl and space length sl.
from fpdf import FPDF
def makeGrid(w=210.0, h=297.0, nrow=5, ncol=4, outf="grid.pdf", grey = 220, dl=3, sl=2, lwd=0.2):
'''Writes a single page pdf of width w mm and height h mm (defaults are A4) with a nrow x ncol grid
traced out on it, to file outf. Grid is a thin line (thickness is lwd) coloured grey (default is very
light grey) with dashing specified by dash length dl and space length sl.'''
pdf = FPDF(orientation="P", unit="mm", format=(w,h))
deltax = float(w)/ncol
deltay = float(h)/nrow
pdf.add_page()
pdf.set_margins(0,0)
pdf.set_line_width(lwd)
pdf.set_draw_color(r=grey, g=grey, b=grey)
for row in range(1,nrow):
pdf.dashed_line(x1=0, y1=deltay*row, x2=w, y2=deltay*row, dash_length=dl, space_length=sl)
for col in range(1,ncol):
pdf.dashed_line(x1=deltax*col, y1=0, x2=deltax*col, y2=h, dash_length=dl, space_length=sl)
pdf.output(outf)
if __name__ == "__main__":
makeGrid(nrow=5, ncol=4, outf="grid020.pdf")
makeGrid(nrow=7, ncol=3, outf="grid021.pdf")
makeGrid(nrow=20, ncol=5, outf="grid100.pdf")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment