John
John

Reputation: 952

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?

Upvotes: 13

Views: 5929

Answers (3)

aljo f
aljo f

Reputation: 2500

Apparently, jsPDF has limitations and/or bugs. It has problems with complex tables (especially with colspans). It throws javascript errors which stops the renderer which is why you're getting blank pdfs.

https://github.com/MrRio/jsPDF/issues/516

https://github.com/MrRio/jsPDF/issues/595

A fork has been posted here: https://github.com/jutunen/jsPDF-table_2 but I'm not sure if it addresses other limitations of jsPDF.

Upvotes: 1

Mohammad Hamedani
Mohammad Hamedani

Reputation: 3354

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.

Upvotes: 6

rbaskam
rbaskam

Reputation: 749

<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.

Upvotes: 1

Related Questions