How to use Javascript using FPDF

Asked

Viewed 582 times

-1

I have a classa fdpf in php to display information of the purchase made through registration of my database, but I cannot execute a javascript command to calculate and display the numbers of installments, value of each installment and expiration date, I have this function working on another page perfectly, but wanted to import it to the FPDF, anyone have an idea? I will put my class with this javascript function working and also my FPDF page:

Javascript running - cadastre_contratos.php

 function calculamensalidades(){

  var valortotal = parseFloat(document.getElementById("total").value);
  var valorparcela = valortotal/document.getElementById("select_parcelas").value;
  var parcelas = parseFloat(document.getElementById("select_parcelas").value);
  var date = new Date();
  var mesvencimento = date.getMonth();
  var diavencimento = date.getDate();

  var tabela;
  tabela = "<br><table border='0' width='30%' style='text-align:center'><tr><td bgcolor='#4682B4'>Parcela</td><td bgcolor='#4682B4' >Valor</td><td bgcolor='#4682B4'>Vencimento</td></tr>";


  for(var a=0; a<document.getElementById("select_parcelas").value; a++)
 {
  var n_date = new Date(date.getFullYear(), eval(a+mesvencimento), diavencimento);
  var diavec = date.getDate();
  var mesvenc = n_date.getMonth();
  var anovenc = n_date.getFullYear();

     tabela = tabela + "<tr><td bgcolor='#9AC0CD'>"+(a+1)+"</td><td bgcolor='#9AC0CD'>R$ "+valorparcela.toFixed(2)+"</td><td bgcolor='#9AC0CD'>"+diavec+"/"+mesvenc+"/"+anovenc+"</td></tr>";
 }
 tabela=tabela+"</table>";
document.getElementById("mensalidades").innerHTML="";
document.getElementById("mensalidades").innerHTML=tabela;
 }

function apagatabela(){
document.getElementById('mensalidades').innerHTML="";
}

 function liberar()
{
  var total = document.getElementById("total"); 
  var parcelas = document.getElementById("select_parcelas");

  if(total.value != "")
  {
    parcelas.disabled=false;
  }
}

HTML form - cadastro_contratos.php:

<form id="adicionarformProdutos" method"post" action"" enctype="multipart/form-data">
     <a href="#" id="adicionarProduto">Adicionar Produto</a>      
    <fieldset class="fieldsetProduto">
        <legend>Produto 1</legend>
        <div class="produtos">
            <label for="codProduto1">Código:</label><input class="codigoProduto" type="text" id="codProduto1" size="5" name="codProduto1" />
            <label for="nomeProduto1">Nome:</label> <input type="text" id="nomeProduto1" name="nomeProduto1" size="9"  />
            <label for="qtProduto1">Qt.:</label> <input type="text" size="1" id="qtProduto1" name="qtProduto1" onblur="calcValor()" />
            <label for="valorProduto1">Valor und. R$:</label> <input type="text" id="valorProduto1" name="valorProduto1" size="6" onkeypress="mascara(this,float)" />
        </div>
     </fieldset>
<br>
            <label>Data da Compra <input name="datacompra" type="text" id="datacompra" size="6" maxlength="10" value="<?php echo date('d/m/Y')?>" onKeyUp="javascript:somente_numero(this);" onkeypress="formatar_mascara(this,'##/##/####')"/></label>
            <label>Desconto (%)<span style="display:none" id="sp_vdesconto"></span><input type="hidden"  name="vdesconto" id="vdesconto" />:<input type="text" name="desconto" size="6" value="0"id="desconto" onblur="calcValor()" /></label>   
            <label>Entrada R$<span style="display:none" id="sp_vdentrada"></span><input type="hidden" size="6" name="vdentrada" id="vdentrada" />:<input type="text" name="entrada" size="6" value="0"id="entrada" onKeyPress="return(MascaraMoeda(this,'.',',',event))" onblur="calcValor()" /></label>
<div>
  <br>
  <div>
            <label>Valor Total: <input type="text" name="total" value="0" size="6" id="total" onblur="liberar(); "/></label>
            <label>Qt. Parcelas: </label><select onchange="calculamensalidades()" disabled="disabled" value="" id="select_parcelas" name="select_parcelas">
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
              <option>6</option>
            </select>
 <div id="mensalidades"></div>
</div>
<br>
    <input type="reset" onClick="apagatabela()">
    <input type="hidden" name="cadastra" value="add"  />
    <input type="hidden" value="<?php echo $nrFicha;?>" name="cadastro" />
    <input type="submit" name="add" id="add" value="Cadastrar" />  
</div><!--fechando div painelcadastro2-->
</form><!--fechando div adicionarformProdutos-->

Now the FPDF class I want to run and display a similar table, without using the HTML form, because the variables that I will use to generate the table are already in the database and being displayed in the FPDF below:

