How to implement react-pdf with print functionEncode PDF to base64 in ReactJSRecommended way to embed PDF in HTML?Proper MIME media type for PDF filesConvert HTML + CSS to PDF with PHP?Merge / convert multiple PDF files into one PDFInserting a pdf file in latexLoop inside React JSXWhat is the difference between using constructor vs getInitialState in React / React Native?What do these three dots in React do?Programmatically navigate using react routerload pdf from redux store

Mimic lecturing on blackboard, facing audience

What fields between the rationals and the reals allow a good notion of 2D distance?

Make a Bowl of Alphabet Soup

Why can't the Brexit deadlock in the UK parliament be solved with a plurality vote?

Short story about a deaf man, who cuts people tongues

Can I cause damage to electrical appliances by unplugging them when they are turned on?

How many arrows is an archer expected to fire by the end of the Tyranny of Dragons pair of adventures?

It grows, but water kills it

Why should universal income be universal?

What to do when eye contact makes your coworker uncomfortable?

Why is the Sun approximated as a black body at ~ 5800 K?

Were Persian-Median kings illiterate?

The Digit Triangles

Why does AES have exactly 10 rounds for a 128-bit key, 12 for 192 bits and 14 for a 256-bit key size?

Does an advisor owe his/her student anything? Will an advisor keep a PhD student only out of pity?

Are Captain Marvel's powers affected by Thanos breaking the Tesseract and claiming the stone?

Microchip documentation does not label CAN buss pins on micro controller pinout diagram

What is the English pronunciation of "pain au chocolat"?

Quoting Keynes in a lecture

How can I write humor as character trait?

Has the laser at Magurele, Romania reached a tenth of the Sun's power?

Is this toilet slogan correct usage of the English language?

What kind of floor tile is this?

How much of a Devil Fruit must be consumed to gain the power?



How to implement react-pdf with print function


Encode PDF to base64 in ReactJSRecommended way to embed PDF in HTML?Proper MIME media type for PDF filesConvert HTML + CSS to PDF with PHP?Merge / convert multiple PDF files into one PDFInserting a pdf file in latexLoop inside React JSXWhat is the difference between using constructor vs getInitialState in React / React Native?What do these three dots in React do?Programmatically navigate using react routerload pdf from redux store













0















I would like to use react-pdf to display the PDF and develop a printing function for direct printing (like using window.print());



The REST server is developed using Jersey.



The PDF will generate from server and return to React client using Jersey with return type is application/pdf. React client will display the PDF using react-pdf.



I don't want to declare the URL path in "file" because this will retrieve the PDF from server again if the React state changed and triggered re-render. Also, I need to develop a print function to print the PDF displayed (Because the PDF content may change if retrieve the PDF again from server)



Below show my code:



Server:



@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();



Client



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;

axio.get("urlPdf).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>
);




I want to get the PDF only one time and display the PDF using react-pdf. Also, I want to print the displayed PDF.



I tried to convert the response.data to base64 followed this line because not success: (this will lose the pdf content)
Encode PDF to base64 in ReactJS



Code like:



 componentDidMount()
var that = this;

axio.get("urlPdf).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);
);



Anyone can give me some suggestion?
Or any better way to reach my goal?



Thanks










share|improve this question
























  • What have you tried so far?

    – Mikkel
    Dec 30 '18 at 12:36











  • @Mikkel I have tried FileReader to convent response to base64. However, still not success(maybe I am not familiar on this...) I have updated some codes to my post.

    – leonlai
    Dec 30 '18 at 12:45
















0















I would like to use react-pdf to display the PDF and develop a printing function for direct printing (like using window.print());



The REST server is developed using Jersey.



The PDF will generate from server and return to React client using Jersey with return type is application/pdf. React client will display the PDF using react-pdf.



I don't want to declare the URL path in "file" because this will retrieve the PDF from server again if the React state changed and triggered re-render. Also, I need to develop a print function to print the PDF displayed (Because the PDF content may change if retrieve the PDF again from server)



Below show my code:



Server:



@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();



Client



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;

axio.get("urlPdf).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>
);




I want to get the PDF only one time and display the PDF using react-pdf. Also, I want to print the displayed PDF.



I tried to convert the response.data to base64 followed this line because not success: (this will lose the pdf content)
Encode PDF to base64 in ReactJS



Code like:



 componentDidMount()
var that = this;

axio.get("urlPdf).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);
);



Anyone can give me some suggestion?
Or any better way to reach my goal?



