How can I help you?
Add a new page to a PDF document in JavaScript PDF Viewer control
13 Feb 20263 minutes to read
The JavaScript PDF Viewer can append a blank page to a loaded PDF document by using the accompanying PDF library service on the server.
Step 1: Follow the guidance in the Getting started with the JavaScript PDF Viewer article to configure a working sample.
Step 2: Complete the web service setup using this guide.
Step 3: Add the following controller action to insert a new page into the loaded PDF document before returning it to the viewer. The example below is a server-side controller action; validate inputs and add appropriate error handling for production use.
[HttpPost("Load")]
[Route("[controller]/Load")]
//Post action for loading PDF documents.
public IActionResult Load([FromBody] Dictionary<string, string> jsonObject)
{
Console.WriteLine("Load called");
//Initialize the PDF viewer object with the memory cache object.
PdfRenderer pdfviewer = new PdfRenderer(_cache);
MemoryStream stream = new MemoryStream();
object jsonResult = new object();
if (jsonObject != null && jsonObject.ContainsKey("document"))
{
if (bool.Parse(jsonObject["isFileName"]))
{
string documentPath = GetDocumentPath(jsonObject["document"]);
if (!string.IsNullOrEmpty(documentPath))
{
byte[] bytes = System.IO.File.ReadAllBytes(documentPath);
stream = new MemoryStream(bytes);
}
else
{
return this.Content(jsonObject["document"] + " is not found");
}
}
else
{
byte[] bytes = Convert.FromBase64String(jsonObject["document"]);
stream = new MemoryStream(bytes);
}
}
//Code to create a new page at the end of the loaded pdf document.
PdfLoadedDocument pdfLoadedDocument = new PdfLoadedDocument(stream);
pdfLoadedDocument.Pages.Add();
MemoryStream str = new MemoryStream();
pdfLoadedDocument.Save(str);
pdfLoadedDocument.Close(true);
jsonResult = pdfviewer.Load(str, jsonObject);
return Content(JsonConvert.SerializeObject(jsonResult));
}