Unusual actions observed when showcasing PDF files within an HTML environment

Exploring the stack and data:


I've been diligently working on integrating a PDF display feature into our AngularJS Kiosk application since yesterday evening. However, I have encountered multiple roadblocks in the process.

At present, I have a table in our SQL Server database that stores various data, including a field containing a varbinary(max) representation of a PDF file.

This data is fetched via a C# REST WebAPI, which returns JSON objects where the PDF varbinary is converted to a byte[] format.

Each PDF file is linked to a specific role and workplace. Currently, this information is bundled within the returned JSON object.


The Issue at Hand:

While my current implementation works perfectly for displaying images, running into problems arises when dealing with PDF files:

a.) The PDF content may be distorted; appearing upside down, having text displayed backwards, or even parts of the content being flipped. (Occurs when using pdf.js)

b.) In some cases, the PDF fails to load due to missing data or errors causing destruction of the worker thread(angular-pdf).

Upon reverting back to using pdf.js, scenario a.) continues to persist.


Code Snippet:

This is how I extract the data using Angular:

$http.post("http://some-example.com/api/PDF/Get", JSON.stringify(vm.content))
    .then(function (response) {
        //success

        vm.data = response.data;
        $sce.trustAsResourceUrl(vm.data[0].Pdf);
    },
    function (error) { 

    })
    .finally(function () {
        let pdf = atob(vm.data[0].Pdf);
        let loadingTask = PDFJS.getDocument({ data: pdf }); 

        loadingTask.promise.then(function (pdf) { 

            let pageNumber = 1;
            pdf.getPage(pageNumber).then(function (page) {
                let scale = 1;
                let viewport = page.getViewport(scale);

                let canvas = document.getElementById('test-canvas');
                let context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;

                let renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };
                let renderTask = page.render(renderContext);
                renderTask.then(function () { 
                    // Wait for rendering to finish
                    renderTask.promise.then(function () {
                        pageRendering = false;
                        if (pageNumPending !== null) {
                            // New page rendering is pending
                            renderPage(pageNumPending);
                            pageNumPending = null;
                        }
                    });
                }); 
            });
        });
    });

Upon inspecting the Pdf property of the returned object, it appears to be of type string and displays a decoded binary value, as the Pdf value stored in the database is encoded.

Here's how the REST API (C#) retrieves and processes the data:

[HttpPost]
public HttpResponseMessage Get(int get_id = 0)
{
    HttpContent req = Request.Content;
    int val = 0;
    string jsonContent = req.ReadAsStringAsync().Result;
    JObject jobobj = JObject.Parse(jsonContent);
    string where = null;
    List<test_pdf_table> list = new List<test_pdf_table>();
    DataSet ds = null;

    try
    {
        where = (jobobj["where"] == null) ? null : (string)jobobj["where"];
        string strcon = ConfigurationManager.ConnectionStrings[(string)jobobj["strcon"]].ConnectionString;
        ds =  dc.FETCHtest_pdf_table((where == null) ? "Where ID = " + get_id : where, (strcon == null) ? conStr : strcon, "REST");
    }

    catch (Exception e)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError, e.ToString());
    }

    if (where == null) 
    {
        ds = dc.FETCHtest_pdf_table("WHERE ID = " + get_id, conStr, "REST");
    } 
    else 
    {
        ds = dc.FETCHtest_pdf_table(where, conStr, "");
    }

    foreach (DataTable table in ds.Tables)
    {

        foreach (DataRow row in table.Rows)
        {
            int? id = row["ID"] as int?;
            int? userid = row["UserID"] as int?;
            int? worksiteid = row["WorksiteID"] as int?;
            Byte[] pdf = row["Pdf"] as Byte[];
            String path = row["Path"] as String;

        list.Add(new test_pdf_table
                {
                    ID = id,
                    UserID = userid,
                    WorksiteID = worksiteid,
                    Pdf = pdf,
                    Path = path
            });
        }
    } 
    return Request.CreateResponse(HttpStatusCode.OK, list);
}

Lastly, here is how I am rendering the PDF content:

<canvas id="test-canvas"></canvas>

To Summarize:

The PDF IS displayed successfully, but with inconsistent results each time. There are instances where the orientation is incorrect, text appears reversed, or duplication of content occurs (as if the PDF has been mirrored) upside-down.

Answer №1

If you encounter rendering issues, consider removing and recreating the canvas element before each render. While it may not be the most elegant solution, it could help address any problems with the display. Hopefully, future updates of PDFJS will eliminate the need for this workaround:

const canvas = document.getElementById('test-canvas');
const parent = canvas.parentNode;
let context;

parent.removeChild(canvas);
const newCanvas = document.createElement('canvas');
newCanvas.id = 'test-canvas';
parent.insertBefore(newCanvas, parent.childNodes[0]);
context = newCanvas.getContext('2d');

newCanvas.height = viewport.height;
newCanvas.width = viewport.width;

