PDF.js无法显示渲染的画布图像
P粉766520991
P粉766520991 2023-08-17 20:02:20
0
1
585
<p>我有一个显示PDF的React组件。当我使用这个组件时,我只需要传递PDF的URL。</p> <pre class="brush:php;toolbar:false;"><Previewer pdfUrl={pdfUrl}></Previewer></pre> <p>组件处理预览的细节。我遇到的问题是这个组件不显示PDF。我是否遗漏了什么?我应该怎么做来解决这个问题?下面是一个演示:</p> <p><br />></p> <pre class="snippet-code-js lang-js Prettyprint-override"><code>const { StrictMode, useRef } = React; const { createRoot } = ReactDOM; 常量样式= {}; const Previewer = (props) =>; { const canvasRef = useRef(null); React.useEffect(() => { if (props.pdfUrl) { initPdf(props.pdfUrl); } }, []); // 将 async/await 函数转换为使用 Promise,因为 Stack Snippet 的 Babel 版本不支持 async/await const initPdf = (pdfUrl) =>; { // 引用PDF.js的CDN版本而不是使用ES6导入 const pdfJS = pdfjsLib; pdfJS.GlobalWorkerOptions.workerSrc = "https://unpkg.com/pdfjs-dist@3.9.179/build/pdf.worker.js"; 返回 pdfJS.getDocument({ 网址: pdfUrl, cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.9.179/cmaps/', cMapPacked:真, }).promise.then((pdf) => { const 总页数 = pdf.numPages; for (让 i = 0; i < 总页数; i++) { renderPdfPage(pdf, pdfJS, i + 1); } }); } // 将 async/await 函数转换为使用 Promise,因为 Stack Snippet 的 Babel 版本不支持 async/await const renderPdfPage = (pdf, pdfJS, pageNum) =>; { return pdf.getPage(pageNum).then((page) => { const viewport = page.getViewport({ 规模:1.0 }); 让 divPage = window.document.createElement("div"); if(!canvasRef || !canvasRef.current) 返回; let canvas = divPage.appendChild(window.document.createElement("canvas")); const canvasContext = canvas.getContext('2d'); 画布.高度 = 视口.高度; 画布.宽度=视口.宽度; const renderContext = { canvasContext, 视口 }; const renderTask = page.render(renderContext); renderTask.promise.then(function () { const textContent = page.getTextContent(); 返回文本内容; }).then(函数(文本内容){ const textLayer = document.querySelector(`.${styles.textLayer}`); if (!textLayer) 返回; textLayer.style.left = canvas.offsetLeft + 'px'; textLayer.style.top = canvas.offsetTop + 'px'; textLayer.style.height = canvas.offsetHeight + 'px'; textLayer.style.width = canvas.offsetWidth + 'px'; textLayer.style.setProperty('--scale-factor', '1.0'); pdfJS.renderTextLayer({ 文本内容来源:文本内容, 容器:文本层, 视口: 视口, 文本分区:[] }); }); canvasRef.current.appendChild(divPage); }); } 返回 ( <div className={styles.cavasLayer}> > {/**
**/}
); } const pdfUrl =“https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf” const root = createRoot(document.getElementById("root")); root.render(<StrictMode><预览器 pdfUrl={pdfUrl} /></StrictMode>);</code></pre> <pre class="snippet-code-html lang-html Prettyprint-override"><code><脚本跨域 src="https://unpkg.com/react@18/umd/react.development.js “></脚本> <脚本跨域 src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <脚本跨域 src="https://unpkg.com/pdfjs-dist@3.9.179/build/pdf.js"></script> <div id="root"></div></code></pre> <p><br />></p>
P粉766520991
P粉766520991

全部回复(1)
P粉298305266

问题

renderPdfPage函数中,您创建了一个包含渲染PDF页面的canvas元素的div元素。然后将这些div元素附加到一个canvas元素上。然而,如果浏览器支持canvas元素,则不会渲染canvas元素的后代元素。根据canvas元素的规范

回退内容的定义如下:

解决方案

您需要将父级canvas更改为适当的元素。在下面的演示中,我使用了一个div

const { StrictMode, useRef } = React;
const { createRoot } = ReactDOM;

const styles = {};

const Previewer = (props) => {

    const pdfContainerRef = useRef(null);

    React.useEffect(() => {
        if (props.pdfUrl) {
            initPdf(props.pdfUrl);
        }
    }, []);
    
    // Converted async/await function to use promise because Stack Snippet's Babel version does not support async/await
    const initPdf = (pdfUrl) => {
        // Reference CDN version of PDF.js instead of using ES6 import
        const pdfJS = pdfjsLib;
        pdfJS.GlobalWorkerOptions.workerSrc = "https://unpkg.com/pdfjs-dist@3.9.179/build/pdf.worker.js";
        return pdfJS.getDocument({
            url: pdfUrl,
            cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.9.179/cmaps/',
            cMapPacked: true,
        }).promise.then((pdf) => {
            const totalPages = pdf.numPages;
            for (let i = 0; i < totalPages; i++) {
                renderPdfPage(pdf, pdfJS, i + 1);
            }
        });
    }
    
    // Converted async/await function to use promise because Stack Snippet's Babel version does not support async/await
    const renderPdfPage = (pdf, pdfJS, pageNum) => {
        return pdf.getPage(pageNum).then((page) => {
            const viewport = page.getViewport({
                scale: 1.0
            });
            let divPage = window.document.createElement("div");
            if(!pdfContainerRef || !pdfContainerRef.current) return;
            let canvas = divPage.appendChild(window.document.createElement("canvas"));
            const canvasContext = canvas.getContext('2d');
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            const renderContext = { canvasContext, viewport };
            const renderTask = page.render(renderContext);
            renderTask.promise.then(function () {
                const textContent = page.getTextContent();
                return textContent;
            }).then(function (textContent) {
                const textLayer = document.querySelector(`.${styles.textLayer}`);
                if (!textLayer) return;
                textLayer.style.left = canvas.offsetLeft + 'px';
                textLayer.style.top = canvas.offsetTop + 'px';
                textLayer.style.height = canvas.offsetHeight + 'px';
                textLayer.style.width = canvas.offsetWidth + 'px';
                textLayer.style.setProperty('--scale-factor', '1.0');
                pdfJS.renderTextLayer({
                    textContentSource: textContent,
                    container: textLayer,
                    viewport: viewport,
                    textDivs: []
                });
            });
            pdfContainerRef.current.appendChild(divPage);
        });
    }

    return (
        <div className={styles.cavasLayer}>
            <div id="pdf-container" ref={pdfContainerRef} />
            {/**<div className={styles.textLayer}></div>**/}
        </div>
    );
}

const pdfUrl = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf"
const root = createRoot(document.getElementById("root"));
root.render(<StrictMode><Previewer pdfUrl={pdfUrl} /></StrictMode>);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/pdfjs-dist@3.9.179/build/pdf.js"></script>
<div id="root"></div>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板