Formulario en línea interactivo en PDF

Resuelto
xav -  
 chteu -
Hola,

Estoy buscando crear, al igual que existe en algunos sitios, un formulario en PDF en línea con campos interactivos. En los campos, los usuarios realizan su escritura directamente en la página que está en formato PDF. ¿Podrías aclararme cómo funciona esto?

Gracias de antemano.

18 respuestas

  1. gg
     
    hola,

    Es posible crear un formulario en pdf . con campos que se pueden completar.

    Generalmente la opción propuesta en este caso es luego guardar o imprimir el formulario .

    Por otro lado, los archivos pdf pueden incorporar JavaScript y por lo tanto hacer que un formulario en pdf tenga un botón enviar. El código JavaScript se encargará de recolectar el nombre y el contenido de los campos del formulario y crear un enlace hacia una página web predefinida a la que se añaden los datos del formulario:
    tipo: http://monsite.com/getformpdf.php?champs1=nom&champs2=prenom
    de la otra lado hace falta un script para recuperar y procesar esos datos pasados en la URL .

    Para crear este formulario pdf hace falta un programa (generalmente de pago) capaz de hacerlo y saber usarlo.

    Para quienes php no asuste, hay soluciones gratuitas de scripts que permiten generar pdfs en línea, hay que integrarles el javascript

    aquí un ejemplo de prueba personal en una página de ejemplo de 'TCPDF' que toma un formulario, al cual se añade el javascript (fin del código casi), la página que recibe el formulario es test.php en el mismo directorio (ver código del script de prueba reducido al mínimo más abajo .

    [código]
    <?php
    //============================================================+
    // Nombre de archivo : example_014.php
    // Inicio : 2008-03-04
    // Última actualización : 2008-05-28
    //
    // Descripción : Example 014 para la clase TCPDF
    // Javascript Form y derechos de usuario
    //
    // Autor: Nicola Asuni
    //
    // (c) Copyright:
    // Nicola Asuni
    // Tecnick.com s.r.l.
    // Via Della Pace, 11
    // 09044 Quartucciu (CA)
    // ITALY
    // www.tecnick.com
    // info@tecnick.com
    //============================================================+

    /**
    * Crea un documento PDF de prueba usando TCPDF
    * @package com.tecnick.tcpdf
    * @abstract TCPDF - Ejemplo: Javascript Form y derechos de usuario
    * @author Nicola Asuni
    * @copyright 2004-2008 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
    * @link https://tcpdf.org/
    * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
    * @since 2008-03-04
    */

    require_once('../config/lang/eng.php');
    require_once('../tcpdf.php');

    // crear nuevo documento PDF
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);

    // establecer información del documento
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor("Nicola Asuni");
    $pdf->SetTitle("TCPDF Example 014");
    $pdf->SetSubject("TCPDF Tutorial");
    $pdf->SetKeywords("TCPDF, PDF, example, test, guide");

    // establecer datos predeterminados de cabecera
    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);

    // establecer fuentes de cabecera y pie
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

    //establecer márgenes
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    //establecer saltos de página automáticos
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    //establecer factor de escala de imágenes
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    //definir cadenas dependientes del idioma
    $pdf->setLanguageArray($l);

    //inicializar documento
    $pdf->AliasNbPages();

    // añadir una página
    $pdf->AddPage();

    // ---------------------------------------------------------

    // establecer fuente
    $pdf->SetFont("dejavusans", "BI", 20);

    // Liberar Derechos del Usuario para el lector de PDF.
    // Esto es necesario para mostrar y rellenar campos de formulario en lectores de PDF.
    $pdf->setUserRights();

    /*
    Caution: the generated PDF works only with Acrobat Reader 5.1.
    It is possible to create text fields, combo boxes, check boxes and buttons. Fields are created at the current position and are given a name. This name allows to manipulate them via JavaScript in order to perform some validation for instance.
    Upon field creation, an associative array can be passed to set a number of properties, among which:
    rect: Position and size of field on page.
    borderStyle: Rectangle border appearance.
    strokeColor: Color of bounding rectangle.
    lineWidth: Width of the edge of the surrounding rectangle.
    rotation: Rotation of field in 90-degree increments.
    fillColor: Background color of field (gray, transparent, RGB, or CMYK).
    userName: Short description of field that appears on mouse-over.
    readonly: Whether the user may change the field contents.
    doNotScroll: Whether text fields may scroll.
    display: Whether visible or hidden on screen or in print.
    textFont: Text font.
    textColor: Text color.
    textSize: Text size.
    richText: Rich text.
    richValue: Text.
    comb: Text comb format.
    multiline: Text multiline.
    charLimit: Text limit to number of characters.
    fileSelect: Text file selection format.
    password: Text password format.
    alignment: Text layout in text fields.
    buttonAlignX: X alignment of icon on button face.
    buttonAlignY: Y alignment of icon on button face.
    buttonFitBounds: Relative scaling of an icon to fit inside a button face.
    buttonScaleHow: Relative scaling of an icon to fit inside a button face.
    buttonScaleWhen: Relative scaling of an icon to fit inside a button face.
    highlight: Appearance of a button when pushed.
    style: Glyph style for checkbox and radio buttons.
    numItems: Number of items in a combo box or list box.
    editable: Whether the user can type in a combo box.
    multipleSelection: Whether multiple list box items may be selected.
    Colors can be chosen in the following list (case sensitive): black white red green blue cyan magenta yellow dkGray gray ltGray or be in the form #RRGGBB.
    */

    $pdf->Cell(0,5,'Subscription form',0,1,'C');
    $pdf->Ln(10);
    $pdf->SetFont('','',12);

    //Primer nombre
    $pdf->Cell(35,5,'First name:');
    $pdf->TextField('firstname',50,5,array('strokeColor'=>'ltGray'));
    $pdf->Ln(6);

    //Apellido
    $pdf->Cell(35,5,'Last name:');
    $pdf->TextField('lastname',50,5,array('strokeColor'=>'ltGray'));
    $pdf->Ln(6);

    //Género
    $pdf->Cell(35,5,'Gender:');
    $pdf->ComboBox('gender',10,5,array('','M','F'),array('strokeColor'=>'ltGray'));
    $pdf->Ln(6);

    //Bebida
    $pdf->Cell(35,5,'Drink:');
    $pdf->RadioButton('drink',5,false);
    $pdf->Cell(35,5,'Water');
    $pdf->Ln(6);
    $pdf->Cell(35,5,'');
    $pdf->RadioButton('drink',5,false);
    $pdf->Cell(35,5,'Beer');
    $pdf->Ln(6);
    $pdf->Cell(35,5,'');
    $pdf->RadioButton('drink',5,false);
    $pdf->Cell(35,5,'Wine');
    // establecer valores de exportación
    $pdf->IncludeJS("fdrink.exportValues=[\"Water\", \"Beer\", \"Wine\"];\n");
    // comprobar el segundo botón de opción
    $pdf->IncludeJS("fdrink.checkThisBox(1,true);\n");
    $pdf->Ln(10);

    //Género
    $pdf->Cell(35,5,'List:');
    $pdf->ListBox('listbox',60,15,array('','item1','item2','item3','item4','item5','item6','item7'), array('multipleSelection'=>'true'));
    $pdf->Ln(20);

    //Dirección
    $pdf->Cell(35,5,'Address:');
    $pdf->TextField('address',60,18,array('multiline'=>true,'strokeColor'=>'ltGray'));
    $pdf->Ln(19);

    //E-mail
    $pdf->Cell(35,5,'E-mail:');
    $pdf->TextField('email',50,5,array('strokeColor'=>'ltGray'));
    $pdf->Ln(6);

    //Boletín de noticias
    $pdf->Cell(35,5,'Receive our',0,1);
    $pdf->Cell(35,5,'newsletter:');
    $pdf->CheckBox('newsletter',5,true);
    $pdf->Ln(10);

    //Fecha del día (determinada y formateada por JS)
    $pdf->Write(5,'Date: ');
    $pdf->TextField('date',30,5);
    $pdf->IncludeJS("getField('date').value=util.printd('dd/mm/yyyy',new Date());\n");
    $pdf->Ln();
    $pdf->Write(5,'Signature:');
    $pdf->Ln(3);

    //Botón para validar e imprimir
    $pdf->SetX(95);
    $pdf->Button('Envoyez',25,15,'Envoyez','EnvFormfdf()',array('textColor'=>'yellow','fillColor'=>'#FF5050'));

    //Funciones de validación del formulario
    $pdf->IncludeJS("
    function CheckField(name,message) {
    var f = getField(name);
    if(f.value == '') {
    app.alert(message);
    f.setFocus();
    return false;
    }

    return true;

    }

    function envoifield(d) {
    var f = getField(d);
    if(f.value == '') {

    return false;
    }
    return f.value;
    }

    function EnvFormfdf() {
    this.submitForm.method='POST';
    this.submitForm({cURL:'test.php?firstname='+envoifield('firstname')+'' , cSubmitAs:'fdf',bAnnotations:true});

    //this.submitForm('test.php',TRUE, 'name');
    //app.alert(firstname);

    }

    //this.EnvFormfdf()

    function Print() {
    //Validación
    if(!CheckField('firstname','First name is mandatory'))
    return;
    if(!CheckField('lastname','Last name is mandatory'))
    return;
    if(!CheckField('gender','Gender is mandatory'))
    return;
    if(!CheckField('address','Address is mandatory'))
    return;
    //Imprimir
    EnvFormfdf();
    //print();
    }
    ");

    // ---------------------------------------------------------

    //Cerrar y salida del documento PDF
    $pdf->Output("example_014.pdf", "I");

    //============================================================+
    // FIN DEL ARCHIVO
    //============================================================+
    ?>
    /codigo
    la página llamada al enviar el formulario pdf que sirve solo para verificar que los datos se envían correctamente mediante el método 'get' (a través de la URL). :
    [código]
    <?php
    echo 'test sur firstname : <br>';
    echo $_GET['firstname'] ;
    ?>
    /codigo
    25
    1. nene
       
      ¡uf...
      0
    2. 23423543
       
      no gratuito = no está bien
      0