您的位置:首页 > Web前端 > React

react pdf_如何在React中创建PDF报告

2020-08-21 00:55 1316 查看

react pdf

In this article, we'll be building a button that generates a PDF document (like you see above) based on data from an API call.

在本文中,我们将构建一个按钮,该按钮根据API调用中的数据生成PDF文档(如您在上面看到的)。

A couple of days ago, I built a full stack CRM application to manage communication between customers and support agents.

几天前,我构建了一个全栈CRM应用程序来管理客户和支持代理之间的通信。

I needed a way for agents to generate a summary of closed tickets as a PDF file. After searching across the internet for an EASY way to do this, I dare say this article will show you the easiest way out there.

我需要代理人将已关闭的票证摘要生成为PDF文件的方法。 在互联网上搜索实现此目的的简便方法之后,我敢说这篇文章将向您展示最简单的方法。

Let's get into it, shall we?

让我们开始吧,对吧?

安装程序包 (Setup packages)

First, let's install the packages we need.

首先,让我们安装所需的软件包。

npm i jspdf jspdf-autotable

定义一个函数来生成PDF (Define a function to generate the PDFs)

Next, let's define a function that we can call anywhere to generate a PDF for us. I've added a lot of comments to help you understand what is going on with each line.

接下来,让我们定义一个函数,该函数可在任何地方调用以为我们生成PDF。 我添加了很多评论来帮助您了解每一行的情况。

// services/reportGenerator.js

import jsPDF from "jspdf";
import "jspdf-autotable";
// Date Fns is used to format the dates we receive
// from our API call
import { format } from "date-fns";

// define a generatePDF function that accepts a tickets argument
const generatePDF = tickets => {
// initialize jsPDF
const doc = new jsPDF();

// define the columns we want and their titles
const tableColumn = ["Id", "Title", "Issue", "Status", "Closed on"];
// define an empty array of rows
const tableRows = [];

// for each ticket pass all its data into an array
tickets.forEach(ticket => {
const ticketData = [
ticket.id,
ticket.title,
ticket.request,
ticket.status,
// called date-fns to format the date on the ticket
format(new Date(ticket.updated_at), "yyyy-MM-dd")
];
// push each tickcet's info into a row
tableRows.push(ticketData);
});

// startY is basically margin-top
doc.autoTable(tableColumn, tableRows, { startY: 20 });
const date = Date().split(" ");
// we use a date string to generate our filename.
const dateStr = date[0] + date[1] + date[2] + date[3] + date[4];
// ticket title. and margin-top + margin-left
doc.text("Closed tickets within the last one month.", 14, 15);
// we define the name of our PDF file.
doc.save(`report_${dateStr}.pdf`);
};

export default generatePDF;

创建一个组件以保存要呈现的票证 (Create a component to save the tickets to be rendered)

Now, let's create a simple Component that fetches and saves the ticket to state.

现在,让我们创建一个简单的Component来获取并保存票证到状态。

import React, { useEffect, useState } from "react";
import generatePDF from "../services/reportGenerator";

const Tickets = () => {

const [tickets, setTickets] = useState([]);

useEffect(() => {
const getAllTickets = async () => {
try {
const response = await axios.get("http://localhost:3000/tickets");
setTickets(response.data.tickets);
} catch (err) {
console.log("error");
}
};
getAllTickets();
}, []);

const reportTickets = tickets.filter(ticket => ticket.status === "completed");

return (
<div>
<div className="container mb-4 mt-4 p-3">
<div className="row">
{user.user.role === "user" ? (
<> </>
) : (
<button
className="btn btn-primary"
onClick={() => generatePDF(reportTickets)}
>
Generate monthly report
</button>
)}
</div>
</div>
<TicketsComponent tickets={tickets} />
</div>
);
};

export default Tickets;

A few points about our

<Tickets />
component. When our component loads, we make a request to http://localhost:3000/tickets to fetch all our tickets. We then save them to the
tickets
state. And finally, we pass them as a prop to the
<TicketsComponent />
to render the tickets in the DOM.

关于

<Tickets />
组件的几点说明。 当我们的组件加载时,我们向http:// localhost:3000 / tickets请求以获取所有票证。 然后,我们将它们保存到
tickets
状态。 最后,我们将它们作为道具传递给
<TicketsComponent />
以在DOM中呈现票证。

We also have a

reportTickets
variable that filters our tickets to get only the tickets that have the status of
completed
.

我们还有一个

reportTickets
变量,该变量过滤票证以仅获取状态为
completed
的票证。

Notice that we also created the Generate Monthly Report button that calls the

generatePDF()
function that we defined earlier when clicked.

注意,我们还创建了“ 生成每月报告”按钮,该按钮调用我们在单击时定义的

generatePDF()
函数。

创建一个组件以在表中显示票证 (Create a component to display the tickets in a table)

Next, let's define our

<TicketsComponent />
that will be responsible for displaying our tickets in a nice looking table. Remember that it accepts the tickets to be displayed as a prop from the
<Tickets />
component.

接下来,让我们定义我们的

<TicketsComponent />
,它将负责在漂亮的表中显示我们的票证。 请记住,它接受
<Tickets />
组件中显示为道具的
<Tickets />

import React from "react";
import { Link } from "react-router-dom";

const TicketsComponent = ({ tickets }) => {

// a function that assigns bootstrap styling classes based on
// the status of the ticket
const assignColorToTicketStatus = ticket => {
if (ticket.status === "completed") {
return "p-3 mb-2 bg-success text-white";
} else if (ticket.status === "in_progress") {
return "p-3 mb-2 bg-warning text-dark";
} else if (ticket.status === "opened") {
return "p-3 mb-2 bg-light text-dark";
}
};
return (
<div className="container">
{tickets.length === 0 ? (
"You currently have no tickets created"
) : (
<table className="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Title</th>
<th scope="col">Issue</th>
<th scope="col">Status</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{tickets.map(ticket => (
<tr key={ticket.id}>
<td>{ticket.id}</td>
<td>{ticket.title}</td>
<td>{ticket.request}</td>
<td className={assignColorToTicketStatus(ticket)}>
{ticket.status}
</td>
<td>
<Link to={`/ticket/${ticket.id}`}>See comments</Link>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
};

export default TicketsComponent;

Now, let's see what our application currently looks like. We have 10 tickets in our state but I'll show 6 here for convenience.

现在,让我们看看我们的应用程序当前的外观。 我们在该州有10张门票,为方便起见,我将在这里显示6张。

As you can see, we have a number of tickets at different statuses. We also have our Generate monthly report button that, when clicked, will export the PDF file.

如您所见,我们有许多状态不同的票证。 我们还有一个“ 生成每月报告”按钮,单击该按钮将导出PDF文件。

And that's it. You should end up with a PDF file with the filename in the form report_dddmmyyyy downloaded in your browser.

就是这样。 您应该最终获得一个PDF文件,该文件的文件名形式是在浏览器中下载的report_dddmmyyyyyy

If this article helped you out, say hello on twitter.

如果这篇文章对您有所帮助,请在twitter上打个招呼。

翻译自: https://www.freecodecamp.org/news/how-to-create-pdf-reports-in-react/

react pdf

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: