Open PDF from AWS S3

The Vue PDF Viewer component supports loading PDF files from AWS S3 using either the standalone or the server-backed PDF Viewer. The following steps demonstrate both approaches.

Using the standalone PDF Viewer

Follow these steps to load a PDF from AWS S3 in the standalone PDF Viewer.

Step 1: Create a PDF Viewer sample in Vue

Follow the instructions in the getting started guide (Vue) to create a basic PDF Viewer sample.

Step 2: Modify the src/App.vue file in the Vue project

  1. Import the required namespaces at the top of the file:
<script>
  import AWS from 'aws-sdk';
</script>
  1. Configure the AWS SDK with the region, access key, and secret access key so the application can interact with S3.

NOTE

Replace Your Region with the actual Region of your AWS S3 account and Your Access Key with the actual Access Key of your AWS S3 account and Your Security Access Key with the actual Security Access Key of your AWS S3 account.

<script>
  AWS.config.update({
    region: '**Your Region**', // Update this your region
    accessKeyId: '*Your Access Key*', // Update this with your access key id
    secretAccessKey: '*Your Security Access Key*', // Update this with your secret access key
  });
</script>
  1. Set parameters for fetching the PDF document from S3, including the bucket name and file key. Use S3.getObject to retrieve the document, convert it to a Base64 string, and pass it to viewer.load in the SyncfusionĀ® PDF Viewer.

NOTE

Replace Your Bucket Name with the actual Bucket name of your AWS S3 account and Your Key with the actual File Key of your AWS S3 account.

<script>
export default {
  methods: {
    loadPdfDocument: function () {
      const getObjectParams = {
        Bucket: '**Your Bucket Name**',
        Key: '**Your Key**',
      };
      var s3= new AWS.S3();
      s3.getObject(getObjectParams, (err, data) => {
        if (err) {
          console.error('Error fetching document:', err);
        } else {
          if (data && data.Body) {
            const bytes = new Uint8Array(data.Body);
            let binary = '';
            bytes.forEach((byte) => (binary += String.fromCharCode(byte)));
            const base64String = window.btoa(binary);
            setTimeout(() => {
              var viewer = document.getElementById('pdfViewer').ej2_instances[0];
              viewer.load("data:application/pdf;base64,"+base64String);
            }, 2000);
          }
        }
      });
    },
  }
}
</script>

NOTE

The npm install aws-sdk package must be installed in your application to use the previous code example.

View sample in GitHub.

Using the server-backed PDF Viewer

Follow these steps to load a PDF from AWS S3 using the server-backed PDF Viewer.

Step 1: Create a PDF Viewer sample in Vue

Create a basic PDF Viewer sample by following the instructions in the getting started guide (Vue).

Step 2: Modify the PdfViewerController.cs File in the Web Service Project

  1. Create a web service project in .NET Core 3.0 or above. You can refer to this link for instructions on how to create a web service project.

  2. Open the PdfViewerController.cs file in your web service project.

  3. Import the required namespaces at the top of the file:

using System.IO;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
  1. Add the following private fields and constructor parameters to the PdfViewerController class, In the constructor, assign the values from the configuration to the corresponding fields
private IConfiguration _configuration;
public readonly string _accessKey;
public readonly string _secretKey;
public readonly string _bucketName;

public PdfViewerController(IWebHostEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration)
{
  _hostingEnvironment = hostingEnvironment;
  _cache = cache;
  _configuration = configuration;
  _accessKey = _configuration.GetValue<string>("AccessKey");
  _secretKey = _configuration.GetValue<string>("SecretKey");
  _bucketName = _configuration.GetValue<string>("BucketName");
}
  1. Modify the Load() method to load the PDF files from AWS S3.
[HttpPost("Load")]
[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
[Route("[controller]/Load")]
//Post action for Loading the PDF documentsĀ 

public async Task<IActionResult> Load([FromBody] Dictionary<string, string> jsonObject)
{
  // Initialize the PDF viewer object with memory cache object
  PdfRenderer pdfviewer = new PdfRenderer(_cache);
  MemoryStream stream = new MemoryStream();
  object jsonResult = new object();

  if (jsonObject != null && jsonObject.ContainsKey("document"))
  {
    if (bool.Parse(jsonObject["isFileName"]))
    {
      RegionEndpoint bucketRegion = RegionEndpoint.USEast1;

      // Configure the AWS SDK with your access credentials and other settings
      var s3Client = new AmazonS3Client(_accessKey, _secretKey, bucketRegion);

      string document = jsonObject["document"];

      // Specify the document name or retrieve it from a different source
      var response = await s3Client.GetObjectAsync(_bucketName, document);

      Stream responseStream = response.ResponseStream;
      responseStream.CopyTo(stream);
      stream.Seek(0, SeekOrigin.Begin);
    }
    else
    {
      byte[] bytes = Convert.FromBase64String(jsonObject["document"]);
      stream = new MemoryStream(bytes);
    }
  }

  jsonResult = pdfviewer.Load(stream, jsonObject);

  return Content(JsonConvert.SerializeObject(jsonResult));
}
  1. Open the appsettings.json file in your web service project. Add the following lines below the existing "AllowedHosts" configuration.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "AccessKey": "Your Access Key from AWS S3",
  "SecretKey": "Your Secret Key from AWS S3",
  "BucketName": "Your Bucket name from AWS S3"
}

NOTE

Replace Your Access Key from AWS S3, Your Secret Key from AWS S3, and Your Bucket name from AWS S3 with your actual AWS access key, secret key and bucket name

Step 3: Configure the PDF Viewer component

Set the serviceUrl to your web service endpoint (replace the localhost URL with your server URL). Set documentPath to the PDF file name to load from AWS S3. Ensure the document name matches an object in your bucket.

<template>
  <div id="app">
    <ejs-pdfviewer id="pdfViewer" :serviceUrl="serviceUrl" :documentPath="documentPath">
    </ejs-pdfviewer>
  </div>
</template>

<script>
import { provide } from "vue";
import {
  PdfViewerComponent as EjsPdfviewer, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView,
  ThumbnailView, Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner
} from '@syncfusion/ej2-vue-pdfviewer';

// Replace the "localhost:44396" with the actual URL of your server
const serviceUrl = "https://localhost:44396/pdfviewer";
const documentPath = "PDF_Succinctly.pdf";

provide('PdfViewer', [Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView,
  Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner]);

</script>
<template>
  <div id="app">
    <ejs-pdfviewer id="pdfViewer" :serviceUrl="serviceUrl" :documentPath="documentPath">
    </ejs-pdfviewer>
  </div>
</template>

<script>
import {
  PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView,
  ThumbnailView, Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner
} from '@syncfusion/ej2-vue-pdfviewer';

export default {
  name: 'app',
  components: {
    'ejs-pdfviewer': PdfViewerComponent
  },
  data() {
    return {
      // Replace the "localhost:44396" with the actual URL of your server
      serviceUrl: "https://localhost:44396/pdfviewer",
      documentPath: "PDF_Succinctly.pdf"
    };
  },
  provide: {
    PdfViewer: [Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView,
      Print, TextSelection, TextSearch, Annotation, FormFields, FormDesigner]
  }
}
</script>

NOTE

The AWSSDK.S3 NuGet package must be installed in your application to use the previous code example.

View sample in GitHub