Read S3 bucket private pdf file by checking S3 access key and secret key using PDF.js Express

Hi,
As per our earlier discussion to load the document viewer with S3 credentials, I tried with below code:

WebViewer({
        path: '/lib/PDFJSExpress/lib',
      }, document.getElementById('viewer1')
    ).then(async instance => {
      const s3 = new AWS.S3();
      const body: BlobPart = await new Promise(resolve => {
      s3.getObject({
        Bucket: 'YOUR_BUCKET',
        Key:'KEY_OF_FILE',
     }, (err, resp) => {
      if (err) {
        console.log(err)
      }
      resolve(resp.Body as BlobPart)
    })
  });
  const file = new Blob([body], {type: 'application/pdf' });
 instance.loadDocument(file);
});

I am getting error "Missing Assignment to constant “body” on below line:
“const body: BlobPart = await new Promise”

Please suggest if required any changes and I am also not getting relevant help from “https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html

Warm Regards,
Kartik Shah

Hi!

Are you in a typescript environment? If not you need to remove the Typescript syntax from that code snippet you sent, so it should look like this:

WebViewer(
  {
    path: '/lib/PDFJSExpress/lib',
  },
  document.getElementById('viewer1'),
).then(async (instance) => {
  const s3 = new AWS.S3();
  
  const body = await new Promise((resolve) => {
    s3.getObject(
      {
        Bucket: 'YOUR_BUCKET',
        Key: 'KEY_OF_FILE',
      },
      (err, resp) => {
        if (err) {
          console.log(err);
        }
        resolve(resp.Body);
      },
    );
  });

  const file = new Blob([body], { type: 'application/pdf' });
  instance.loadDocument(file);
});

If you are using Typescript, then i’m not sure what the issue would be. My best guess would be that your promise is resolving to null or undefined which would make body null, and then you are trying to construct a blob with a null blob part.

Since this question is not related to PDF.js Express, I am going to close this discussion.

Thanks!
Logan