from pdfrw import PdfReader, PdfWriter, PageMerge
from fpdf import FPDF

import io
PATH = 'cerfa_13407-02.pdf'



def get_page_fields(page):
    for field in page.Annots:
        name = field.T
        rect = field.Rect
        yield name, rect

overlay = FPDF()
inpdf = PdfReader(PATH)

def ppi_to_mm(x):
    return x / 72.0 * 25.4

def Rect_to_rect(*args):
    llx, lly, urx, ury = map(ppi_to_mm, map(float, args))
    return (llx, ury, urx - llx, ury - lly)

overlay.set_font('Arial', size=5)
for page in inpdf.pages:
    overlay.add_page()
    width, height = map(ppi_to_mm, map(float, page.MediaBox[2:]))
    print(width, height)
    for name, rect in get_page_fields(page):
        x, y, w, h = Rect_to_rect(*rect)
        y = height - y
        overlay.set_draw_color(200, 0, 0)
        overlay.set_line_width(0.5)
        overlay.rect(x, y, w, h)
        new_x, new_y = x, min(height - 30, max(0, float(y) - 3.5))
        overlay.set_xy(new_x, new_y)
        overlay.set_fill_color(240, 240, 240)
        t_w = overlay.get_string_width(name)
        overlay.cell(t_w + 1.5, 2.5, border=1, txt=name, fill=True)
        print(name, new_x, new_y, t_w)

overlay_content = overlay.output(dest='S')

overlaypdf = PdfReader(io.StringIO(overlay_content))

for page, overlay_page in zip(inpdf.pages, overlaypdf.pages):
    PageMerge(page).add(overlay_page, prepend=False).render()

PdfWriter('out.pdf', trailer=inpdf).write()

