|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
from pypdf import PdfWriter from pypdf.generic import DictionaryObject, NameObject, DecodedStreamObject def crear_pdf_con_boton(output_filename: str, target_url: str): writer = PdfWriter() page = writer.add_blank_page(width=72 * 8.5, height=72 * 11) # Letter: 612x792 # --- Botón (posición/tamaño) --- x, y, w, h = 100, 700, 220, 32 label = "Visitar jesusninoc.com" font_size = 14 # --- Fuente estándar (Helvetica) --- font = DictionaryObject({ NameObject("/Type"): NameObject("/Font"), NameObject("/Subtype"): NameObject("/Type1"), NameObject("/BaseFont"): NameObject("/Helvetica"), }) font_ref = writer._add_object(font) page[NameObject("/Resources")] = DictionaryObject({ NameObject("/Font"): DictionaryObject({NameObject("/F1"): font_ref}) }) # --- Contenido visible: rectángulo + texto --- text_x = x + 8 text_y = y + (h - font_size) / 2 + 2 # Ojo: evita paréntesis en label o escápalos si los necesitas. content = f"""q 0 0 1 RG 1 w {x} {y} {w} {h} re S BT /F1 {font_size} Tf 1 0 0 1 {text_x} {text_y} Tm ({label}) Tj ET Q """ stream = DecodedStreamObject() stream.set_data(content.encode("latin-1")) page[NameObject("/Contents")] = writer._add_object(stream) # --- Zona clicable (link) encima del “botón” --- writer.add_uri( page_number=0, uri=target_url, rect=[x, y, x + w, y + h], border=[0, 0, 0], # sin borde (ya lo dibujamos nosotros) ) with open(output_filename, "wb") as f: writer.write(f) if __name__ == "__main__": crear_pdf_con_boton("documento_con_boton_web.pdf", "https://www.jesusninoc.com/") print("PDF generado: documento_con_boton_web.pdf") |

