Saving PDF file

6 Jul 20246 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 Typescript

Start by following the steps provided in this link to create a simple PDF viewer sample in Typescript. 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 { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation,ThumbnailView,
         BookmarkView, TextSelection, Annotation, FormFields, FormDesigner} from '@syncfusion/ej2-pdfviewer';

PdfViewer.Inject( Toolbar,Magnification,Navigation, LinkAnnotation,ThumbnailView,
                  BookmarkView, TextSelection, Annotation, FormFields, FormDesigner);

let viewer: PdfViewer = new PdfViewer();
// Replace PDF_Succinctly.pdf with the actual document name that you want to load
viewer.documentPath="PDF_Succinctly.pdf"
viewer.serviceUrl = 'https://localhost:44396/pdfviewer';
viewer.appendTo('#pdfViewer');

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.

<button id="download">Download</button>
document.getElementById('download').addEventListener('click', function () {
  //API to perform download action.
  viewer.download();
});

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 Typescript

Start by following the steps provided in this link to create a simple PDF viewer sample in Typescript. 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 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";

  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