1. Install the PDFObject plug-in
npm i pdfobject
Copy the code
2. The import
import PDFObject from 'pdfobject'
Copy the code
3. Obtain the back-end file flow
$post(1000165, { projectId: value.pid, month: newStr, reportType: "pdf" }, { responseType: "arraybuffer" })/ / request
.then((data) = > {
let judge = this.transformation(data)
if (judge.success) {
let oArrayBuffer = data.data;/ / file stream
let blob = new Blob([oArrayBuffer], { type: "application/pdf" });// A bloB will be generated
let testUrl = window.URL.createObjectURL(blob)// Convert to link
PDFObject.embed(testUrl, '.bottom-pdf')// The first argument is the converted link, and the second argument is className
} else {
message.error("File does not exist"); }})})Copy the code
4. Write the return structure in render()
render(){
return(
<React.Fragment>
<div className="bottom-pdf">// Render the PDF file to this node</div>
</React.Fragment>)}Copy the code
At this stage you have the PDF file displayed
5.PDFObject plug-in documentation
The plugin documentation
6. Problems encountered during development
A,
- In the development encountered a more difficult problem, the back-end file stream returned after rendering success, display is blank, the reason is to request the file stream type interface, need to put
responseType
Set toarraybuffer
, otherwise it will render blank, this aspect of the problem is also difficult to find in Baidu, is a point that needs to pay attention to.
Second,
- Render normally when the request returns to the file stream interface successfully.
- When the request request file flow interface fails, because the request
responseType
Be set toarraybuffer
, so the failure parameter returned by the back end is{"success":"false","code":"200","message":" no file "}
, will also be convertedarraybuffer
In this case, the HTTP status codes returned by both successful and failed requests are 200, and the parameters of failed requests cannot be obtained
To convert the arrayBuffer type data to JSON objects, and then determine, this part of baidu, arrayBuffer to JSON objects, there are also more pit, because Baidu many methods after converting messgae: no file, this will be garbled.