steve
steve

Reputation: 95

How to upload only PDF file and preview in react Js

I am doing pdf upload in react js. I want to upload pdf file and just wants to show on the top of the upload button with small div along with remove button, if I click on the remove then it should be removed.

The same I have done it for image successfully. I can upload image and also can preview. But I need some help in doing pdf upload

here is my code,

 this.state = {
      file: '',
      imagePreviewUrl: ''
    }

getPhoto (e) { e.preventDefault();

let reader = new FileReader();
let file = e.target.files[0];

reader.onloadend = () => {
  this.setState({
    file: file,
    imagePreviewUrl: reader.result
  });
}
  reader.readAsDataURL(file);
}

 render() {
  const { imagePreviewUrl, file } = this.state;
  let imagePreview = null;
     if (imagePreviewUrl) {
        imagePreview = (<img src={imagePreviewUrl} />);
      } else {
        imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
      }
return (
      <React.Fragment>
      <div className={styles.previewBlock}>
        {imagePreview}
        <div className={styles.fileName}>{file.name}<span>
        <i className="fa fa-times" /></span></div>
      </div>
  )
 }

Upvotes: 0

Views: 18737

Answers (3)

Arnas Jelizarovas
Arnas Jelizarovas

Reputation: 21

I am using react-pdf to render the PD, and once it's rendered, convert canvas to a blob url that then can be displayed as image.

import React, { useRef, useState } from "react";
import { Document, Page } from "react-pdf/dist/esm/entry.webpack";
import "react-pdf/dist/esm/Page/AnnotationLayer.css";
const pdfSrc = "/pdfs/test.pdf";

export const PDFPreview = ({ preview = pdfSrc, setPreview }) => {
  const canvasRef = useRef(null);
  const [thumb, setThumb] = useState(null);
  if (thumb) return <img src={thumb} alt="pdf preview" className="rounded overflow-hidden" />;
  return (
    <>
      <Document file={preview}>
        <Page
          onRenderSuccess={() => {
            canvasRef?.current?.toBlob((blob) => setThumb(URL.createObjectURL(blob)));
          }}
          height={200}
          canvasRef={canvasRef}
          className="rounded overflow-hidden shadow-lg "
          renderTextLayer={false}
          pageNumber={1}
        />
      </Document>
    </>
  );
};

Upvotes: 0

Mati Cassanelli
Mati Cassanelli

Reputation: 743

You can try using react-pdf. I haven't used it, but in the outline demo it renders a pdf file. Hope it helps you!

Upvotes: 1

Dylan
Dylan

Reputation: 343

There is no HTML element that will render a pdf for you, but one possible solution is to use Mozilla's pdf.js library which can render pdf pages onto canvas elements.

Upvotes: 1

Related Questions