<?php 
define('FPDF_FONTPATH', 'font/');
require('fpdf/fpdf.php');
$pdf=new FPDF('P', 'cm', 'A4');
$pdf->Open();
$pdf->AddPage();
$pdf->SetFont('Arial', '', 10);

    include"../Connections/config.php";
    $conexao = mysql_connect("$hostname_config","$username_config","$password_config")
                or die ("Erro ao realizar a conexão com o banco de dados, por favor informe o administrador do sistema ([email protected]) ou envie um email para [email protected] !");
    $db = mysql_select_db("$database_config")
                or die ("Erro ao selecionar o banco de dados, por favor informe o administrador do sistema ([email protected]) ou envie um email para [email protected] !");
    $contrato = $_GET['id'];
    $seleciona = mysql_query("SELECT contr.*,client.Snome FROM t_cadcontratos contr INNER JOIN t_cadclientes client ON contr.Ficha = client.Ficha WHERE NumContrato = '$contrato'");
      if($seleciona == ''){
        echo "Erro ao Selecionar, tente novamente !";
      }else{  
        while($res_id = mysql_fetch_array($seleciona)){
        $pdf->Cell(3,0.5,"Ficha:",0,0,'R'); $pdf->Cell(2,0.5,$res_id['Ficha'],1,1,'L');
        $pdf->Cell(3,0.5,"N Contrato:",0,0,'R'); $pdf->Cell(2,0.5,$res_id['NumContrato'],1,1,'L');
        $pdf->Cell(3,0.5,"Nome Cliente:",0,0,'R'); $pdf->Cell(5,0.5,$res_id['Snome'],1,1,'L');
        $pdf->Cell(1,0.5,"",0,1,'C');
        $pdf->Cell(0,0.5,"______________________________________________DADOS COMPRA______________________________________________",0,1,'C');
        $pdf->Cell(1,0.5,"",0,1,'C');
        $pdf->Cell(3,0.5,"Forma de Pagamento:",0,0,'R'); $pdf->Cell(5,0.5,$res_id['FormaPagamento'],0,1,'L');   
        $pdf->Cell(3,0.5,"Data Compra:",0,0,'R'); $pdf->Cell(5,0.5,date("d/m/Y", strtotime($res_id['DataContrato'])),0,0,'L');
        $pdf->Cell(3,0.5,"Parcelas:",0,0,'R'); $pdf->Cell(2,0.5,$res_id['QuantParcelas'],0,1,'L');
        $pdf->Cell(3,0.5,"Valor Compra R$:",0,0,'R'); $pdf->Cell(5,0.5,$res_id['ValorContrato'],0,0,'L');
        $pdf->Cell(3,0.5,"Produto:",0,0,'R'); $pdf->Cell(2,0.5,$res_id['DescricaoProduto'],0,1,'L');  
        $pdf->Cell(3,0.5,"Entrada R$:",0,0,'R'); $pdf->Cell(5,0.5,$res_id['Entrada'],0,0,'L');
        $pdf->Cell(3,0.5,"Vendedor:",0,0,'R'); $pdf->Cell(5,0.5,$res_id['Vendedor'],0,1,'L');
        $pdf->Cell(7.8,0.1,"--------------",0,1,'C');
        $pdf->Cell(3,0.5,"Saldo R$:",0,0,'R'); $pdf->Cell(5,0.5,$res_id['Saldo'],0,1,'L');
        $pdf->Cell(1,0.5,"",0,1,'C');
        $pdf->Cell(0,0.5,"_________________________________________________PARCELAS_________________________________________________",0,1,'C');
        $pdf->Cell(1,0.5,"",0,1,'C');
        $DataContrato = $res_id['DataContrato'];
        $QuantParcelas = $res_id['QuantParcelas'];
        $ValorContrato = $res_id['ValorContrato'];
        $Entrada = $res_id['Entrada'];
        $Saldo = $res_id['Saldo'];
        $DescricaoProduto = $res_id['DescricaoProduto'];
        $Vendedor = $res_id['Vendedor'];
        $FormaPagamento = $res_id['FormaPagamento'];
      }
    }
    $pdf->Output();
    ?>
  • 1

    Can you do a jsFiddle? Javascript functions are missing in the html code you presented

  • I haven’t used jfFiddle @Sergio yet, I’ll try... But what happens is that I need to use the same function of calculating monthly payment only in the FPDF class using to caucalo the variable Balance, Quantparcelas and Datacontrato. But so parcebi can not put anything in javascript in this class...

  • 1

    You won’t be able to use the same html JS, you’ll need to create a new one based on what is supported by Adobe Reader (I don’t know their Javascript API, but I know there is one).

  • understood, and perhaps a php function that calculates the due date via the BD field (dataContract, Balance and Quantinstallments) and exebindo in the pdf per Installment:1 - Installment value R$: 50,00 - due date: xx/xx/xxx and display the other installments...do you have any idea how I can proceed?

1 answer

2

Rafael,

The Javascript you are using is that of the browser, by the time it starts running the pdf file has already been generated and it has no means to read or edit the file data.

If the variables you need are already in the database the easiest way would be to "translate" the logic of your Javascript pro PHP functions.

  • understood, I will evaluate some other logic and bring news, hugs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.