import { useEffect, useState } from 'react'; import { Viewer, DocumentGate, pageRefsEqual } from '@embedpdf/react/runtime'; import type { OpenInput, PageContextValue, PageRef } from '@embedpdf/react/runtime'; import { Stage, stagePlugin } from '@embedpdf/react/stage'; import { RenderLayer, renderPlugin } from '@embedpdf/react/render'; import { interactionPlugin, useInteraction } from '@embedpdf/react/interaction'; import { localEngine } from '@embedpdf/engine'; import './ruler.css'; const engine = localEngine(); const plugins = [stagePlugin(), renderPlugin(), interactionPlugin()]; const welcome = async (): Promise => { const response = await fetch('https://www.embedpdf.com/pdfs/welcome.pdf'); return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) }; }; interface Point { readonly x: number; readonly y: number; } interface Measurement { readonly page: PageRef; readonly from: Point; readonly to: Point; } // Page coordinates are points, 72 to the inch. const lengthOf = ({ from, to }: Measurement) => { const inches = Math.hypot(to.x - from.x, to.y - from.y) / 72; return `${inches.toFixed(2)} in · ${(inches * 2.54).toFixed(1)} cm`; }; // The measured line on its page, placed in the page's pixels. function RulerLayer({ page, measurement, }: { page: PageContextValue; measurement: Measurement | null; }) { if (!measurement || !pageRefsEqual(measurement.page, page.ref)) return null; const from = page.transform.toPixels(measurement.from); const to = page.transform.toPixels(measurement.to); return ( <> {lengthOf(measurement)} ); } function Ruler() { const interaction = useInteraction(); const [measurement, setMeasurement] = useState(null); const [pointer, setPointer] = useState(null); // A tool you drag with: the press starts a line, the moves stretch it, the release ends it. useEffect(() => { const remove = interaction.registerTool({ id: 'ruler', cursor: 'crosshair', touch: 'draw', // one finger measures, two fingers scroll and zoom onPointerDown: ({ page, point }) => { setMeasurement({ page, from: point, to: point }); return true; }, onPointerMove: ({ point }) => { setMeasurement((current) => current && { ...current, to: point }); }, onPointerUp: ({ point }) => { setMeasurement((current) => current && { ...current, to: point }); }, onHover: ({ point }) => setPointer(point), }); interaction.activateTool('ruler'); return remove; }, [interaction]); return ( <>
{measurement ? lengthOf(measurement) : 'Drag on a page to measure'} {pointer ? `x ${Math.round(pointer.x)} · y ${Math.round(pointer.y)} pt` : ''}
{(page) => ( <> )} ); } export default function App() { return ( Loading…

}>
); }