How to show pdf file in react.js - reactjs

i just try to sample application for ios, android and web using react-native-web. Here i have to download a pdf file from server and while click the showpdf button the downloaded file need to open in both android application as well as windows browser also. for browser download i have used the following code
fetch('http://www.pdf995.com/samples/pdf.pdf',{
method: 'GET',
mode: 'no-cors',
responseType: 'blob', // important
headers: {
'Content-Type': 'application/json',
},})
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', item.pdfFileName);
document.body.appendChild(link);
link.click();
this.setState({
pdf_url:url
});
after download i need to open this pdf file. please help if anyone know this. thanks.

You could use <iframe> to preview the PDF directly in your page, setting the src attribute to pdf_url. window.open(pdf_url) is also an option as mentioned above, but it'll require the user to have adblocker/pop-up blocker turned off.
In your render():
{pdf_url && <iframe src={pdf_url} />}
See MDN for multiple ways to display files

I suggest you to look at https://www.npmjs.com/package/react-pdf library, using which you can simply display pdfs just like images
Here is online demo http://projects.wojtekmaj.pl/react-pdf/

Related

Images not found for Dropbox login window

I have been implementing the Dropbox API and Dropbox Chooser into a React application. When I call 'oauth2/authorize' for the login page, I receive the correct HTML, but when I load it I receive 404 errors for all of the image files that would help style it. I attached a screenshot to show what the error looks like. Any idea why it's happening or how to fix it?
The call :
axios({
method: 'get',
url: 'https://www.dropbox.com/oauth2/authorize?client_id=' + APP_KEY + '&response_type=code',
headers: {
'Content-Type' : 'application/json' ,
'Authorization' : AUTH
}
}).then(function (res) {
let pretty = stringifyObject(res.data, {
singleQuotes: false
});
response.send(pretty);
})
.catch(function (error) {
response.send(error.response.data);
});
The fetch :
fetch(URL + '/api/login', {method: "GET"})
.then((res)=>{ return res.text() })
.then((text)=>{
let html = React.createElement('div',{dangerouslySetInnerHTML: {__html:text}});
})
You're downloading the data for Dropbox's /oauth2/authorize, but https://www.dropbox.com/oauth2/authorize is actually a web page, not an API call, so you should not be using your HTTPS client like this to download the HTML data.
You should instead be directing the user to that https://www.dropbox.com/oauth2/authorize... page in their browser. For example, you can construct the https://www.dropbox.com/oauth2/authorize... URL and then put it in an <a> HTML link for the user to click on, or redirect them there via JavaScript, depending on what makes sense for your use case.

How to proxy my API URL to some other proxy

I am on http://localhost:8081/post URL and my API is hosted at some "http://dummy.restapiexample.com/api/v1".
I want it to appear in the network tab like "/custom/create". But the network tab is showing "http://localhost:8081/custom/create" but it should not append localhost URL in that. It should take the hosted API URL.
I am using CRA boilerplate. And I do not want to use express for the same.
I tried the following code
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(proxy("/custom",
{target: "http://dummy.restapiexample.com/api/v1"}));
};
and in for API calls, I am using below format:
fetch('/custom/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(authData),
})
I am not getting how to hide the whole Hosted API URL and show proxy URL
in the network tab.
Please give your valuable suggestion over this.
I am a novice in proxy-middleware. Thank you in advance :)
In your package.json include the url of your API as a proxy.
"proxy": "http://dummy.restapiexample.com",

download file in react

i have an Restful API i created using Laravel, this API like this:
http://127.0.0.1:8000/api/file/pdf/{id}
and this is my code for download:
public function pdfDownload($id){
$pdf = Cv::findOrfail($id);
return Storage::download('public/pdf/'.$pdf->pdf);
}
it is worked in postman, and also in browser, it is directly download the file,
but with react.js, it is not work, this my code in react:
pdfDownload = (id) => {
fetch(' http://127.0.0.1:8000/api/file/pdf/' + id, {
method: 'get',
headers: {
Accept: 'application/octet-stream',
'Content-Type': 'application/octet-stream'
}
}).then((res) => res.json());
};
and i call this function in button like this :
<Button color="primary" onClick={() => this.pdfDownload(data.id)}>
Download
</Button>
the id is corrected, i am ensure from this, my question is how can i download file when click this button.. Thans...
XHR calls can not trigger file download, the way browser handles it. You will have to mimic a file download using javascript code yourself, using something like below:
Reference
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
Or use File Saver package, if you don't mind an extra dependency.
FileSaver Npm

How to successfully embed blob PDF response in IE11/Edge

I am not able to embed a blob url as an PDF in IE 11/Edge. There is a CORS issue and IE gives an 'Access Denied'. From my research on SO, I have realized that this is due to IE's inherent security restrictions. My question is is there any other way of taking the blob URL data response from the REST service and displaying it embedded in the browser. I want to avoid using any third party libraries.
The service returns as below:
function getTest(id) {
miEService.get(id)
.then(function (response) {
var fileUrl = URL.createObjectURL(response.data);
$scope.pdfData = $sce.trustAsResourceUrl(fileUrl);
});
get: function (id) {
var config = {
headers: {
accept: 'application/pdf'
}
, responseType: 'blob'
}
return $http.get(miEnv.services.eApi + '?$filter=id eq' +
' ' + id, config);
Finally inside the html the display is as below -
<object id="pdf" data={{$ctrl.pdfData}} type="application/pdf" width="100%" height="100%" alt="pdf" class="view-pdf_document">
If the rest service returns the binary data of the pdf, you could just embedd the url in your page as an Iframe rather than the binary content itself. It should render the pdf. If not, I've had success in the past just having the pdf be a link and when you click the link it opens the request to the rest service in a new tab. If the issue is that you don't want the rest service to show up in the url on the page, then you might have to proxy the request through your own server.

Is it possible to force file downloads in browsers with angularjs?

I'm have developed a SPA (Single Page Application) with AngularJS and I'm trying to force a pdf file download with AngularJS.
By the moment I only can open de pdf file in a new tab with the next code.
HTML view:
<a ng-click="download()"></a>
Controller:
$scope.download = function(){
$window.open('/cv.pdf', '_blank');
};
Is there any way to force the pdf download in the browser?
You can see this example in the following URLs:
www.juanmanuellopezpazos.es/curriculum (HTML View)
www.juanmanuellopezpazos.es/Curriculum.pdf (pdf file whose download I want to force)
I am done this in MVC.NET WITH ANGULAR JS.
It works fine with firefox also(Tested in version:50.0)
Write down following code in your function:
//in mvc view
<a ng-href="#" title="{{attachments.FileName}} " ng-click="download(attachment.FilePath,attachment.FileName)">{{attachments.FileName}} </a>
// in .js file
$scope.download = function download(pathoffile, filename) {
$http.get(pathoffile, {
responseType: "arraybuffer"
}).then(function (response) {
$scope.filedata = response.data;
var headers = response.headers();
headers['Content-Disposition'] = "attachment";
var blob = new Blob([response.data], { type: "octet/stream" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
This previous question should provide quite a lot of information on this.
(HTML) Download a PDF file instead of opening them in browser when clicked
In you're case I'd recommend just direct linking to the PDF and using the download attribute (http://www.w3schools.com/tags/att_a_download.asp).
Finally I got the solution with #kierandotco answer. The best way is something like this:
The download HTML5 attribute and target attribute with _self value do the trick.

Resources