Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display PDF using an AJAX call

Tags:

jquery

ajax

pdf

I'm trying to display a PDF(which is created in the server side and pass to the client side as a web stream) through an AJAX call. My code is given below:

jQuery.ajax({
    type: "POST",
    processData: false,
    url: "aaaa.p?name=pdf",
    data: inputxml,
    contentType: "application/xml; charset=utf-8",
    success: function(data)
    {
      // here the data is the PDF stream i'm getting from the server side. 

    }
});

The 'inputxml' is containing input parameters for the server to create the PDF. and the 'data' in the success function containing PDF stream. Is there any way to open the PDF file on the browser inside the success function of the AJAX call with-out doing any page submit? In the server side the PDF is not physically generated also. Highly appreciate your help....

like image 707
Knissanka Avatar asked Jan 28 '13 09:01

Knissanka


2 Answers

Why do you load it via AJAX? Why don't you load it in an IFRAME that you generate when you need it. The standard browsers plugin will display it then inside that Iframe.

$('#link').click(function(e) {
    e.preventDefault(); // if you have a URL in the link
    jQuery.ajax({
        type: "POST",
        processData: false,
        url: "aaaa.p?name=pdf",
        data: inputxml,
        contentType: "application/xml; charset=utf-8",
        success: function(data)
        {
            var iframe = $('<iframe>');
            iframe.attr('src','/pdf/yourpdf.pdf?options=first&second=here');
            $('#targetDiv').append(iframe);
        }
    });
});
like image 77
Zim84 Avatar answered Oct 03 '22 16:10

Zim84


Here is my way of dealing with this issue. It is based on line 50 of this pdfmake file (https://github.com/bpampuch/pdfmake/blob/master/src/browser-extensions/pdfMake.js).

  1. assuming you have a pdf stream I convert it to base64 and echo it back to my AJAX:

    $pdfString = $mpdf->Output('', 'S');
    $pdfBase64 = base64_encode($pdfString);
    echo 'data:application/pdf;base64,' . $pdfBase64;
    
  2. Here is my AJAX code. When receiving data it opens a new window and replaces url with base64 endoded data:

    var ajaxRequest = $.ajax({
        url: "php/generate-pdf/print-control.php",
        data: '',
        cache: false,
        contentType: 'application/json',
        processData: false,
        type: 'POST'
    
    });
    $.when(ajaxRequest).done(function (ajaxValue) {
        var win = window.open('', '_blank');
        win.location.href = ajaxValue;
    });
    

    The downside of this method is that you get a base64 string in the adress bar.

like image 36
andrzej.szmukala Avatar answered Oct 03 '22 16:10

andrzej.szmukala