React-pdf: Fetch Base64string data from Asp.Net Core Web Api

Created on 2 Sep 2018  路  5Comments  路  Source: wojtekmaj/react-pdf

Before you start - checklist

  • [x] I have read documentation in README
  • [x] I have checked sample and test suites to see real life basic implementation
  • [x] I have checked if this question is not already asked

I need to fetch data from Web Api (Asp.Net Core 2.1) and Pdf Viewer.

I want to pass data not from url but from a string Base64String converted with asp net method (ToBase64String)

This is my try:

         import React, { Component } from 'react';
                     import { Document } from 'react-pdf/dist/entry.webpack';


       class Home extends Component {
         constructor(props) {
         super(props);

  this.state = {
    data:""
  }
   }

   componentDidMount() {
       fetch('http://localhost:5000/api/document')
    .then(data => this.setState({ data }));
     }  
       render() {
      return (
      <div>
        <Document file={this.state.data}>
        </Document>
      </div>

      );
    }
  }

export default Home

I can not understand what I'm forgetting?

  • Browser Microsoft Edge
  • React-PDF version 3.0.4
  • React version latest
  • Webpack version Latest
question

All 5 comments

If you want to use Base64 (which I cannot find the reason to; this would add 33% network usage and no benefits) you need to remember it should be a data URL, so it needs to start from data:application/pdf;base64, followed by base64 string. A good way to test if you got it right is to copy the whole string and paste into your browser address bar - if it's valid, a PDF should open.

I stored a varbinary in database table, then i retrive and send it after Base64 conversion. I don't have a pdf saved on filesystem.
Don't you think is this the best way to achive the result?

The best would be to send a binary file to the user. base64 makes everything bigger in 4/3 ratio.

is there a way to render the pdf sending the coded data in an http request body from a json?

No, if that's your requirement then base64 is indeed the only option.

Was this page helpful?
0 / 5 - 0 ratings