How can I help you?
Open PDF from AWS S3
25 Feb 20269 minutes to read
The React 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 React
Follow the instructions in the getting started guide (React) to create a basic PDF Viewer sample: https://help.syncfusion.com/document-processing/pdf/pdf-viewer/react/getting-started
Step 2: Modify the src/index.js File in the React Project
- Import the required namespaces at the top of the file:
import AWS from 'aws-sdk';- Configure the AWS SDK with the region, access key, and secret access key so the application can interact with S3.
NOTE
Replace the placeholders with values for the target AWS account (region, access key, and secret access key). Do not commit credentials to source control.
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
});- Set parameters for fetching the PDF (bucket name and file key). Use S3.getObject to retrieve the document, convert it to a Base64 string, and pass it to viewer.load.
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.
const s3 = new AWS.S3();
loadDocument() {
const getObjectParams = {
Bucket: '**Your Bucket Name**',
Key: '**Your Key**',
};
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(() => {
viewer.load("data:application/pdf;base64,"+base64String);
}, 2000);
}
}
});
}NOTE
Install the
aws-sdkpackage in your application to use the previous code example. Do not embed AWS credentials in client-side code for production—use a server-backed approach or secure token service instead.
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 React
Create a basic PDF Viewer sample by following the getting started guide: https://help.syncfusion.com/document-processing/pdf/pdf-viewer/react/getting-started
Step 2: Modify the PdfViewerController.cs File in the Web Service Project
-
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.
-
Open the
PdfViewerController.csfile in your web service project. -
Import the required namespaces at the top of the file:
using System.IO;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;- Add the following private fields and constructor parameters to the
PdfViewerControllerclass, 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");
}- 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));
}- Open the
appsettings.jsonfile 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 the placeholders with the actual AWS credentials and bucket name. When storing secrets in
appsettings.json, follow secure secrets-management practices (for example, environment variables or a secrets store) in production.
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.
import * as ReactDOM from 'react-dom';
import * as React from 'react';
import { PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView, ThumbnailView,
Print, TextSelection, Annotation, TextSearch, Inject, FormDesigner, FormFields} from '@syncfusion/ej2-react-pdfviewer';
function App() {
return (<div>
<div className='control-section'>
{/* Render the PDF Viewer */}
<PdfViewerComponent
id="container"
documentPath="PDF_Succinctly.pdf"
// Replace the "localhost:44396" with the actual URL of your server
serviceUrl="https://localhost:44396/pdfviewer"
style={{ 'height': '640px' }}>
<Inject services={[ Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, BookmarkView, ThumbnailView,
Print, TextSelection, TextSearch, FormDesigner, FormFields ]} />
</PdfViewerComponent>
</div>
</div>);
}
const root = ReactDOM.createRoot(document.getElementById('sample'));
root.render(<App />);NOTE
Install the
AWSSDK.S3NuGet package in your web service project to use the previous code example.