
本文将展示如何在 js/react 中从 json 数据创建 pdf。
作为开发人员,我们必须将 pdf 生成集成到应用程序中。因此,在本文中,我们将讨论使用 jspdf 创建 pdf。
那么,让我们开始吧。
我们将专门为本文使用 react 环境。我假设你熟悉 javascript/react 并且已经设置了 react 环境
在深入研究之前,我们需要一些示例数据来生成 pdf。我们将创建一个方法来生成这些数据。
const generateusers = (count) => {
const users = [];
for (let i = 1; i <= count; i++) {
const user = {
id: i,
firstname: `firstname_${i}`,
lastname: `lastname_${i}`,
email: `email_${i}@example.com`,
address: [
`street ${i + 1}, address line 1`,
`district ${(i % 7) + 1}, city_${i}`,
],
};
users.push(user);
}
return users;
};
现在,我们需要安装一些 npm 包 jspdf 和 jspdf-autotable。
jspdf 负责创建 pdf,而 jspdf-autotable 用于在 pdf 中以表格格式显示数据。
您可以使用以下命令来安装这两个软件包。
npm i jspdf-autotable jspdf
现在,我们将开发一种处理 pdf 创建的方法。我将创建一个通用的generatepdf方法,这样你就可以在任何需要的地方使用它。
1。函数定义
函数generatepdf将数据作为参数,该参数应该是一个对象数组(要包含在pdf中的json数据)。
export const generatepdf = (data) => {
2。 pdf 文档设置
使用以下选项创建一个新的 jspdf 实例:
const doc = new jspdf("l", "pt", "a3");
// if you want to use custom dimensions
// width,height
const doc = new jspdf("l", "pt", [3000,1000]);
3。为 pdf 添加标题
doc.setfontsize(16);
doc.text("json data pdf", doc.internal.pagesize.getwidth() / 2, 30, {
align: "center",
});
4。提取表头
const tablecolumnheaders = object.keys(data[0]);
5。设置表格行格式
迭代数据中的每个对象,创建一个新数组(tablerows),其中:
const tablerows = data.map((row) =>
object.keys(row).map((key) => {
const value = row[key];
if (array.isarray(value)) {
return value.join(", ");
}
return value;
})
);
6。将表格添加到 pdf
使用以下选项配置表:
doc.autotable({
starty: 50,
head: [tablecolumnheaders],
body: tablerows,
margin: { top: 50, left: 20, right: 20 },
styles: {
fontsize: 10,
cellpadding: 5,
valign: "middle",
},
headstyles: { fillcolor: [41, 128, 185], textcolor: 255, fontsize: 12 },
alternaterowstyles: { fillcolor: [245, 245, 245] },
columnstyles: { auto: { cellwidth: auto } },
theme: "striped",
});
7。保存 pdf
以文件名“js-pdf.pdf”保存 pdf 文件。
doc.save(`${filename}.pdf`);
这是此代码的完整版本。
// app.jsx
import "./styles.css";
import { generatepdf } from "./pdf.jsx";
export default function app() {
const generateusers = (count) => {
const users = [];
for (let i = 1; i <= count; i++) {
const user = {
id: i,
firstname: `firstname_${i}`,
lastname: `lastname_${i}`,
email: `email_${i}@example.com`,
address: [
`street ${i + 1}, address line 1`,
`district ${(i % 7) + 1}, city_${i}`,
],
};
users.push(user);
}
return users;
};
const pdfgenerator = () => {
let jsondata = generateusers(100);
generatepdf(jsondata);
};
return (
hello codesandbox
start editing to see some magic happen!
);
}
//Pdf.jsx
import jsPDF from "jspdf";
import "jspdf-autotable";
export const generatePDF = (data) => {
let fileName = "JS-pdf";
const doc = new jsPDF("l", "pt", "a3");
doc.setFontSize(16);
doc.text("JSON Data PDF", doc.internal.pageSize.getWidth() / 2, 30, {
align: "center",
});
const tableColumnHeaders = Object.keys(data[0])
// Determine the table rows based on the values in data
const tableRows = data.map((row) =>
Object.keys(row).map((key) => {
const value = row[key];
if (Array.isArray(value)) {
return value.join(", ");
}
return value; // Return non-array values as is
})
);
doc.autoTable({
startY: 50,
head: [tableColumnHeaders],
body: tableRows,
margin: { top: 50, left: 20, right: 20 },
styles: {
fontSize: 10,
cellPadding: 5,
valign: "middle",
},
headStyles: { fillColor: [41, 128, 185], textColor: 255, fontSize: 12 },
alternateRowStyles: { fillColor: [245, 245, 245] },
columnStyles: { auto: { cellWidth: auto } }
theme: "striped",
});
doc.save(`${fileName}.pdf`);
};
现在已经完成了。希望你喜欢它。祝你有美好的一天!!!
以上就是如何使用 jsPDF 在 React 中从 JSON 数据创建 PDF的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号