Save PDF files to Box cloud storage
28 Feb 20264 minutes to read
To save a PDF file to Box cloud storage using the ASP.NET Core PDF Viewer, follow the steps below. This approach uses a server-backed web service.
Step 1: Set up a Box developer account and create a Box application
Go to the Box Developer Console, sign in or create a new account, and create a new Box application. This application provides the required credentials (Client ID and Client Secret) to authenticate and access the Box APIs. Box supports OAuth 2.0 authentication.
Step 2: Create an ASP.NET Core PDF Viewer sample
Follow the instructions in this Getting Started guide to create a simple PDF Viewer sample in ASP.NET Core. This sets up the basic structure of the application.
Step 3: Modify the Index.cshtml.cs file in the project
- Import the required namespaces at the top of the file:
using Box.V2;
using Box.V2.Auth;
using Box.V2.Config;
using Box.V2.Models;- Add the following private fields and constructor parameters to the
Index.cshtml.csclass. In the constructor, assign the values from the configuration to the corresponding fields.
private IConfiguration _configuration;
public readonly string _accessToken;
public readonly string _clientID;
public readonly string _clientSecret;
public readonly string _folderID;
public IndexModel(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration)
{
_hostingEnvironment = hostingEnvironment;
_cache = cache;
_configuration = configuration;
_accessToken = _configuration.GetValue<string>("AccessToken");
_clientID = _configuration.GetValue<string>("ClientID");
_clientSecret = _configuration.GetValue<string>("ClientSecret");
_folderID = _configuration.GetValue<string>("FolderID");
}- Modify the
OnPostDownload()method to save the downloaded PDF files to the Box cloud storage folder.
public async Task<IActionResult> OnPostDownload([FromBody] jsonObjects responseData)
{
PdfRenderer pdfviewer = new PdfRenderer(_cache);
var jsonObject = JsonConverterstring(responseData);
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";
// Initialize the Box API client with your authentication credentials
var auth = new OAuthSession(_accessToken, "YOUR_REFRESH_TOKEN", 3600, "bearer");
var config = new BoxConfigBuilder(_clientID, _clientSecret, new Uri("http://boxsdk")).Build();
var client = new BoxClient(config, auth);
var fileRequest = new BoxFileRequest
{
Name = fileName,
Parent = new BoxFolderRequest { Id = _folderID },
};
using (var stream = new MemoryStream(documentBytes))
{
var boxFile = await client.FilesManager.UploadAsync(fileRequest, stream);
}
return Content(documentBase);
}- Open the
appsettings.jsonfile in the project and add the following lines below the existing"AllowedHosts"configuration.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AccessToken": "Your_Box_Storage_Access_Token",
"FolderID": "Your_Folder_ID",
"ClientID": "Your_Box_Storage_ClientID",
"ClientSecret": "Your_Box_Storage_ClientSecret"
}NOTE
Replace the placeholders with your actual Box access token and the target folder ID. Use valid Box API credentials for Client ID and Client Secret.
Step 4: Set the PDF Viewer properties in the ASP.NET Core PDF Viewer component
Set the documentPath property of the PDF Viewer component to the desired PDF file name that you wish to load from Box cloud storage. Ensure that the document exists in the target Box folder.
@page "{handler?}"
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<ejs-pdfviewer id="pdfviewer" style="height:600px" serviceUrl="/Index" documentPath="PDF_Succinctly.pdf">
</ejs-pdfviewer>
</div>NOTE
Install the Box.V2.Core NuGet package in the application to use the previous code example.
NOTE
Replace
PDF_Succinctly.pdfwith the actual document name to load from Box cloud storage. Pass the document name from the Box folder to thedocumentPathproperty of theReact PDF Viewercomponent.