Skip to content

Instantly share code, notes, and snippets.

@deepakshrma
Last active October 25, 2021 15:41
Show Gist options
  • Save deepakshrma/173ecc3a639ea70addb1bb968aee5ce6 to your computer and use it in GitHub Desktop.
Save deepakshrma/173ecc3a639ea70addb1bb968aee5ce6 to your computer and use it in GitHub Desktop.
Download PDF/View/Display using react
import React, { useEffect, useState } from "react";
import { Document, Page } from "react-pdf/dist/esm/entry.webpack";
import "./App.css";
let fnGetFileNameFromContentDispostionHeader = function (header: string = "") {
let contentDispostion = header.split(";");
const fileNameToken = `filename*=UTF-8''`;
let fileName = "downloaded.pdf";
for (let thisValue of contentDispostion) {
if (thisValue.trim().indexOf(fileNameToken) === 0) {
fileName = decodeURIComponent(
thisValue.trim().replace(fileNameToken, "")
);
break;
}
}
return fileName;
};
async function getPdf() {
const data = await fetch(`https://decipher.dev/Resume-Deepak-Vishwakarma.pdf`)
.then(async (res) => ({
filename: fnGetFileNameFromContentDispostionHeader(
res.headers.get("content-disposition") ?? ""
),
blob: await res.blob(),
}))
.then((resObj) => {
const newBlob = new Blob([resObj.blob], { type: "application/pdf" });
return newBlob;
});
return data;
}
async function getPdfAxios() {
const data = await axios
.get(`https://decipher.dev/Resume-Deepak-Vishwakarma.pdf`, {
responseType: "blob",
})
.then((res: any) => ({
blob: res.data,
}))
.then((resObj) => {
return new Blob([resObj.blob], { type: "application/pdf" });
});
return data;
}
function App() {
const [numPages, setNumPages] = useState(null);
const [pageNumber, setPageNumber] = useState(1);
const [content, setContent] = useState<Blob>();
function onDocumentLoadSuccess({ numPages }: any) {
setNumPages(numPages);
}
useEffect(() => {
getPdf().then(data => setContent(data));
}, []);
return (
<div style={{ display: "flex" }}>
<div style={{ width: "50%" }}>
<Document
file={content}
onLoadSuccess={onDocumentLoadSuccess}
>
<Page pageNumber={pageNumber} />
</Document>
<p>
Page {pageNumber} of {numPages}
</p>
</div>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment