0

hello guys i am rendering a pdf on my react application using react-pdf/renderer react pdf and now i want to upload that rendered pdf directly to the aws s3 storage I have successfully made an api to upload files to s3 storage and its working fine in postman.I can upload files to s3 using input type file but i want to upload rendered pdf directly to that storage for later retreival in my application. sharing boiler react-pdf template I found some solutions like convert react-pdf to buffer and stream but i didnt get any sufficient resources or solutions.

import React from 'react';
import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer';

// Create styles
const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4'
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

// Create Document Component
const MyDocument = () => (
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.section}>
        <Text>Section #1</Text>
      </View>
      <View style={styles.section}>
        <Text>Section #2</Text>
      </View>
    </Page>
  </Document>
);

Backend code

const aws = require('aws-sdk')
const multer = require('multer')
const multerS3 = require('multer-s3');


aws.config.update({
    secretAccessKey: process.env.ACCESS_SECRET,
    accessKeyId: process.env.ACCESS_KEY,
    region: process.env.REGION,

});
const BUCKET = process.env.BUCKET
const s3 = new aws.S3();

const upload = multer({
  storage: multerS3({
      s3: s3,
      acl: "public-read",
      bucket: BUCKET,
      key: function (req, file, cb) {
          console.log(file);
          cb(null, file.originalname)
      }
  })
})

app.post('/uploadContractTos3', upload.single('file'), async function (req, res, next) {

  res.send({s3fileurl : req.file.location})
  // res.send("S3 uploaded")

})

1 Answers1

0

Using renderToStream() method from @react-pdf/renderer:

const pdfStream = await ReactPDF.renderToStream(<MyPdf />)

var uploadParams = {Bucket: '<bucket>', Key: '<fileName>', Body: pdfStream, ContentType: 'application/pdf'}
let uploadPromise = await s3.upload(uploadParams).promise()
console.log('Uploaded file URL', uploadPromise.Location)

Second way is not ideal but you can save the document to a folder and then upload it again to S3 bucket.

import ReactPDF from "@react-pdf/renderer";
ReactPDF.render(<MyDocument />, `${__dirname}/example.pdf`);

Note: I am not sure about React but in NextJS, it's not possible to access dynamically generated files on runtime through direct links but you can refer to file path instead.