如何在 Javascript 中将 PDF 缩放到画布宽度和高度?

问题描述 投票:0回答:0

我有一个 PDF 文档列表,我正在尝试呈现类似于 Google Docs UI 的预览。

{documents.map((doc) => {
                                    return (
                                        <div key={doc.id} className="border-solid border-2 border-sky-500" >
                                            <ImagePreview pdf={doc} containerHeight={130} containerWidth={110}/>
                                        </div>
                                    );
                                })}

ImagePreview
组件如下所示:

function ImagePreview({ pdf, containerWidth, containerHeight }) {
    const canvasRef = useRef(null);

    useEffect(() => {
        async function init() {
            try {
                const canvas = canvasRef.current;
                const ctx = canvas.getContext("2d");
                const uid = await getUserId();
                const publicUrl = await supabase.storage.from("pdf-documents").getPublicUrl(uid + "/" + pdf.name).data.publicUrl;

                // Load the PDF file
                pdfjsLib
                    .getDocument(publicUrl)
                    .promise.then((pdf) => {
                        // Get the specified page
                        return pdf.getPage(1);
                    })
                    .then((page) => {
                        // Set the canvas dimensions to match the PDF page dimensions
                        const viewport = page.getViewport({ scale: 1 });
                        const canvasWidth = containerWidth;
                        const canvasHeight = containerHeight;
                        const scaleX = canvasWidth / viewport.width;
                        const scaleY = canvasHeight / viewport.height;
                        const scale = Math.min(scaleX, scaleY);
                        const newViewport = page.getViewport({ scale });
                        console.log(newViewport);

                        // Set the canvas dimensions to match the fixed size
                        canvas.width = canvasWidth;
                        canvas.height = canvasHeight;

                        // Render the PDF page as an HTML5 canvas
                        const renderContext = {
                            canvasContext: ctx,
                            viewport: page.getViewport({ scale }),
                        };
                        page.render(renderContext);
                    });
            } catch (error) {
                console.log(error);
            }
        }

        init();
    }, []);

    return (
        <div>
            <canvas ref={canvasRef} />
        </div>
    );
}

我正在使用

pdfjs-dist
库将 PDF 的第一页绘制到画布上,并根据画布的高度和宽度缩放 PDF 的高度和宽度。但是,在呈现
ImagePreview
组件时,我在父 div 中添加了一个边框,我发现 PDF 没有使用画布的大小。

如何使 PDF 放大或缩小到画布的完整尺寸?

javascript reactjs pdf canvas pdf.js
© www.soinside.com 2019 - 2024. All rights reserved.