Skip to content

Instantly share code, notes, and snippets.

@emorling
Created March 29, 2021 12:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save emorling/227644effd10eea1ac2366426ab60543 to your computer and use it in GitHub Desktop.
Save emorling/227644effd10eea1ac2366426ab60543 to your computer and use it in GitHub Desktop.
Scaling react-pdf to fit
import React, {
useCallback,
useState,
useMemo,
} from 'react';
import { pdfjs, Document, Page } from 'react-pdf';
import Measure from 'react-measure';
import throttle from 'lodash/throttle';
import {
Viewer,
DocumentWrapper,
} from './styles';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
function Present() {
const [wrapperWidth, setWrapperWidth] = useState(0);
const [wrapperHeight, setWrapperHeight] = useState(0);
const [pageWidth, setPageWidth] = useState(0);
const [pageHeight, setPageHeight] = useState(0);
const fitHorizontal = useMemo(() => {
const wRatio = pageWidth / wrapperWidth;
const hRatio = pageHeight / wrapperHeight;
if (wRatio < hRatio) {
return false;
}
return true;
}, [pageHeight, pageWidth, wrapperHeight, wrapperWidth]);
const setWrapperDimensions = useCallback(throttle((w, h) => {
setWrapperWidth(w);
setWrapperHeight(h);
}, 500), []);
return (
<Viewer>
<Measure
bounds
onResize={(contentRect) => setWrapperDimensions(contentRect.bounds.width, contentRect.bounds.height)}
>
{({ measureRef }) => (
<DocumentWrapper ref={measureRef}>
<Document
file="URL TO FILE HERE"
>
<Page
key="page"
onLoadSuccess={(page) => {
setPageWidth(page.width);
setPageHeight(page.height);
}}
width={fitHorizontal ? wrapperWidth : null}
height={!fitHorizontal ? wrapperHeight : null}
/>
</Document>
</DocumentWrapper>
)}
</Measure>
</Viewer>
);
}
export default Present;
import styled from 'styled-components';
import { Document, Page } from 'react-pdf';
export const Viewer = styled.div`
display: flex;
flex-direction: column;
height: 100%;
`;
export const DocumentWrapper = styled.div`
position: relative;
flex: 1;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
width: 100%;
overflow: auto;
background-color: ${({ theme }) => theme.colors.N80};
border: 1px solid ${({ theme }) => theme.colors.N80};
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment