Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create PDF file from PHP

I am trying to create an PDF file from a PHP page with jsPDF but it is not working and I dont know whats wrong.

Can someone help me?

First I have a Iframe. The page I want to convert is displayed in the Iframe:

Iframe:

<?php
    <iframe id="frame" name="frame" width="100%" height="1160px" frameborder="0" src="./page.php?id=' . $_GET['id'] . '"></iframe>
    <button id="cmd">Button</button>
?>

When I hit Button the following script should convert the page to PDF

Script

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script type="text/javascript">
    var doc = new jsPDF();

    var specialElementHandlers = {
        '#editor': function(element, renderer){
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('frame').get(0), 15, 15, {
            'width': 170, 
            'elementHandlers': specialElementHandlers
        });

    doc.save('sample-file.pdf');
    });
</script>

But when I hit Button. Nothing is happening. Does someone know whats wrong?

like image 733
John Avatar asked Jun 02 '17 11:06

John


2 Answers

You must be get html of iframe, so use contents() function and then get documentElement of iframe:

<iframe id="frame" name="frame" width="100%" height="1160px" frameborder="0" src="http://localhost/"></iframe>
<button id="cmd">Button</button>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script type="text/javascript">
    var doc = new jsPDF();

    var specialElementHandlers = {
        '#editor': function(element, renderer){
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('#frame').contents().find('html').html(), 15, 15, {
            'width': 170, 
            'elementHandlers': specialElementHandlers
        });

    doc.save('sample-file.pdf');
    });
</script>

Note: If your iframe source page or part of it protected with x-frame-options header, you cannot access to html of it.

like image 150
Mohammad Hamedani Avatar answered Sep 21 '22 15:09

Mohammad Hamedani


<button onclick="cmd()">Button</button>

Change this to

<button id="cmd">Button</button>

You are calling the click event in JS on the id. Or change the onclick event to a function with the name cmd.

like image 26
rbaskam Avatar answered Sep 23 '22 15:09

rbaskam