Saving PDF files in React Pdfviewer component (2024)

4 Nov 20238 minutes to read

After editing the PDF file with various annotation tools, you will need to save the updated PDF to the server, database, or local file system.

Save PDF file to Server

Need to save the modified PDF back to a server. To achieve this, proceed with the following steps

Step 1: Create a Simple PDF Viewer Sample in React

Start by following the steps provided in this link to create a simple PDF viewer sample in React. This will give you a basic setup of the PDF viewer component.

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. Modify the Download() method to open it in the viewer using URL

public 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); MemoryStream stream = new MemoryStream(); string documentName = jsonObject["document"]; string result = Path.GetFileNameWithoutExtension(documentName); string fileName = result + "_downloaded.pdf"; // Save the file on the server string serverFilePath = @"Path to where you need to save your file in the server"; string filePath = Path.Combine(serverFilePath, fileName); using (FileStream fileStream = new FileStream(filePath, FileMode.Create)) { //Saving the new file in root path of application stream.CopyTo(fileStream); fileStream.Close(); } return Content(documentBase);}

Step 3: Set the PDF Viewer Properties in React 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.Modify the documentPath with the correct PDF Document URL want to load.

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”
// Replace correct PDF Document URL want to load
documentPath=”https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf”
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();

View sample in GitHub

Download PDF file as a copy

In the built-in toolbar, you have an option to download the updated PDF to the local file system, you can use it to download the PDF file.

import * as ReactDOM from ‘react-dom/client’;
import * as React from ‘react’;
import ‘./index.css’;
import { PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation, BookmarkView,
ThumbnailView, Print, TextSelection, Annotation, TextSearch, FormFields, FormDesigner, Inject} from ‘@syncfusion/ej2-react-pdfviewer’;

export function App() {

function downloadClicked() {
var viewer = document.getElementById(‘container’).ej2_instances[0];
viewer.download();
}

return (<div>
<div className='control-section'>
<button onClick={downloadClicked}>Download</button>
<PdfViewerComponent
id=”container”
// Replace PDF_Succinctly.pdf with the actual document name that you want to load
documentPath:”PDF_Succinctly.pdf”
// Replace the “localhost:44396” with the actual URL of your server
serviceUrl=”https://localhost:44396/pdfviewer”
style={{ ‘height’: ‘640px’ }}>

 {/* Inject the required services */} <Inject services={[ Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, BookmarkView, ThumbnailView, Print, TextSelection, TextSearch, FormFields, FormDesigner]} /> </PdfViewerComponent></div>

</div>);
}
const root = ReactDOM.createRoot(document.getElementById(‘sample’));
root.render();

Save PDF file to Database

If you have plenty of PDF files stored in database and you want to save the updated PDF file back to the database, use the following code example.

Step 1: Create a Simple PDF Viewer Sample in React

Start by following the steps provided in this link to create a simple PDF viewer sample in React. This will give you a basic setup of the PDF viewer component.

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 System.Data.SqlClient;
  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 _connectionString;public PdfViewerController(IWebHostEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration){ _hostingEnvironment = hostingEnvironment; _cache = cache; _configuration = configuration; _connectionString = _configuration.GetValue<string>("ConnectionString");}
  1. Modify the Download() method to open it in the viewer using URL
[HttpPost("Download")][Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")][Route("[controller]/Download")]//Post action for downloading the PDF documentspublic 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"; string connectionString = _connectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand cmd = new SqlCommand("INSERT INTO Table (FileName, fileData) VALUES (@FileName, @fileData)", connection)) { cmd.Parameters.AddWithValue("@FileName", fileName); cmd.Parameters.AddWithValue("@fileData", documentBytes); cmd.ExecuteNonQuery(); } connection.Close(); } return Content(documentBase);}
  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": "*", "ConnectionString": "Your connection string for SQL server"}

NOTE

Replace Your Connection string from SQL server with the actual connection string for your SQL Server database

NOTE

The System.Data.SqlClient package must be installed in your application to use the previous code example. You need to modify the connectionString variable in the previous code example as per the connection string of your database.

View sample in GitHub

Saving PDF files in React Pdfviewer component (2024)
Top Articles
17 Best GPS Navigation Apps for iOS and Android for 2024
ACI Segmentation and Migrations made easier with Endpoint Security Groups (ESG)
Aberration Surface Entrances
Craigslist Cars And Trucks For Sale By Owner Indianapolis
Craigslist Benton Harbor Michigan
Retro Ride Teardrop
Red Wing Care Guide | Fat Buddha Store
Mikayla Campinos Videos: A Deep Dive Into The Rising Star
Pwc Transparency Report
What is the surrender charge on life insurance?
R/Afkarena
Studentvue Columbia Heights
DoorDash, Inc. (DASH) Stock Price, Quote & News - Stock Analysis
What is Rumba and How to Dance the Rumba Basic — Duet Dance Studio Chicago | Ballroom Dance in Chicago
Amc Flight Schedule
Echat Fr Review Pc Retailer In Qatar Prestige Pc Providers – Alpha Marine Group
St. Petersburg, FL - Bombay. Meet Malia a Pet for Adoption - AdoptaPet.com
MLB power rankings: Red-hot Chicago Cubs power into September, NL wild-card race
Self-Service ATMs: Accessibility, Limits, & Features
Talk To Me Showtimes Near Marcus Valley Grand Cinema
Hdmovie2 Sbs
Aspenx2 Newburyport
27 Modern Dining Room Ideas You'll Want to Try ASAP
1773x / >
Nottingham Forest News Now
Scott Surratt Salary
Phoenixdabarbie
Panchang 2022 Usa
Movies123.Pick
SOC 100 ONL Syllabus
Babylon 2022 Showtimes Near Cinemark Downey And Xd
Bella Thorne Bikini Uncensored
Devotion Showtimes Near The Grand 16 - Pier Park
Myanswers Com Abc Resources
Paperless Employee/Kiewit Pay Statements
Cpmc Mission Bernal Campus & Orthopedic Institute Photos
Cnp Tx Venmo
Differential Diagnosis
Dragon Ball Super Super Hero 123Movies
Parent Portal Pat Med
Coffee County Tag Office Douglas Ga
Sara Carter Fox News Photos
Syrie Funeral Home Obituary
Leland Westerlund
Dobratz Hantge Funeral Chapel Obituaries
Erica Mena Net Worth Forbes
Walmart Front Door Wreaths
Wild Fork Foods Login
Gear Bicycle Sales Butler Pa
Image Mate Orange County
Where To Find Mega Ring In Pokemon Radical Red
When Is The First Cold Front In Florida 2022
Latest Posts
Article information

Author: Golda Nolan II

Last Updated:

Views: 5669

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.