I am new to full stack development and am facing this problem while retrieving and displaying the contents of a pdf. I am using reactjs and express.
Problem statement: I want to retrieve pdf documents from the backend and send it to the frontend. When displaying it I want to create a scroll list with the preview of page 1 of each document. For now I have made my problem statement simpler and am sending a pdf from the 'public' folder of my express app and retrieving it in my reactjs app.
Express code: express code
app.get("/pdf-templates", (req, res) => {
let pdf = fs.createReadStream("./public/templates/final_look.pdf");
pdf.pipe(res);
});
Frontend code: reactjs code
function GetCertificateTemplates() {
const [pdfUrl, setPdfUrl] = useState("");
const getTemplateHandler = async () => {
axios("http://localhost:3030/pdf-templates", {
method: "GET",
responseType: "blob",
}).then((res) => {
const file = new Blob([res.data], { type: "application/pdf" });
const fileURL = URL.createObjectURL(file);
setPdfUrl(fileURL);
// console.log(res.data);
// window.open(
// fileURL,
// "pdfwindow",
// "left=100,top=100,width=300,height=300"
// );
});
};
return (
<div className="Get-Certificate-Template">
<button onClick={getTemplateHandler}>Get Templates</button>
{/* <iframe src={pdfUrl} />; */}
<embed src={pdfUrl} type="application/pdf" />;
</div>
);
}
In the commented lines, the 'window' command works and the pdf is rendered fine. But the same url is not working for iframe or embeded in chrome. iframe code is working for edge though. I am not using 'window' as my final goal is to display multiple pdf previews in the same window.
The questions are the follows:
Thank you for your time in advance.