An easy way to display a PDF preview in the browser is to use an iframe
and set the src
to a link to the file. However, there is no way to set additional headers on requests from an iframe
so you can’t use this method if the request requires authentication or any other special headers.
To workaround this issue, fetch
the PDF in the browser then use URL.createObjectURL
on the response blob to generate a src
link for the iframe
. This will render the PDF preview and provides control over the request for things like setting authentication headers.
Here’s an example React component that fetches a PDF with custom headers and renders a preview without any other external dependencies. As long as the server sends a mimetype
of application/pdf
, the PDF will render properly.
export const PreviewPDF: FunctionComponent = (props) => {
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
useEffect(() => {
// Set up headers, cookies, or other settings needed here
const request: RequestInit = {
method: 'GET',
mode: 'cors',
headers: {
Authorization: `Bearer ${token}`,
},
};
fetch(props.url, request)
.then((resp) => resp.blob())
.then((blob) => {
const objectURL = URL.createObjectURL(blob);
setPreviewUrl(objectURL);
});
}, []);
if (!previewUrl) {
return <span>Loading...</span>;
}
return (
<iframe
src={`${previewUrl}#toolbar=0`}
title={url}
frameBorder="0"
/>
);
};
See also:
- This is naive implementation, fetching using React usually needs to handle more edge cases: gracefully fetch API data with React and TypeScript