How to Save PDF Document on the Server Side Using a Standalone PDF Viewer
How to Save PDF Document on the Server Side Using a Standalone PDF Viewer
Description:
This article shows how to save annotations made in Standalone PDF Viewer on the server side. The annotations can be made in standalone mode, downloaded, and then saved to the server.
Solution:
To allow users to save annotations to the server side, first add annotations using the Standalone PDF Viewer. Then, by clicking using Save Document function, the document is uploaded to the server for storage. This process includes loading, saving, and handling document changes and annotations via server-side integration.
Prerequisites:
Before diving into the implementation, ensure that the following steps are completed:
-
Ensure that the Syncfusion PDF Viewer is installed and configured in your Angular project. If you have not done so, please refer to the Getting Started guide for Syncfusion PDF Viewer for Angular.
-
Familiarity with Angular components and the basic setup of Angular projects will help you follow along with the implementation.
Code Snippets:
app.component.ts
Import Necessary Modules
In your app.component.ts, import all necessary modules from Syncfusion’s PDF Viewer package:
import { Component, OnInit } from '@angular/core';
import {LinkAnnotationService, BookmarkViewService,MagnificationService,
ThumbnailViewService, ToolbarService, NavigationService, AnnotationService,
TextSearchService, TextSelectionService, FormFieldsService,
FormDesignerService, PrintService, PdfViewerComponent} from '@syncfusion/ej2-angular-pdfviewer';
Handling Document Download and Save
To manage the download of annotations in base64 format, we monitor download events and initiate the server-side process to store the document.
//To save the PDF with Annotations in server.
public SaveDocument() {
const viewer = (document.getElementById('pdfViewer') as any).ej2_instances[0];
viewer.saveAsBlob()
.then((blob: Blob) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = (e: ProgressEvent<FileReader>) => {
const base64String = e.target?.result;
const xhr = new XMLHttpRequest();
xhr.open('POST', this.downloadurl, true);
xhr.setRequestHeader(
'Content-type',
'application/json; charset=UTF-8'
);
const requestData = JSON.stringify({ base64String });
xhr.onload = () => {
if (xhr.status === 200) {
console.log('Download request success');
} else {
console.error('Download failed:', xhr.statusText);
}
};
xhr.onerror = () => {
console.error(
'An error occurred during the download:',
xhr.statusText
);
};
xhr.send(requestData);
};
})
.catch((error: any) => {
console.error('Error saving Blob:', error);
});
}
Controller Code:
Server-Side Logic for Saving Annotations
On the server side, use the SaveDocument action to receive the document’s base64 data and save it as a PDF file.
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);
//return Content(documentBase);
string base64 = jsonObject["base64String"];
string base64String = base64.Split(new string[] { "data:application/pdf;base64," }, StringSplitOptions.None)[1];
byte[] byteArray = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(byteArray);
var path = _hostingEnvironment.ContentRootPath;
System.IO.File.WriteAllBytes(path + "/ouptut.pdf", byteArray);
return Content(string.Empty)
}
Key Features Used in the Code:
- Server Mode Integration: By switching the viewer to server mode, it allows for saving the document on the server side after annotations are made in standalone mode.
- Base64 Encoding: The document is downloaded in base64 format, which is then sent to the server for storage.
Sample Link:
You can access the complete sample via our GitHub Sample Repository
Steps to run the sample:
- Start the Server Project: Launch the server project and note down the hosting URL, which usually appears as https://localhost:7255/pdfviewer.
- Launch the Client: Input the server URL you copied into the client’s configuration under the downloadurl field and then initiate the client.
- Insert Annotations: Using the client, add the necessary annotations to the document.
- Save the Document: After adding annotations, click the SaveDocument button to store the document.
Conclusion:
I hope you enjoyed learning about how to save annotations on the server side using the with Standalone Angular PDF Viewer.
You can refer to Angular PDF feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Angular PDF Viewer example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!