react pdf转图片展示

最近有一个需求,需要在钉钉微应用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 (
        
            
{!loading && ( setCurrentPage(value)} /> )}
); }; export default PdfViewer;

页面中使用

你可能感兴趣的:(react pdf转图片展示)