React - How to Open Pdf File as a Href Target Blank

React - How to open PDF file as a href target blank

Place the pdf into a folder in /src. Import it like a component. Set href parameter as the imported pdf and the target = "_blank".

import React, { Component } from 'react';
import Pdf from '../Documents/Document.pdf';

class Download extends Component {

render() {

return (
<div className = "App">
<a href = {Pdf} target = "_blank">Download Pdf</a>
</div>
);

}
}

export default Download;

Trying to view data as pdf , pdf is blank

Issue was the api call for the frontend, backend works fine;
Reponse type needed to be blob

const result = await axios({
url: `${localUrl + url}`, //your url
method: 'GET',
responseType: 'blob', // important
})
.then(({ data }) => data);
return result;

How to open a pdf in new tab in reactjs?

You can use something like this:

<a href='/api/v1/print/example.pdf' target='_blank' rel='noopener noreferrer'>

Open PDF in React with correct title

I think we can't change the baseURL of a window without reloading to a new URL. But we can change the path using history.pushState. Here is a solution which is working in Mozilla and Chrome.

import React from "react";
import Resume from "./Sample.pdf";

const Landing = () => {
const openPDF = () => {
const pdfWindow = window.open("test");
const title = "My PDF";
const URI = "test/test";
const html = `
<html>
<head>
<title>${title}</title>
</head>
<body style="margin:0">
<embed width="100%" height="100%" src=${Resume} type="application/pdf">
</body>
</html>
`;

pdfWindow.document.write(html);
pdfWindow.document.close();
pdfWindow.history.pushState(null, null, URI);
};

return (
<div className="MainLandingContainer">
<div className="ResumeContainer">
<button variant="primary" target="_blank" onClick={openPDF}>
Resume
</button>
</div>
</div>
);
};

export default Landing;

You can find the codesandbox here

Open link (.pdf file) in new tab after running function and without changing route

Why not just use Window.open()? Once you have the URL of the file, you can just open it in a new window without pushing any state or otherwise having to do anything React-specific.



Related Topics



Leave a reply



Submit