3

我正在使用 ReactJS 开发一个课程平台。当用户完成课程后,他可以下载 PDF 文件。

我需要与图像(png或jpg)相同的文件的版本,但我还没有找到任何方法来做到这一点。有人能帮我吗?

要生成 PDF 证书,我使用的是 lib: React-PDF

这是我生成pdf文件的代码:

<PDFDownloadLink
  document={
    <Certificate course={course} name={name} date={today()} />
  }
  fileName="somename.pdf"
  >
    {({ blob, url, loading, error }) => {
      return loading ? 'Loading document...' : 'Download now!';
    }}
</PDFDownloadLink>
4

2 回答 2

3

我创建了一个辅助函数:convertPdfToImages,它接收 pdf 文件并使用pdfjs包返回以 base64 编码的图像数组。

npm install pdfjs-dist -S

const PDFJS = require("pdfjs-dist/webpack");

const readFileData = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      resolve(e.target.result);
    };
    reader.onerror = (err) => {
      reject(err);
    };
    reader.readAsDataURL(file);
  });
};

//param: file -> the input file (e.g. event.target.files[0])
//return: images -> an array of images encoded in base64 
const convertPdfToImages = async (file) => {
  const images = [];
  const data = await readFileData(file);
  const pdf = await PDFJS.getDocument(data).promise;
  const canvas = document.createElement("canvas");
  for (let i = 0; i < pdf.numPages; i++) {
    const page = await pdf.getPage(i + 1);
    const viewport = page.getViewport({ scale: 1 });
    const context = canvas.getContext("2d");
    canvas.height = viewport.height;
    canvas.width = viewport.width;
    await page.render({ canvasContext: context, viewport: viewport }).promise;
    images.append(canvas.toDataURL());
  }
  canvas.remove();
  return images;
}

于 2021-01-31T23:46:03.910 回答
3

请使用这个库

https://www.npmjs.com/package/react-pdf-to-image

这很简单。它将返回图像列表(pdf中的每一页作为一个图像)

import React from 'react';
import {PDFtoIMG} from 'react-pdf-to-image';
import file from './pdf-sample.pdf';

const App = () =>
    <div>
        <PDFtoIMG file={file}>
            {({pages}) => {
                if (!pages.length) return 'Loading...';
                return pages.map((page, index)=>
                    <img key={index} src={page}/>
                );
            }}
        </PDFtoIMG>
    </div>

export default App;

如果您只想将每个 pdf 页面下载为图像而不是组件,请遵循以下代码

import PDFJS from 'pdfjs-dist/webpack';

这是 react-pdf-to-image 的依赖库。然后阅读pdf文件(我将base64作为输入)

PDFJS.getDocument(blob).promise.then(pdf => {
     const pages = [];
     this.pdf = pdf;
     for (let i = 0; i < this.pdf.numPages; i++) {
         this.getPage(i + 1).then(result => {
         // the result is the base 64 version of image
     });
   }
})

阅读完每一页后,从 getPage 方法中读取每一页作为图像,如下所示

getPage = (num) => {
    return new Promise((resolve, reject) => {
        this.pdf.getPage(num).then(page => {
            const scale = "1.5";
            const viewport = page.getViewport({
                scale: scale
            });
            const canvas = document.createElement('canvas');
            const canvasContext = canvas.getContext('2d');
            canvas.height = viewport.height || viewport.viewBox[3]; /* viewport.height is NaN */
            canvas.width = viewport.width || viewport.viewBox[2];  /* viewport.width is also NaN */
            page.render({
                canvasContext, viewport
            }).promise.then((res) => {
                resolve(canvas.toDataURL());
            })
        })
    })
}
于 2020-08-18T02:25:39.250 回答