4

I am trying to output the text content of a collection of text area inputs as a pdf file using jspdf. I can't work out how to put in line breaks or use the pagesplit:true option as it doesn't take it as an argument in doc.text. I see the a similar question was asked 25 days ago but I don't understand how to implement the answer and am not sure it would work for multiple text areas. I would greatly appreciate any advice.

<html>
<title>Multi-line/pagesplit</title>
<body>
<form action="#" method="post" id="myForm">
    <table id="myTable">
        <tr>
            <td>Please enter text</td>
        </tr>
        <tr>
            <td><textarea rows="4" cols="50" id="myText" wrap="soft" placeholder="Your text..."></textarea></td>
        </tr>
    </table>
</form>
<input type="button" value="Download as PDF" onclick="downloadPDF()"/></button>
<script>
function downloadPDF(){
    var text = document.getElementById("myText").value;
    var doc = new jsPDF();
    doc.setFontSize(12);
    doc.text(20, 20, text);
    doc.save('Test.pdf');
    ;
}
</script>
<script src="jspdf.min.js"></script>
</body>
</html>

EDIT: I found a really helpful answer here: Word wrap in generated PDF (using jsPDF)? and managed to tweak it slightly for my needs. It seems that the necessary plugins were already in jspdf.min.js. Here's the code I've ended up using:

<!DOCTYPE html>
<html>
<title>Multi-line/pagesplit</title>
<body>
<form action="#" method="post" id="myForm">
    <table id="myTable">
        <tr>
            <td>Please enter text</td>
        </tr>
        <tr>
            <td><textarea rows="4" cols="50" id="myText" wrap="soft" placeholder="Your text..."></textarea></td>
        </tr>
    </table>
</form>
<input type="button" value="Download as PDF" onclick="downloadPDF()"/>.     </button>
<script>
function downloadPDF(){
    var text = document.getElementById("myText").value;
    var doc = new jsPDF();
    var splitText = doc.splitTextToSize(text, 250);
    var pageHeight = doc.internal.pageSize.height;
    doc.setFontSize(11);
    var y = 20;
    for (var i=0; i<splitText.length; i++){
        if (y > 275){
            y = 20;
            doc.addPage();
        }
        doc.text(20, y, splitText[i]);
        y = y + 5;
    }
    doc.save('Test.pdf');
    ;
}
</script>
<script src="jspdf.min.js"></script>
</body>
</html>
Druloop
  • 43
  • 1
  • 7

0 Answers0