本文示範如何使用 jsPDF 在客戶端生成 PDF 文件,並透過 iframe 在網頁中直接展示生成的內容。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>jsPDF</title>
<script type="text/javascript" src="jspdf.js"></script>
<script type="text/javascript">
window.onload = function () {
var doc = new jsPDF();
// var doc = new jsPDF('landscape'); // 橫排
doc.setProperties({ // 設置文檔屬性
title: 'Title',
subject: 'This is the subject',
author: 'Dragon',
keywords: 'javascript, web 2.0, ajax',
creator: 'MEEE'
});
doc.setTextColor(0, 255, 0);
doc.setFontSize(22);
doc.setFont("times");
doc.setFontType("italic");
doc.text(20, 20, 'Hello world!'); // 添加文字
doc.setTextColor(255, 0, 0);
doc.setFontSize(16);
doc.setFont("helvetica");
doc.setFontType("bold");
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage(); // 添加頁
doc.setLineWidth(1); // 設置線寬
doc.setDrawColor(0, 255, 0); // 設置畫筆顏色
doc.setFillColor(255, 0, 0); // 設置填充顏色
doc.line(60, 20, 115, 60); // 畫線
doc.rect(100, 50, 20, 30); // 畫矩形
doc.ellipse(20, 20, 20, 10, 'F'); // 畫橢圓
doc.circle(120, 20, 20, 'FD'); // 畫圓
doc.triangle(100, 100, 110, 100, 120, 130, 'FD');
// doc.output('datauri'); // 直接輸出為新的 web 頁
document.getElementById("iframe123").src = doc.output('datauristring'); // 在 iframe 中顯示
}
</script>
</head>
<body>
<iframe id="iframe123" frameborder="0" width="400" height="500"></iframe>
</body>
</html>
程式透過 setProperties 設定文檔屬性,setTextColor、setFontSize、setFont 控制文字樣式,line、rect、ellipse、circle、triangle 等方法繪製圖形。最後關鍵的一步是 doc.output('datauristring'),把生成的 PDF 轉成 data URI 字串並指定給 iframe 的 src,就能在網頁中直接預覽 PDF 內容。