How can I help you?
Save PDF files to Dropbox cloud storage
25 Feb 202610 minutes to read
The React PDF Viewer component supports saving PDF files to Dropbox using either the standalone or server-backed configuration. The following steps demonstrate both approaches.
Using Standalone PDF Viewer
To save a PDF file to Dropbox, follow these steps:
Step 1: Create a Dropbox API app
To create a Dropbox API App, you should follow the official documentation provided by Dropbox link. The process involves visiting the Dropbox Developer website and using their App Console to set up your API app. This app will allow you to interact with Dropbox programmatically, enabling secure access to files and data.
Step 2: Create a PDF Viewer sample in React
Follow the instructions provided in this link to create a simple PDF Viewer sample in React. This sets up the basic structure of the PDF Viewer application.
Step 3: Modify the src/app/app.ts file in the React project
- Import the required namespaces at the top of the file:
import { Dropbox } from 'dropbox';- Configure a custom toolbar item for the download function to save a PDF file to Dropbox.
var toolItem1 = {
prefixIcon: 'e-icons e-pv-download-document-icon',
id: 'download_pdf',
tooltipText: 'Download file',
align: 'right'
};
function toolbarClick(args){
if (args.item && args.item.id === 'download_pdf') {
saveDocument();
}
};
return (<div>
<div className='control-section'>
{/* Render the PDF Viewer */}
<PdfViewerComponent
ref={(scope) => {
viewer = scope;
}}
created={loadDocument}
id="container"
resourceUrl="https://cdn.syncfusion.com/ej2/31.2.2/dist/ej2-pdfviewer-lib"
style={{ height: '640px' }}
toolbarSettings={{ showTooltip : true, toolbarItems: [ 'OpenOption', 'PageNavigationTool', 'MagnificationTool', 'PanTool', 'SelectionTool', 'SearchOption', 'PrintOption', toolItem1, 'UndoRedoTool', 'AnnotationEditTool', 'FormDesignerEditTool', 'CommentTool', 'SubmitForm']}}
toolbarClick={toolbarClick}
>
<Inject services={[ Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, BookmarkView,
ThumbnailView, Print, TextSelection, TextSearch, FormFields, FormDesigner ]}/>
</PdfViewerComponent>
</div>
</div>);- Retrieve the PDF viewer instance and save the current PDF as a Blob. Then read the Blob using a FileReader to convert it into an ArrayBuffer, and upload the ArrayBuffer to Dropbox using the
filesUploadmethod of the Dropbox instance.
NOTE
Replace Your Access Token with the actual access token for the Dropbox app.
function saveDocument() {
viewer.saveAsBlob().then(function (value) {
var reader = new FileReader();
reader.onload = async () => {
if (reader.result) {
const dbx = new Dropbox({ accessToken: 'Your Access Token' });
const uint8Array = new Uint8Array(reader.result);
dbx.filesUpload({ path: '/' + viewer.fileName, contents: uint8Array })
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
}
};
reader.readAsArrayBuffer(value);
});
};NOTE
Install the
dropboxpackage in the React project before running the sample:npm install dropbox.
Using server-backed PDF Viewer
To save a PDF file to Dropbox cloud file storage, you can follow the steps below
Step 1: Create a Dropbox API app
To create a Dropbox API app, follow the Dropbox .NET tutorial: Dropbox .NET tutorial. Use the Dropbox App Console to register an app and obtain the necessary access token and permissions.
Step 2: Create a PDF Viewer sample in React
Follow the Syncfusion getting-started instructions for the React PDF Viewer: React PDF Viewer getting started. This sets up the basic PDF Viewer application structure.
Step 3: Modify the PdfViewerController.cs file in the web service project
-
Create a web service project in .NET Core 3.0 or above. Refer to the Syncfusion knowledge base article on creating a PDF Viewer web service: Create a PDF Viewer web service in .NET Core 3.0 and above.
-
Open the
PdfViewerController.csfile in your web service project. -
Import the required namespaces at the top of the file:
using System.IO;
using Dropbox.Api;
using Dropbox.Api.Files;- Add the following private fields and constructor parameters to the
PdfViewerControllerclass. In the constructor, assign configuration values to the corresponding fields.
private IConfiguration _configuration;
public readonly string _accessToken;
public readonly string _folderName;
public PdfViewerController(IWebHostEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration)
{
_hostingEnvironment = hostingEnvironment;
_cache = cache;
_configuration = configuration;
_accessToken = _configuration.GetValue<string>("AccessToken");
_folderName = _configuration.GetValue<string>("FolderName");
}- Modify the
Download()method to save the downloaded PDF files to Dropbox cloud storage
[HttpPost("Download")]
[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
[Route("[controller]/Download")]
//Post action for downloading the PDF documents
public async Task<IActionResult> Download([FromBody] Dictionary<string, string> jsonObject)
{
//Initialize the PDF Viewer object with memory cache object
PdfRenderer pdfviewer = new PdfRenderer(_cache);
string documentBase = pdfviewer.GetDocumentAsBase64(jsonObject);
byte[] documentBytes = Convert.FromBase64String(documentBase.Split(",")[1]);
string documentId = jsonObject["documentId"];
string result = Path.GetFileNameWithoutExtension(documentId);
string fileName = result + "_downloaded.pdf";
using (var dropBox = new DropboxClient(_accessToken))
{
using (var stream = new MemoryStream(documentBytes))
{
// Upload the document to Dropbox
var uploadedFile = await dropBox.Files.UploadAsync(
_folderName + "/" + fileName,
WriteMode.Overwrite.Instance,
body: stream
);
}
}
return Content(documentBase);
}- Open the
appsettings.jsonfile in the web service project and add the following entries below the existing"AllowedHosts"configuration
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AccessToken": "Your_Dropbox_Access_Token",
"FolderName": "Your_Folder_Name"
}NOTE
Replace the placeholders with the actual Dropbox access token and folder name.
Step 4: Set the PDF Viewer properties in the React PDF Viewer component
Modify the serviceUrl property of the PDF Viewer component with the accurate URL of the web service, replacing https://localhost:44396/pdfviewer with the actual server URL. Set the documentPath property to the desired PDF file name to load from Dropbox, and ensure that the document exists in the target folder.
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 the 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
Dropbox.ApiNuGet package in the web service application to use the previous code example.
NOTE
Replace
PDF_Succinctly.pdfwith the actual document name stored in Dropbox and pass that name to thedocumentPathproperty of the PDF Viewer component.