Thanks










share|improve this question
























  • What have you tried so far?

    – Mikkel
    Dec 30 '18 at 12:36











  • @Mikkel I have tried FileReader to convent response to base64. However, still not success(maybe I am not familiar on this...) I have updated some codes to my post.

    – leonlai
    Dec 30 '18 at 12:45














0












0








0








I would like to use react-pdf to display the PDF and develop a printing function for direct printing (like using window.print());



The REST server is developed using Jersey.



The PDF will generate from server and return to React client using Jersey with return type is application/pdf. React client will display the PDF using react-pdf.



I don't want to declare the URL path in "file" because this will retrieve the PDF from server again if the React state changed and triggered re-render. Also, I need to develop a print function to print the PDF displayed (Because the PDF content may change if retrieve the PDF again from server)



Below show my code:



Server:



@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();



Client



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;

axio.get("urlPdf).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>
);




I want to get the PDF only one time and display the PDF using react-pdf. Also, I want to print the displayed PDF.



I tried to convert the response.data to base64 followed this line because not success: (this will lose the pdf content)
Encode PDF to base64 in ReactJS



Code like:



 componentDidMount()
var that = this;

axio.get("urlPdf).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);
);



Anyone can give me some suggestion?
Or any better way to reach my goal?



Thanks










share|improve this question
















I would like to use react-pdf to display the PDF and develop a printing function for direct printing (like using window.print());



The REST server is developed using Jersey.



The PDF will generate from server and return to React client using Jersey with return type is application/pdf. React client will display the PDF using react-pdf.



I don't want to declare the URL path in "file" because this will retrieve the PDF from server again if the React state changed and triggered re-render. Also, I need to develop a print function to print the PDF displayed (Because the PDF content may change if retrieve the PDF again from server)



Below show my code:



Server:



@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();



Client



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;

axio.get("urlPdf).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>
);




I want to get the PDF only one time and display the PDF using react-pdf. Also, I want to print the displayed PDF.



I tried to convert the response.data to base64 followed this line because not success: (this will lose the pdf content)
Encode PDF to base64 in ReactJS



Code like:



 componentDidMount()
var that = this;

axio.get("urlPdf).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);
);



Anyone can give me some suggestion?
Or any better way to reach my goal?



Thanks







reactjs pdf jersey state react-pdf






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 30 '18 at 13:32







leonlai

















asked Dec 30 '18 at 12:15









leonlaileonlai

528




528












  • What have you tried so far?

    – Mikkel
    Dec 30 '18 at 12:36











  • @Mikkel I have tried FileReader to convent response to base64. However, still not success(maybe I am not familiar on this...) I have updated some codes to my post.

    – leonlai
    Dec 30 '18 at 12:45


















  • What have you tried so far?

    – Mikkel
    Dec 30 '18 at 12:36











  • @Mikkel I have tried FileReader to convent response to base64. However, still not success(maybe I am not familiar on this...) I have updated some codes to my post.

    – leonlai
    Dec 30 '18 at 12:45

















What have you tried so far?

– Mikkel
Dec 30 '18 at 12:36





What have you tried so far?

– Mikkel
Dec 30 '18 at 12:36













@Mikkel I have tried FileReader to convent response to base64. However, still not success(maybe I am not familiar on this...) I have updated some codes to my post.

– leonlai
Dec 30 '18 at 12:45






@Mikkel I have tried FileReader to convent response to base64. However, still not success(maybe I am not familiar on this...) I have updated some codes to my post.

– leonlai
Dec 30 '18 at 12:45













3 Answers
3






active

oldest

votes


















1














Update on receiving the error message from the back-end:



When a request fails, we receive a JSON object from the back-end which contains the error message. The problem is that when we are forcing to receive the response in Blob format: responseType: 'blob' - no matter if the request fails or not, we receive a Blob Object. So, I was thinking about changing the responseType in the function provided from axios: transformResponse, but unfortunately, we do not have access to 'responseType' object, only to the headers. Here: https://github.com/axios/axios/pull/1155 there is an open issue about converting accordingly to responseType, it is still not resolved.



So, my way of resolving this problem is using fetch instead of axios.
Here is an example:



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
);
);


I hope this helps!






share|improve this answer























  • Thanks for your help! This seems work for me!

    – leonlai
    Mar 7 at 9:25


















1














Recently I got a similar use case with the pdf part, my request is Post, but you can make it Get with no problem. So, what is happening:



1) - I am using axios for making a request to the back-end:



