Encountering problem while opening a PDF document in an AngularJS mobile application built with Cordova

Currently I am working on implementing the functionality to open PDF documents in AngularJS on desktop and mobile devices. I have been referring to the following resource: Open a PDF in a new window of the browser with AngularJS I have implemented a similar approach in my code, which looks like this:

**$http.get('generatePdfUrl')
  .then(function (data) {     // data is your url
      var file = new Blob([data], {type: 'application/pdf'});
      var fileURL = URL.createObjectURL(file);
  });**

I have also tried using 'responsetype: 'arraybuffer'', and in the AngularJS web application, the URL points to blob://http://localhost:8080/126gyesdfsdfadjf, it successfully opens the PDF document using window.open(fileURL), However, the same approach does not work for the AngularJS mobile application built with Cordova. The application URL points to blob:file///126gyesdfsdfadjf, but it fails to open the PDF document. I would appreciate any suggestions or solutions for this issue. Regards, Vasu.

Answer №1

To view a pdf document, you'll need to download a specific plugin.

function savePDF(fileName, pdfData){
        try{
            window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function(directoryEntry){
                directoryEntry.getFile(fileName, { create: true }, function(fileEntry){
                    fileEntry.createWriter(function(fileWriter){
                        fileWriter.onwriteend = function(e){
                            cordova.plugins.fileOpener2.open(cordova.file.externalApplicationStorageDirectory + fileName, 'application/pdf',{
                                error: function(e){
                                    console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
                                },
                                success: function () {
                                    console.log('Successfully opened file');
                                }
                            });
                        };

                        fileWriter.onerror = function(e){
                            alert(e);
                        };

                        var blob = new Blob([pdfData], { type: 'application/pdf' });
                        fileWriter.write(blob);

                    }, function onerror(e){
                        alert(e);
                    });
                }, function onerror(e){

                    alert(e);
                });
            },function onerror(e){            
                alert(e);
            });
        }catch(e){
            alert(e);
        }
    }

The code above worked well for me. You can also refer to this link for more information on the plugin.

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

Expressing the relationship between API endpoints in a nested structure

I'm currently working on a REST API using expressjs. There are two api endpoints that I have defined: router.get('/probe/:id', function() {}); router.get('/:id', function() {}); However, I am facing an issue where calling the fir ...

What could be causing the issue of why the null check in JavaScript isn't functioning properly

function getProperty(property) { console.log(localStorage[property]) //Displays “null” if(localStorage[property] == null) { console.log('Null check') return false; } return localStorage[property]; } The log outputs "nu ...

Tips for updating Okta token when there are changes to claims

Currently, my react app is successfully using oauth (specifically okta), but I am encountering a problem. Whenever I modify the claims in the authorization server, the changes are not reflected in the app until the token expires or I perform a logoff and ...

Find the frequency of a specific string within a JSON array

My current task involves working with a stringified array: JSON.stringify(arr) = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","resti ...

Is there a Page Views tracker in sinatra?

Help needed with implementing a page views counter using Sinatra and Ruby. I attempted using the @@ variables, but they keep resetting to zero every time the page is reloaded... Here's an example: Appreciate any advice! ...

Angular material table cell coloring

Here is my current setup: I have an array of objects like this: users : User []; average = 5; compareValue (value){ ...} And I am displaying a table as shown below: <table mat-table [dataSource]="users"> <ng-container matColumnDef= ...

How to deal with jQuery's set val() behavior on SELECT when there is no matching value

Let's say I have a select box like this: <select id="s" name="s"> <option value="0">-</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> </ ...

Issue with React Native, incapable of modifying value

Having trouble updating the title value in my code. It's not updating as expected. Can someone kindly assist in figuring out what's causing the issue? class EditScreen extends Component { render() { return ( <KeyboardAvoidingView ...

The Iframe contains its own scroll feature within the body

I am facing an issue with displaying an Iframe inside a modal. The challenge is that the content within the Iframe varies in height, making it difficult to set a fixed height for the Iframe itself. When I try setting the height to 100%, the result is a 150 ...

NativeScript element isn't showing up

Being relatively new to application development with NativeScript, I find myself in a situation where I need assistance in finding a solution. Drawing from my experience with PHP, I am now looking to create a template for each "page" of the application. Th ...

Using AngularJS to send a 2D array via POST request

How to use Angular HTTP POST $http({ contentType: "application/json; charset=UTF-8", url: "myCSharpMethod", method: "POST", data: myData, // 2D array ( myData[[],[]] ) traditional: true }) .success ...

ThreeJs is known for effortlessly handling an abundance of vertices, far surpassing the number typically found

I came across this code snippet: function loadObject(filePath){ var loader = new THREE.OBJLoader(); loader.load( filePath, function ( object ) { child = object.children[0]; var geometry = new THREE.Geometry().fromBufferGeometry( ch ...

Utilize JSON data loading instead of directly embedding it onto the page for improved website

I've integrated Mention.js into my website, allowing a dropdown list of usernames to appear when "@" is typed in a designated textarea. <textarea id="full"></textarea> While it's functioning well, the examples provided only show how ...

Creating a custom jQuery plugin for exporting data

I am crossing my fingers that this question doesn't get marked as 'already answered' because I have thoroughly searched previous questions and unfortunately, my specific case is not listed anywhere. I have successfully created a jQuery func ...

Combine several objects into one consolidated object

Is there a way to combine multiple Json objects into one single object? When parsing an array from AJAX, I noticed that it logs like this: 0:{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support", ...} 1:{id: "25", user: "Jim ...

After using promise.all, I successfully obtained an array of links. Now, how do I calculate the total number of links in the array?

function verifyAndTallyURLs(linksArray) { let validations = linksArray.map((link) =>{ return fetch(link) .then((response) => { return { webpageURL: response.url, status: response.status, ...

Error in Vue.js: Trying to access properties of an undefined object

My understanding of vue.js is limited, but based on what I know, this code should work. However, when attempting to access the variable in the data property, it seems unable to locate it. data: function() { return { id: 0, clients: [] ...

Deciding on excluding empty key:value pairs from an object for various filtering needs

One of the features in my app allows users to filter results by "blood group" and "city", along with other areas. The information is retrieved from a database using Axios for Vuejs, incorporating query strings within the URL. For example: http://example.co ...

Iterating through a JSON object and an array

I've been attempting to iterate through a JSON object but I'm struggling with it. Below is the JSON object I need to work with. This JSON data will be fetched from another website, and my goal is to loop through it to extract certain details. ...

Adding a new element with Jquery when a dropdown option is selected

What is causing this issue to not function properly? <script> $(document).ready(function(){ $('#custom_field option').click(function(){ $('#custom_field_input').append('<tr><td></td> ...