我想使用react-pdf来显示PDF,并开发一个打印函数来直接打印(比如使用window.print());
REST服务器是使用Jersey开发的。
PDF将从服务器生成,并使用Jersey返回到React客户端,返回类型为application/pdf。React客户端将使用react-pdf显示PDF。
我不想在"file“中声明URL路径,因为如果React状态改变并触发重新渲染,这将再次从服务器检索PDF。另外,我需要开发一个打印功能来打印显示的PDF (因为如果再次从服务器检索PDF,PDF内容可能会更改)
下面显示了我的代码:
服务器:
@Override
@GET
@Path("/pdf")
@Produces(MediaType.APPLICATION_PDF_VALUE)
public Response testPdf() throws Exception {
File file = new File("C:\\Desktop\\test.pdf");
FileInputStream fileInputStream = new FileInputStream(file);
ResponseBuilder response = Response.ok((Object) fileInputStream);
response.type("application/pdf");
response.header("Content-Disposition", "filename=test.pdf");
return response.build();
}客户端
import React, { Component } from 'react';
import { Document, Page } from 'react-pdf';
import axios from 'axios';
class MyApp extends Component {
state = {
numPages: null,
pageNumber: 1,
pdfContent: null
}
componentDidMount(){
var that = this;
axios.get("url\Pdf").then((response) => {
that.setState({pdfContent:response.data});
}).catch((error) => {
console.warn(error);
});
}
onDocumentLoadSuccess = ({ numPages }) => {
this.setState({ numPages });
}
printHandler(){
window.print();
}
render() {
const { pageNumber, numPages } = this.state;
return (
<div>
<Document
file={this.state.pdfContent}
onLoadSuccess={this.onDocumentLoadSuccess}
>
<Page pageNumber={pageNumber} />
</Document>
<p>Page {pageNumber} of {numPages}</p>
<button onClick={() => this.setState(prevState => ({
pageNumber: prevState.pageNumber + 1 }))}>Next page</button>
<button onClick={() => this.setState(prevState => ({
pageNumber: prevState.pageNumber - 1 }))}>Prev Page</button>
<button onClick={this.printHandler}/>
</div>
);
}
}我只想得到一次PDF,并使用react-pdf显示PDF。另外,我想打印显示的PDF。
我尝试将response.data转换为base64,因为没有成功:(这将丢失pdf内容) Encode PDF to base64 in ReactJS
代码如下:
componentDidMount(){
var that = this;
axios.get("url\Pdf").then((response) => {
let reader = new FileReader();
var file = new Blob([response.data], { type: 'application/pdf' });
reader.onloadend = () => {
that.setState({
base64Pdf:reader.result
});
}
reader.readAsDataURL(file);
}).catch((error) => {
console.warn(error);
});
}有人能给我一些建议吗?或者有什么更好的方法来达到我的目标?
谢谢
发布于 2019-02-04 20:40:49
收到来自后端的错误消息时的更新
当请求失败时,我们从后端收到一个包含错误消息的JSON对象。问题是,当我们强制接收Blob格式的响应时: responseType:' Blob‘-无论请求是否失败,我们都会收到一个Blob对象。因此,我正在考虑更改axios: transformResponse提供的函数中的responseType,但不幸的是,我们不能访问'responseType‘对象,只能访问头部。在这里:https://github.com/axios/axios/pull/1155有一个关于相应地转换为responseType的未决问题,它仍然没有解决。
因此,我解决这个问题的方法是使用fetch而不是axios。下面是一个示例:
fetch('here.is.your/endpoint', {
method: 'POST', // specifying the method request
body: JSON.stringify(request), // specifying the body
headers: {
"Content-Type": "application/json"
}
}
).then((response) => {
if (response.ok) { // checks if the response is with status 200 (successful)
return response.blob().then(blob => {
const name = 'Report.pdf';
saveAs(blob, name);
});
} else {
return response.json().then((jsonError) => {
this.setState({
modalMessage: jsonError.message // access the error message returned from the back-end
});
});
}
}).catch(function (error) {
this.setState({
modalMessage: "Error in data type received." // general handler
});
});我希望这能帮到你!
发布于 2019-02-04 16:06:02
最近我得到了一个类似的pdf部分的用例,我的请求是Post,但你可以让它Get没有问题。那么,到底发生了什么:
1) -我正在使用axios向后端发出请求:
2) -端点请求是我发送的对象,但您不会有这样的对象,因为您可能只发送id,例如:axios.get(‘here.is.your//id’);
3) -我正在使用: file-saver来保存我收到的文件。
代码的其余部分应该是自解释的,我还添加了一些注释。
import {saveAs} from "file-saver";
...
axios.post('here.is.your/endpoint', qs.parse(request), {
headers: {
'Content-Type': 'application/json'
},
responseType: 'blob' // here I am forcing to receive data in a Blob Format
})
.then(response => {
if (response.data) {
//Create a Blob from the PDF Stream
const file = new Blob(
[response.data],
{type: 'application/pdf'});
const name = 'Report.pdf';
saveAs(file, name);
} else {
throw new Error("Error in data type received.");
}
})
.catch(error => {
this.setState({
modalMessage: "Here Add Custom Message"
});
});我仍然不能从后端获得错误消息,如果我在它上面得到了一些进展,我会发回短信-现在,我显示了一个自定义的消息。
我希望这对你有帮助!
祝你好运!
发布于 2019-03-21 18:02:05
我很高兴我能帮上忙!
我还有一个用于接收错误消息的更新
只有在收到文本消息而不是JSON的情况下才有效。
fetch('here.is.your/endpoint', {
method: 'POST', // specifying the method request
body: JSON.stringify(request), // specifying the body
headers: {
"Content-Type": "application/json"
}
}
).then((response) => {
if (response.ok) { // checks if the response is with status 200 (successful)
return response.blob().then(blob => {
const name = 'Report.pdf';
saveAs(blob, name);
});
} else {
return response.text().then(function (error) {
throw new Error(error); // we should throw an Error with the received error
}
);
}
}).catch(function (error) {
this.setState({
modalMessage: error.message // that way we access the error message
});
});我们使用response.text().then(),因为我们设法将它从Promise转换为文本。使用.then()非常重要,因为此时Promise已被解析,并且我们收到Promise值。然后,我们只是抛出一个错误,因为我们不能访问状态对象。
这就是你从回复中获取文本的方式。
https://stackoverflow.com/questions/53977498
复制相似问题