简体   繁体   中英

Using PHP DOMPDF and AJAX to download a PDF File

I have this PHP File called print.php:

<?php
require_once("modules/pdf/dompdf_config.inc.php");
$html = $_POST["toRender"];
$number = $_POST["number"];
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream($number.".pdf");

As you can see, the HTML and a Number are received via POST.

The JavaScript file looks like this:

 $("#btnViewPDF").click(function() {

        var theHtml = $("#printable").html();
        var theNumber = $("#invoiceNumber").val();

        $.ajax({
            type : "post",
            url  : "views/print.php",
            data : {toRender : theHtml, number : theNumber},
            beforeSend: function() {
                $(".ajax-loader-bg").fadeIn();
            }
        }).always(function() {
            $(".ajax-loader-bg").fadeOut();
        });
        return false;
    });

Basically it takes all the content inside a DIV called 'printable' but what I want next is the PDF that has been generated in print.php to be displayed, I haven't been able to figure out how can I make this.

I've made it work when I generate test HTML inside print.php and then I type in the url mysite.com/print.php ... it renders the PDF and allows me to download it or see it in another browser tab.

How can I achieve this via AJAX?

You can't download something via AJAX, you could simulate the behavior using an hidden iframe.

Not that you can't download it, but, it will never end up in the filesystem for saving purpose because javascript can't do that for security reasons.

Anyway people always find solutions, you can try this: https://stackoverflow.com/a/23797348/1131176

i did achieve this, by doing just a trick, this example is made in codeigniter, so you can adapt it, first, the ajax method:

$.ajax({
    url: base_url+"controladorapr/exportComprobanteIngresos", //method i called
    data: $(this).serialize() //i serialized data from a form,
type:"POST",
    dataType: 'JSON',
    success: function (data) {
  //create a link to download the pdf file
  var link=document.createElement('a');
  //i used the base url to target a file on mi proyect folder
  link.href=window.URL = base_url+"exportacion.pdf";
  //download the name with a different name given in the php method
  link.download=data.nombre_archivo;
  link.click();
  //this js function hides the loading gif i use
  hideLoad();
    }
});

Now, let's head to the method on my controller:

function exportComprobanteIngresos(){
   //receive your ajax data
   $fecha = $this->input->post("fecha_comprobante_ingresos");
   $fecha = date_format(DateTime::createFromFormat('d/m/Y', $fecha), "Y-m-d");
   //send data to pdf
   $data["fecha"] = $fecha;

   //do some query here to send data and save it into $data[] array

   //pdf size
   $tamaño = 'A4';
   //create a file name
   $nombre_archivo = "Comprobante_ingresos".date_format(DateTime::createFromFormat('Y-m-d', $fecha), "Y_m_d").".pdf";
   //load dompdf method, i will show this later, and send the data from db and file name
   $pdf = $this->pdf->load_view("pdf/comprobanteIngresos", $data, $tamaño, $nombre_archivo);
   //save the pdf content into the file we are downloading
   file_put_contents('exportacion.pdf', $pdf);
   //send data back to javascript
   $data2["nombre_archivo"] = $nombre_archivo;
   echo json_encode($data2);

}

now, we will include dompdf, to use dompdf on codeigniter see this answer: Codeigniter with dompdf

Now, this is the code from dompdf i use in the function '$this->pdf->load_view':

 $dompdf = new Dompdf();
 $html = $this->ci()->load->view($view, $data, TRUE);

 $dompdf->loadHtml($html);

 // (Optional) Setup the paper size and orientation
 $dompdf->setPaper($size, 'portrait');

 // Render the HTML as PDF
 $dompdf->render();

 // Output the generated PDF to variable and return it to save it into the file
 $output = $dompdf->output();
 return $output;

now with this, i managed to use ajax with dompdf and put a loading gif to it, and it works great, by last, the php file you load on '$this->pdf->load_view' doesn't have a header or else, is pure html and php, hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM