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?
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.
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With