上传之前如何预览PDF文件?

时间:2019-07-02 07:55:38

标签: reactjs

将上传数据转换为base64,我想在发送之前对其进行预览。

图像数据转换为base64,并显示在<img>标记中。
同样,文本文件也已完成。
但是现在可以在PDF预览中获取内容。

期望当我上传时,PDF应该是预览。

<div className="text-center">
  {this.state.files.map((file, i) => {
    if (
      file.Image_extension == "html" ||
      file.Image_extension == "png" ||
      file.Image_extension == "PNG" ||
      file.Image_extension == "JPG" ||
      file.Image_extension == "jpg"
    ) {
      return <img key={i} src={file.type} />;
      console.log(file.type);
    } else if (file.Image_extension == "txt" || file.Image_extension == "TXT") {
      //  alert(file.type)
      console.log(<textarea key={i} value={file.type}></textarea>);
      return <textarea id="text" key={i} value={file.type}></textarea>;
    } else {
      return <PDF file={file.type} scale={1.3} pages={Infinity} />;
    }
  })}
</div>;

1 个答案:

答案 0 :(得分:1)

您可以使用mozilla pdf.js。您可以查看here

document.querySelector("#pdf-upload").addEventListener("change", function(e) {
  var canvasElement = document.querySelector("canvas")
  var file = e.target.files[0]
  if (file.type != "application/pdf") {
    console.error(file.name, "is not a pdf file.")
    return
  }

  var fileReader = new FileReader();

  fileReader.onload = function() {
    var typedarray = new Uint8Array(this.result);

    PDFJS.getDocument(typedarray).then(function(pdf) {
      // you can now use *pdf* here
      console.log("the pdf has ", pdf.numPages, "page(s).")
      pdf.getPage(pdf.numPages).then(function(page) {
        // you can now use *page* here
        var viewport = page.getViewport(2.0);
        var canvas = document.querySelector("canvas")
        canvas.height = viewport.height;
        canvas.width = viewport.width;


        page.render({
          canvasContext: canvas.getContext('2d'),
          viewport: viewport
        });
      });

    });
  };

  fileReader.readAsArrayBuffer(file);
})
body {
  background: rgb(204, 204, 204);
}

.page {
  background: white;
  display: block;
  margin: 0 auto;
  margin-bottom: 0.5cm;
  box-shadow: 0 0 0.5cm rgba(0, 0, 0, 0.5);
}

.page[size="A4"] {
  width: 21cm;
  height: 29.7cm;
}

.page[size="A4"][layout="landscape"] {
  width: 29.7cm;
  height: 21cm;
}

.page[size="A3"] {
  width: 29.7cm;
  height: 42cm;
}

.page[size="A3"][layout="landscape"] {
  width: 42cm;
  height: 29.7cm;
}

.page[size="A5"] {
  width: 14.8cm;
  height: 21cm;
}

.page[size="A5"][layout="landscape"] {
  width: 21cm;
  height: 14.8cm;
}

@media print {
  body,
  page {
    margin: 0;
    box-shadow: 0;
  }
}
<script src="//cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.349/pdf.min.js"></script>
<input type="file" id="pdf-upload" />
<hr/>
<canvas class="page" size="A4" layout="landscape"></canvas>