const renderContext = {
    canvasContext: context,
    viewport: viewport
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Find differences in JSON elements regardless of their specific field values using Groovy

I'm facing a challenge with JSON files containing the same fields but different values. I need to create a groovy script that compares these files while ignoring the values of the fields. For example: json1 = '{"name" : "abc", "value": "123", " ...

Modifying td background color according to values in a PHP array

Trying to update the background color of a td element with the code below. However, it seems that the code needs some adjustment as the color is not being applied. Any assistance or alternative solutions would be greatly appreciated. Snippet of PHP code: ...

Can you use typeahead, filtering, and then parsing JSON data?

Currently struggling with the task of extracting data from an external .json file in my typeahead code. However, the structure of the .json file (which cannot be altered) is as follows: {"**cms_countries**": [{"**cms_country**": [{"**countrydisplayname ...

Adding a value to a JSON array using Bash

I have been working on a bash script to parse a URL into its different components. I am currently facing an issue while trying to add an array value to a key within a JSON object. What I've Tried: The URL that I parsed is: https://bar.foo.com/v2020/ ...

Three database queries and two JSON objects

I've set up a query to retrieve the communities that I belong to. In addition, I have created two additional queries to fetch the communities that I am currently following. However, the results only show my own communities and not the ones I am foll ...

What is the process for choosing a table column by clicking on the "select" option?

Welcome to my project! Here is an example table that I'm working on. I have a question - how can I make it so that when I click on "choose me", the entire column is selected? Can you help me with this? <table> <tr> <th>plan A&l ...

What is the best way to have DOMDocument processed in PHP after running Javascript?

Currently, I'm working on a program that searches for tags. Unfortunately, I'm encountering difficulties retrieving tags created with JavaScript. ...

Is there a way for me to showcase a collection of pictures in an array format

I am facing an issue on my react page where the data is successfully fetched from an API, but I am having trouble fetching the array of images. Below is the code snippet that I have written: import React, {Component} from 'react'; export defaul ...

Using the mouseover event in three.js to interact with child meshes

My array, objMesh, contains multiple mesh objects. Each object has a children attribute, which in turn holds an array of more mesh objects (such as countries and their islands). How can I make it so that when I hover over each mesh object, its children are ...

What is the method for retrieving the active element with Waypoint?

Currently, I am implementing Waypoint (version 7.3.2) in my React project using React version 16. My goal is to create a scrollable list of items where each item fades out as it reaches the top of the container div. My main inquiry is how can I obtain a re ...

I'm working with a substantial volume of data and I'm looking for a way to efficiently page it in a datatable. Any suggestions on

When dealing with a large amount of data for comparison and fetching records from the database, I am encountering issues with memory usage and slow performance when inserting into a datatable. Is there any suggestion for implementing data paging in the d ...

Having difficulties in Vue while attempting to access a particular row

I encountered an error message stating Uncaught TypeError: snapShotChnaged.forEach is not a function. My goal is to retrieve specific row data, which is why I am utilizing the doc method. retrieveSpecificDonation() { firestore .collection('d ...

Is React-Apollo encountering a 404 network error?

I am currently exploring React-apollo and attempting to implement Server-side rendering with apollo, but I keep encountering a 404 error. Despite confirming that my graphQL endpoint is functional. Here is the specific error message: { Error: Network erro ...

Efficiently managing database writes in a multithreaded application

I am currently working on a server application that is responsible for receiving data from clients and storing it in a database. For the client/server communication, I am utilizing ServiceStack. Each client call may result in one or more records that need ...

Start the jQuery animation only when the ajax information differs

I am using setInterval to create a timer that runs every 20 seconds. It utilizes jQuery's ajax function load() to populate the toparticles div with data from another URL on the site. After the data is successfully loaded, it applies a jQuery highlight ...

Shortcut for JSON formatting in Sublime Text

I prefer using SublimeText for coding. Is there a quick way to reindent JSON code in SublimeText? I've successfully installed Package Control and it's functioning properly. I attempted to use the JsonReindent package, but couldn't find a ...

Applying an AngularJS ng-repeat filter based on specified conditions

I am working with two arrays: items and items2. If items2 is empty, I want to display only the one item in items. Is there a way to add a conditional statement to the limitTo filter? The limitTo should be applied based on a certain condition. Appreciate ...

`JQuery fadeOut seems to have a limitation where it only applies to the

I have a group of divs, each containing an anchor tag that triggers a JavaScript function (which uses AJAX to delete a row from a table). Here's an example setup: <div id="container"> <div><a id="btn" onclick="deleteRow()">Delet ...

Developed a hierarchical JSON format using a JavaScript array

I am aiming to generate a properly structured nested JSON file from an array, with unique key values. Currently, I can only output the JSON without any nesting. The desired structure to be displayed in the console is : { "Key" : "data1", "header" ...

Utilizing a refreshed array of elements within a component directive

When working within a view, I am utilizing ng-repeat inside a directive to iterate over an array of objects from my controller. However, as the objects in the array undergo value changes, I encounter a dilemma when transitioning to a new instance of the sa ...