
本文旨在解决使用jspdf库将动态生成的html表格下载为pdf时文件内容为空的问题。核心解决方案是利用`html2canvas`库将html元素转换为图像,然后将该图像添加到jspdf文档中,从而确保生成的pdf文件包含完整的表格内容。文章将详细阐述实现步骤、提供完整代码示例及注意事项,帮助开发者准确生成包含html内容的pdf文件。
在前端开发中,将页面上的HTML内容导出为PDF是常见的需求。jsPDF是一个流行的JavaScript库,用于在客户端生成PDF文件。然而,许多开发者在使用jsPDF尝试将复杂的HTML结构(如表格)转换为PDF时,可能会遇到生成的PDF文件为空白页的问题。
原始代码中尝试使用doc.html(content)方法直接将HTML字符串添加到PDF。虽然jsPDF在某些版本中提供了类似的html()方法,但它通常依赖于html2canvas或特定的DOM解析能力,并且对于动态生成或复杂样式的HTML内容,其兼容性和渲染效果可能不尽如人意,甚至可能导致内容无法正确渲染而出现空白文件。
解决此问题的关键在于理解jsPDF如何处理HTML内容。最可靠的方法是将HTML元素“渲染”成一个图像,然后将这个图像插入到PDF文档中。html2canvas库正是为此目的而生,它可以将任何HTML元素渲染到Canvas上,我们再将Canvas内容转换为图片数据,供jsPDF使用。
本教程将指导您如何结合使用html2canvas和jsPDF,将动态生成的HTML表格正确地导出为PDF文件。
立即学习“前端免费学习笔记(深入)”;
确保您的HTML文件中正确引入了jsPDF和html2canvas库。dompurify库虽然在原始代码中出现,但对于本示例的HTML转图片再转PDF的流程并非必需,您可以根据实际安全需求决定是否保留。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script> <!-- dompurify 并非必需,但可用于HTML内容净化 --> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.3.1/purify.min.js"></script> -->
页面需要一个用户输入框来决定生成表格的数量,以及两个按钮分别用于生成表格和下载PDF。生成的表格将放置在一个div容器中。
<h1>Tabelas de Bingo</h1> <label for="repeticoes">Número de Repetições:</label> <input type="number" id="repeticoes" value="3"> <button onclick="criarTabelas()">Gerar Tabelas</button> <button onclick="CriaPDF()">Baixar PDF</button> <div id="container"></div>
为表格添加一些基本样式,以确保在页面上和PDF中都有良好的视觉效果。
table {
width: 700px;
height: 500px;
font: 17px Calibri;
margin-bottom: 20px;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}这部分代码负责根据用户输入的数字动态生成多个“宾果”表格。每个表格包含随机生成的基因组合。这部分功能在原始代码中已经正确实现。
window.jsPDF = window.jspdf.jsPDF; // 确保jsPDF全局可用
// 基因组合数据
var combinacoes1 = ["UUU", "UUC", "UUA", "UUG", "UCU", "UCC", "UCA", "UCG", "UAU", "UAC", "UAA", "UAG", "UGU", "UGC", "UGA", "UGG"];
var combinacoes2 = ["CUU", "CUC", "CUA", "CUG", "CCU", "CCC", "CCA", "CCG", "CAU", "CAC", "CAA", "CAG", "CGU", "CGC", "CGA", "CGG"];
var combinacoes3 = ["AUU", "AUC", "AUA", "AUG", "ACU", "ACC", "ACA", "ACG", "AAU", "AAC", "AAA", "AAG", "AGU", "AGC", "AGA", "AGG"];
var combinacoes4 = ["GUU", "GUC", "GUA", "GUG", "GCU", "GCC", "GCA", "GCG", "GAU", "GAC", "GAA", "GAG", "GGU", "GGC", "GGA", "GGG"];
// 从给定数组中随机生成4个不重复的值
function gerarValorAleatorio(valores) {
var temp = valores.slice();
var valoresAleatorios = [];
for (var i = 0; i < 4; i++) {
var indice = Math.floor(Math.random() * temp.length);
valoresAleatorios.push(temp[indice]);
temp.splice(indice, 1);
}
return valoresAleatorios;
}
// 根据用户输入生成指定数量的表格
function criarTabelas() {
var container = document.getElementById("container");
container.innerHTML = ""; // 清除之前的内容
var repeticoes = parseInt(document.getElementById("repeticoes").value, 10) || 0;
for (var i = 0; i < repeticoes; i++) {
var div = document.createElement("div");
div.className = "tabelaBingo"; // 添加类名以便后续选择
var tabela = document.createElement("table");
tabela.innerHTML = "<caption>Tabela de Bingo de Genes " + (i + 1) + "</caption>";
for (var j = 0; j < 4; j++) {
var resultados;
if (j === 0) {
resultados = gerarValorAleatorio(combinacoes1);
} else if (j === 1) {
resultados = gerarValorAleatorio(combinacoes2);
} else if (j === 2) {
resultados = gerarValorAleatorio(combinacoes3);
} else if (j === 3) {
resultados = gerarValorAleatorio(combinacoes4);
}
var tr = document.createElement("tr");
tabela.appendChild(tr);
for (var k = 0; k < 4; k++) {
var valor = resultados[k];
var td = document.createElement("td");
td.textContent = valor;
tr.appendChild(td);
}
}
div.appendChild(tabela);
container.appendChild(div);
}
}这是解决问题的关键部分。我们将遍历所有生成的表格,使用html2canvas将每个表格渲染为Canvas图像,然后将图像添加到独立的jsPDF文档中。
function CriaPDF() {
var tabelaBingo = document.getElementsByClassName("tabelaBingo");
var promises = []; // 用于存储每个表格转换为图片的Promise
for (let i = 0; i < tabelaBingo.length; i++) { // 使用let确保i在每次循环中独立
var tabela = tabelaBingo[i];
// 使用html2canvas将表格元素渲染为canvas
var promise = html2canvas(tabela, {
scale: 2 // 提高渲染质量,避免图片模糊
}).then(function (canvas) {
var imgData = canvas.toDataURL("image/png"); // 将canvas内容转换为PNG图片数据
var doc = new jsPDF('p', 'mm', 'a4'); // 创建一个新的PDF文档,A4大小
var imgWidth = 210; // A4页面的宽度 (mm)
// 根据图片原始宽高比计算图片在PDF中的高度,确保图片不变形
var imgHeight = canvas.height * imgWidth / canvas.width;
// 如果图片高度超过A4页面高度,则进行分页处理(简单示例,实际应用可能需要更复杂的逻辑)
let position = 0;
let heightLeft = imgHeight;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= doc.internal.pageSize.getHeight();
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= doc.internal.pageSize.getHeight();
}
// 保存PDF文件
doc.save("bingo" + (i + 1) + ".pdf");
});
promises.push(promise);
}
// 等待所有PDF生成完成后执行回调
Promise.all(promises).then(function () {
console.log("所有PDF已成功生成并下载。");
}).catch(function(error) {
console.error("生成PDF时发生错误:", error);
});
}将上述HTML、CSS和JavaScript代码整合到一个文件中,即可运行。
<!DOCTYPE html>
<html>
<head>
<title>Tabelas de Bingo</title>
<style>
table {
width: 700px;
height: 500px;
font: 17px Calibri;
margin-bottom: 20px;
}
table, th, td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</head>
<body>
<h1>Tabelas de Bingo</h1>
<label for="repeticoes">Número de Repetições:</label>
<input type="number" id="repeticoes" value="3">
<button onclick="criarTabelas()">Gerar Tabelas</button>
<button onclick="CriaPDF()">Baixar PDF</button>
<div id="container"></div>
<script>
window.jsPDF = window.jspdf.jsPDF;
// 基因组合数据 (与上面相同,此处省略以保持简洁)
var combinacoes1 = ["UUU", "UUC", "UUA", "UUG", "UCU", "UCC", "UCA", "UCG", "UAU", "UAC", "UAA", "UAG", "UGU", "UGC", "UGA", "UGG"];
var combinacoes2 = ["CUU", "CUC", "CUA", "CUG", "CCU", "CCC", "CCA", "CCG", "CAU", "CAC", "CAA", "CAG", "CGU", "CGC", "CGA", "CGG"];
var combinacoes3 = ["AUU", "AUC", "AUA", "AUG", "ACU", "ACC", "ACA", "ACG", "AAU", "AAC", "AAA", "AAG", "AGU", "AGC", "AGA", "AGG"];
var combinacoes4 = ["GUU", "GUC", "GUA", "GUG", "GCU", "GCC", "GCA", "GCG", "GAU", "GAC", "GAA", "GAG", "GGU", "GGC", "GGA", "GGG"];
function gerarValorAleatorio(valores) {
var temp = valores.slice();
var valoresAleatorios = [];
for (var i = 0; i < 4; i++) {
var indice = Math.floor(Math.random() * temp.length);
valoresAleatorios.push(temp[indice]);
temp.splice(indice, 1);
}
return valoresAleatorios;
}
function criarTabelas() {
var container = document.getElementById("container");
container.innerHTML = "";
var repeticoes = parseInt(document.getElementById("repeticoes").value, 10) || 0;
for (var i = 0; i < repeticoes; i++) {
var div = document.createElement("div");
div.className = "tabelaBingo";
var tabela = document.createElement("table");
tabela.innerHTML = "<caption>Tabela de Bingo de Genes " + (i + 1) + "</caption>";
for (var j = 0; j < 4; j++) {
var resultados;
if (j === 0) resultados = gerarValorAleatorio(combinacoes1);
else if (j === 1) resultados = gerarValorAleatorio(combinacoes2);
else if (j === 2) resultados = gerarValorAleatorio(combinacoes3);
else if (j === 3) resultados = gerarValorAleatorio(combinacoes4);
var tr = document.createElement("tr");
tabela.appendChild(tr);
for (var k = 0; k < 4; k++) {
var td = document.createElement("td");
td.textContent = resultados[k];
tr.appendChild(td);
}
}
div.appendChild(tabela);
container.appendChild(div);
}
}
function CriaPDF() {
var tabelaBingo = document.getElementsByClassName("tabelaBingo");
var promises = [];
for (let i = 0; i < tabelaBingo.length; i++) {
var tabela = tabelaBingo[i];
var promise = html2canvas(tabela, {
scale: 2 // 提高渲染质量
}).then(function (canvas) {
var imgData = canvas.toDataURL("image/png");
var doc = new jsPDF('p', 'mm', 'a4');
var imgWidth = 210;
var imgHeight = canvas.height * imgWidth / canvas.width;
let position = 0;
let heightLeft = imgHeight;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= doc.internal.pageSize.getHeight();
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= doc.internal.pageSize.getHeight();
}
doc.save("bingo" + (i + 1) + ".pdf");
});
promises.push(promise);
}
Promise.all(promises).then(function () {
console.log("所有PDF已成功生成并下载。");
}).catch(function(error) {
console.error("生成PDF时发生错误:", error);
});
}
</script>
</body>
</html>通过将html2canvas与jsPDF结合使用,我们可以有效地解决将动态生成的HTML内容导出为PDF时遇到的空白文件问题。核心思想是将HTML元素转换为高质量的图像,然后将这些图像嵌入到PDF文档中。这种方法提供了更高的灵活性和可靠性,尤其适用于处理复杂或动态的HTML结构。理解这两个库的工作原理及其异步特性,是成功实现此类功能的关键。
以上就是解决jsPDF下载空文件问题:HTML表格转换为PDF的正确姿势的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号