我正在嘗試實現它,這樣當我點擊按鈕時,它允許我下載一個包含我在文本區寫的東西的PDF文件。
將jsPDF定義為頁面常量的另一種方法是這樣的,但是請注意,web security不會讓這些代碼片段在堆棧溢出頁面中運行,它們需要在您自己的環境中使用。
<!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>
您需要在腳本的開頭添加這一行:
window.jsPDF = window.jspdf.jsPDF;
最終代碼:
<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>
window.jsPDF = window.jspdf.jsPDF;
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>