Requirement: When the back-end interface returns a PDF file address, it needs to be displayed in front and paginated
React-pdf: Failed to load PDF file: Failed to load PDF file
It must be added:
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
Copy the code
Invalid parameter object: need either. Data,.range, or.url
File ={{url}} file={{url}
paging
For Pagination, use ANTD’s Pagination
The complete code
<>
// setTotal Gets the total number of pages in the PDF
<Document file={url} onLoadSuccess={({ numPages}) = > setTotal(numPages)}>
<Page key={page} pageNumber={page} width={600} />
</Document>
<Pagination
style={{ marginTop: 20 }}
total={total}
showTotal={total= >${total} page '} current={page} pageSize={1} size="small" onChange={page => setPage(page)} />
</>
Copy the code
Download function
The most basic implementation of downloading is to add the Download attribute to the tag. But when it comes to files such as images/PDFS, it will open new link mode for preview. To implement the download function, you must first convert the file in the URL to a BLOB address for download.
export const downloadFile = async (url: string.name: string) = > {const { data } = await axios({
method: 'get'.baseURL: BACKEND_URL,
url,
headers: {
accessToken: user.getToken(),
},
});
const link = document.createElement('a');
/ / method
fetch(data.data)
.then(res= > res.blob())
.then(blob= > {
// Convert link address character content to bloB address
link.href = URL.createObjectURL(blob);
link.download = `${name}.pdf`;
document.body.appendChild(link);
link.click();
link.remove();
});
/ / method 2
link.href = URL.createObjectURL(res.data);
link.download = `${name}.pdf`;
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(downloadUrl);
};
Copy the code
Main Reference Sources
- react-pdf