Save PDF files to Dropbox cloud storage in Angular
13 Feb 202611 minutes to read
The Angular 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 Simple PDF Viewer Sample in Angular
Follow the instructions provided in this link to create a simple PDF Viewer sample in Angular. This sets up the basic structure of the PDF Viewer application.
Step 3: Modify the src/app/app.ts file in the Angular 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 in Azure Blob Storage.
@Component({
selector: 'app-root',
template: `<div class="content-wrapper">
<ejs-pdfviewer id="pdfViewer"
[resourceUrl]='resource'
[toolbarSettings]="toolbarSettings"
(toolbarClick)="toolbarClick($event)"
style="height:640px;display:block">
</ejs-pdfviewer>
</div>`,
providers: [ LinkAnnotationService, BookmarkViewService, MagnificationService,
ThumbnailViewService, ToolbarService, NavigationService,
TextSearchService, TextSelectionService, PrintService,
AnnotationService, FormDesignerService, FormFieldsService, PageOrganizerService]
})
export class AppComponent implements OnInit {
public resource: string = "https://cdn.syncfusion.com/ej2/23.1.43/dist/ej2-pdfviewer-lib";
public toolItem1: CustomToolbarItemModel = {
prefixIcon: 'e-icons e-pv-download-document-icon',
id: 'download_pdf',
tooltipText: 'Download file',
align: 'right'
};
public toolbarSettings = {
showTooltip: true,
toolbarItems: ['OpenOption', 'PageNavigationTool', 'MagnificationTool', 'PanTool', 'SelectionTool', 'SearchOption', 'PrintOption', this.toolItem1, 'UndoRedoTool', 'AnnotationEditTool', 'FormDesignerEditTool', 'CommentTool', 'SubmitForm']
};
public toolbarClick(args: any): void {
if (args.item && args.item.id === 'download_pdf') {
this.SavePdfToBlob();
}
}
}- 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.
saveDocument() {
var proxy = this
var viewer = (<any>document.getElementById("pdfViewer")).ej2_instances[0];
this.fileName = viewer.fileName;
viewer.saveAsBlob().then((value: Blob) => {
const reader = new FileReader();
reader.onload = async () => {
let dbx = new Dropbox({ accessToken: 'Your Access Token' });
const uint8Array = new Uint8Array(reader.result as ArrayBuffer);
dbx.filesUpload({ path: '/' + proxy.fileName , contents: uint8Array })
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.error(error);
});
};
reader.readAsArrayBuffer(value);
});
}NOTE
Install the
dropboxpackage in the Angular 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 Simple PDF Viewer Sample in Angular
Follow the Syncfusion getting-started instructions for the Angular PDF Viewer: Angular 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 the values from the configuration 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 Angular PDF Viewer component
Modify the serviceUrl property of the PDF viewer component with the accurate URL of your web service project, replacing https://localhost:44396/pdfviewer with the actual URL of your server. Set the documentPath property of the PDF viewer component to the desired name of the PDF file you wish to load from Dropbox cloud file storage. Ensure that you correctly pass the document name from the files available in your dropbox folder to the documentPath property.
import { Component, OnInit } from '@angular/core';
import { LinkAnnotationService, BookmarkViewService, MagnificationService,
ThumbnailViewService, ToolbarService, NavigationService,
TextSearchService, AnnotationService, TextSelectionService,
PrintService, FormDesignerService, FormFieldsService} from '@syncfusion/ej2-angular-pdfviewer';
@Component({
selector: 'app-container',
// specifies the template string for the PDF Viewer component
template: `<div class="content-wrapper">
<ejs-pdfviewer id="pdfViewer"
[serviceUrl]='service'
[documentPath]='documentPath'
style="height:640px;display:block">
</ejs-pdfviewer>
</div>`,
providers: [ LinkAnnotationService, BookmarkViewService, MagnificationService,ThumbnailViewService,
ToolbarService, NavigationService, AnnotationService, TextSearchService,
TextSelectionService, PrintService, FormDesignerService, FormFieldsService]
})
export class AppComponent implements OnInit {
// Replace the "localhost:44396" with the actual URL of the server
public service = 'https://localhost:44396/pdfviewer';
public documentPath = 'PDF_Succinctly.pdf';
}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.