<!DOCTYPE html>
<html>
<head>
<title>Generate PDF from Text</title>
</head>
<body>
<h1>Generate PDF from Text</h1>
<textarea id="textInput" rows="10" cols="50"></textarea>
<br>
<button id="downloadBtn">Download as PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script>
document.getElementById("downloadBtn").addEventListener("click", function() {
var text = document.getElementById("textInput").value;
// Create a new jsPDF instance
var doc = new jsPDF();
// Set the font size and add the text to the PDF
doc.setFontSize(12);
doc.text(text, 10, 10);
// Download the PDF file
doc.save("my_pdf.pdf");
});
</script>
</body>
</html>
I am trying to acheive it so that the when I click the button, it allows me download a PDF file containing the things I wrote in the textarea.
An alternative way of defining jsPDF as a page constant is like this, however note that web security will not let these snippets run in Stack Overflow pages, they need to be used in your own environment.
<!DOCTYPE html>
<html>
<head>
<title>Generate PDF from Text</title>
</head>
<body>
<h1>Generate PDF from Text</h1>
<textarea id="textInput" rows="10" cols="50"></textarea>
<br>
<button id="downloadBtn">Download as PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js" integrity="sha512-qZvrmS2ekKPF2mSznTQsxqPgnpkI4DNTlrdUmTzrDgektczlKNRRhy5X5AAOnx5S09ydFYWWNSfcEqDTTHgtNA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
document.getElementById("downloadBtn").addEventListener("click", function() {
// Create a new jsPDF instance
const {jsPDF} = window.jspdf;
var doc = new jsPDF();
var text = document.getElementById("textInput").value;
// Set the font size and add the text to the PDF
doc.setFontSize(12);
doc.text(text, 10, 10);
// Download the PDF file
doc.save("my_pdf.pdf");
});
</script>
</body>
</html>
NOTE that in common with the way NATIVE PDF works there is no line wrap since text cannot be natively wrapped by a PDF
what you would need is to hardware key-in an enter at EOL (end of line)
With a few more bits of styling it makes for a good Notes.PDF generator especially if using a courier font for programmers code copying.