2) - request is the object that I am sending, but you will not have such, since you will probably send only id, for example: axios.get('here.is.your/endpoint/id');



3) - I am using: file-saver for saving the file I receive.



The rest of the code should be self-explaining and I also added some comments.



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"
);
);


I cannot get the error message from the back-end still, I will text back if I get some progress on it - for now, I show a custom message.



I hope that helps!



Wish you luck!






share|improve this answer






























    0














    I am glad I helped!



    I have one more UPDATE FOR RECEIVING THE ERROR MESSAGE



    THIS ONE IS VALID ONLY IF YOU RECEIVE TEXT MESSAGE NOT 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
    );
    );


    We are using response.text().then() because of that way we manage to convert it from Promise to text. And it is important to use .then() because the Promise at that moment is resolved and we receive the Promise value. Then we simply throw an Error because we do not have access to the state object.



    That is how you get a text from a response.






    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53977498%2fhow-to-implement-react-pdf-with-print-function%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Update on receiving the error message from the back-end:



      When a request fails, we receive a JSON object from the back-end which contains the error message. The problem is that when we are forcing to receive the response in Blob format: responseType: 'blob' - no matter if the request fails or not, we receive a Blob Object. So, I was thinking about changing the responseType in the function provided from axios: transformResponse, but unfortunately, we do not have access to 'responseType' object, only to the headers. Here: https://github.com/axios/axios/pull/1155 there is an open issue about converting accordingly to responseType, it is still not resolved.



      So, my way of resolving this problem is using fetch instead of axios.
      Here is an example:



      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
      );
      );


      I hope this helps!






      share|improve this answer























      • Thanks for your help! This seems work for me!

        – leonlai
        Mar 7 at 9:25















      1














      Update on receiving the error message from the back-end:



      When a request fails, we receive a JSON object from the back-end which contains the error message. The problem is that when we are forcing to receive the response in Blob format: responseType: 'blob' - no matter if the request fails or not, we receive a Blob Object. So, I was thinking about changing the responseType in the function provided from axios: transformResponse, but unfortunately, we do not have access to 'responseType' object, only to the headers. Here: https://github.com/axios/axios/pull/1155 there is an open issue about converting accordingly to responseType, it is still not resolved.



      So, my way of resolving this problem is using fetch instead of axios.
      Here is an example:



      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
      );
      );


      I hope this helps!






      share|improve this answer























      • Thanks for your help! This seems work for me!

        – leonlai
        Mar 7 at 9:25













      1












      1








      1







      Update on receiving the error message from the back-end:



      When a request fails, we receive a JSON object from the back-end which contains the error message. The problem is that when we are forcing to receive the response in Blob format: responseType: 'blob' - no matter if the request fails or not, we receive a Blob Object. So, I was thinking about changing the responseType in the function provided from axios: transformResponse, but unfortunately, we do not have access to 'responseType' object, only to the headers. Here: https://github.com/axios/axios/pull/1155 there is an open issue about converting accordingly to responseType, it is still not resolved.



      So, my way of resolving this problem is using fetch instead of axios.
      Here is an example:



      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
      );
      );


      I hope this helps!






      share|improve this answer













      Update on receiving the error message from the back-end:



      When a request fails, we receive a JSON object from the back-end which contains the error message. The problem is that when we are forcing to receive the response in Blob format: responseType: 'blob' - no matter if the request fails or not, we receive a Blob Object. So, I was thinking about changing the responseType in the function provided from axios: transformResponse, but unfortunately, we do not have access to 'responseType' object, only to the headers. Here: https://github.com/axios/axios/pull/1155 there is an open issue about converting accordingly to responseType, it is still not resolved.



      So, my way of resolving this problem is using fetch instead of axios.
      Here is an example:



      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
      );
      );


      I hope this helps!







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Feb 4 at 12:40









      RenetaReneta

      364




      364












      • Thanks for your help! This seems work for me!

        – leonlai
        Mar 7 at 9:25

















      • Thanks for your help! This seems work for me!

        – leonlai
        Mar 7 at 9:25
















      Thanks for your help! This seems work for me!

      – leonlai
      Mar 7 at 9:25





      Thanks for your help! This seems work for me!

      – leonlai
      Mar 7 at 9:25













      1














      Recently I got a similar use case with the pdf part, my request is Post, but you can make it Get with no problem. So, what is happening:



      1) - I am using axios for making a request to the back-end:



      2) - request is the object that I am sending, but you will not have such, since you will probably send only id, for example: axios.get('here.is.your/endpoint/id');



      3) - I am using: file-saver for saving the file I receive.



      The rest of the code should be self-explaining and I also added some comments.



      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"
      );
      );


      I cannot get the error message from the back-end still, I will text back if I get some progress on it - for now, I show a custom message.



      I hope that helps!



      Wish you luck!






      share|improve this answer



























        1














        Recently I got a similar use case with the pdf part, my request is Post, but you can make it Get with no problem. So, what is happening:



        1) - I am using axios for making a request to the back-end:



        2) - request is the object that I am sending, but you will not have such, since you will probably send only id, for example: axios.get('here.is.your/endpoint/id');



        3) - I am using: file-saver for saving the file I receive.



        The rest of the code should be self-explaining and I also added some comments.



        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"
        );
        );


        I cannot get the error message from the back-end still, I will text back if I get some progress on it - for now, I show a custom message.



        I hope that helps!



        Wish you luck!






        share|improve this answer

























          1












          1








          1







          Recently I got a similar use case with the pdf part, my request is Post, but you can make it Get with no problem. So, what is happening:



          1) - I am using axios for making a request to the back-end:



          2) - request is the object that I am sending, but you will not have such, since you will probably send only id, for example: axios.get('here.is.your/endpoint/id');



          3) - I am using: file-saver for saving the file I receive.



          The rest of the code should be self-explaining and I also added some comments.



          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"
          );
          );


          I cannot get the error message from the back-end still, I will text back if I get some progress on it - for now, I show a custom message.



          I hope that helps!



          Wish you luck!






          share|improve this answer













          Recently I got a similar use case with the pdf part, my request is Post, but you can make it Get with no problem. So, what is happening:



          1) - I am using axios for making a request to the back-end:



          2) - request is the object that I am sending, but you will not have such, since you will probably send only id, for example: axios.get('here.is.your/endpoint/id');



          3) - I am using: file-saver for saving the file I receive.



          The rest of the code should be self-explaining and I also added some comments.



          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"
          );
          );


          I cannot get the error message from the back-end still, I will text back if I get some progress on it - for now, I show a custom message.



          I hope that helps!



          Wish you luck!







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Feb 4 at 8:06









          RenetaReneta

          364




          364





















              0














              I am glad I helped!



              I have one more UPDATE FOR RECEIVING THE ERROR MESSAGE



              THIS ONE IS VALID ONLY IF YOU RECEIVE TEXT MESSAGE NOT 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
              );
              );


              We are using response.text().then() because of that way we manage to convert it from Promise to text. And it is important to use .then() because the Promise at that moment is resolved and we receive the Promise value. Then we simply throw an Error because we do not have access to the state object.



              That is how you get a text from a response.






              share|improve this answer





























                0














                I am glad I helped!



                I have one more UPDATE FOR RECEIVING THE ERROR MESSAGE



                THIS ONE IS VALID ONLY IF YOU RECEIVE TEXT MESSAGE NOT 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
                );
                );


                We are using response.text().then() because of that way we manage to convert it from Promise to text. And it is important to use .then() because the Promise at that moment is resolved and we receive the Promise value. Then we simply throw an Error because we do not have access to the state object.



                That is how you get a text from a response.






                share|improve this answer



























                  0












                  0








                  0







                  I am glad I helped!



                  I have one more UPDATE FOR RECEIVING THE ERROR MESSAGE



                  THIS ONE IS VALID ONLY IF YOU RECEIVE TEXT MESSAGE NOT 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
                  );
                  );


                  We are using response.text().then() because of that way we manage to convert it from Promise to text. And it is important to use .then() because the Promise at that moment is resolved and we receive the Promise value. Then we simply throw an Error because we do not have access to the state object.



                  That is how you get a text from a response.






                  share|improve this answer















                  I am glad I helped!



                  I have one more UPDATE FOR RECEIVING THE ERROR MESSAGE



                  THIS ONE IS VALID ONLY IF YOU RECEIVE TEXT MESSAGE NOT 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
                  );
                  );


                  We are using response.text().then() because of that way we manage to convert it from Promise to text. And it is important to use .then() because the Promise at that moment is resolved and we receive the Promise value. Then we simply throw an Error because we do not have access to the state object.



                  That is how you get a text from a response.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 15 hours ago

























                  answered 17 hours ago









                  RenetaReneta

                  364




                  364



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53977498%2fhow-to-implement-react-pdf-with-print-function%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현