• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

react pdf转图片展示

互联网 diligentman 1周前 (02-20) 5次浏览

最近有一个需求,需要在钉钉微应用PC端用上展示pdf,无奈钉钉的的webview不支持embed标签,故为了兼容只能使用图片来展示pdf文件
项目是用react写的,ui为antd,脚手架umi,npm上找了几个pdf转图片的react库,例如react-pdf,浏览器展示没有问题,但是在钉钉上遇到了

The browser/environment lacks native support for critical functionality used by the PDF.js library (e.g. 'ReadableStream' and/or 'Promise.allSettled'); please use an ES5-compatible build instead.

该错误,点击这里查看相关内容。后改用了pdfjd-dist

配合ant ui库,自己实现了一个简单的组件

import React, { useState, useEffect, useRef } from 'react';
import { Spin, Pagination } from 'antd';
var pdfjsLib = require('pdfjs-dist/es5/build/pdf.js');
import 'pdfjs-dist/es5/build/pdf.worker.entry';

interface PdfViewerProps {
    url: string;
}
const PdfViewer = ({ url }: PdfViewerProps) => {
    const [pageNumbers, setPageNumbers] = useState(0);
    const [currentPage, setCurrentPage] = useState(1);
    const [loading, setLoading] = useState(true);
    const [rendering, setRendering] = useState(false);
    const pdfRef: any = useRef(null);
    function renderPdf(pdfFile: any) {
        let canvas: any = document.getElementById('pdf');
        let canvasContext = canvas.getContext('2d');
        pdfFile.getPage(currentPage).then((page: any) => {
            //逐页解析PDF
            var viewport = page.getViewport({ scale: 5 }); // 页面缩放比例,值越大越清晰
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            canvasContext.clearRect(0, 0, canvas.width, canvas.height);
            var renderContext = {
                canvasContext: canvasContext,
                viewport: viewport,
                rotate: 90,
            };
            setRendering(true);
            page.render(renderContext).promise.finally(() => {
                setRendering(false);
            }); //渲染生成
        });
    }

    useEffect(() => {
        let loadingTask = pdfjsLib.getDocument(url);
        loadingTask.promise
            .then((pdf: any) => {
                // console.log(pdf.numPages);
                pdfRef.current = pdf;
                setPageNumbers(pdf.numPages);
                renderPdf(pdf);
            })
            .catch((error: any) => {
                console.log(error);
            })
            .finally(() => {
                setLoading(false);
            });
    }, []);

    useEffect(() => {
        if (pdfRef.current) {
            window.scrollTo({ top: 0 });
            renderPdf(pdfRef.current);
        }
    }, [currentPage]);

    return (
        <Spin spinning={loading || rendering}>
            <div>
                <canvas id="pdf" style={{ width: '100%' }} />
                {!loading && (
                    <Pagination
                        style={{ textAlign: 'center', marginTop: 15 }}
                        current={currentPage}
                        total={pageNumbers}
                        pageSize={1}
                        onChange={value => setCurrentPage(value)}
                    />
                )}
            </div>
        </Spin>
    );
};

export default PdfViewer;

页面中使用

<PdfViewer url="temp.pdf" />

程序员灯塔
转载请注明原文链接:react pdf转图片展示
喜欢 (0)