Adding a PDF to the email composer feature in an Ionic app

I am facing an issue with attaching a blob PDF file to an email composer. Despite my efforts, it does not seem to work as expected.

function generatePdf(reportData){
         return $q(function(resolve, reject) {
            var docDefinition = createDocumentDefinition(reportData);
            var pdfDoc = pdfMake.createPdf(docDefinition)
            .getBuffer(function(buffer){
                var utf8Array = new Uint8Array(buffer); // Convert to UTF-8... 
                binaryArray = utf8Array.buffer; // Convert to Binary...
                $cordovaFile.writeFile(cordova.file.dataDirectory, "file.pdf", binaryArray, true)
                .then(function (success) {
                   alert('PDF created'); 
                console.log("PDF created");
                }, function (error) {
                console.log("Error");
                });
            });
        });
    }

This piece of code functions correctly and triggers an alert when the PDF is successfully created.

pdfGenerator.generatePdf(reportbody)
      .then(function(pdf){
        $ionicLoading.hide();
        var fileBlob = new Blob([pdf], {type: 'application/pdf'});
        $scope.pdfUrl = URL.createObjectURL(fileBlob);
            var email = {
           to: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117c7069517c64626574637c707f7f3f7574">[email protected]</a>',
           cc: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b4e5942404a6b465e585f4e59464a4545054f4e">[email protected]</a>',
           bcc: ['<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c060304022c080309420f0301">[email protected]</a>', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86ece7e8e3c6e2e9e3a8e5e9eb">[email protected]</a>'],
           attachments: [$scope.pdfUrl],
           subject: 'Cordova Icons',
           body: 'How are you? Nice greetings from Leipzig',
           isHtml: true
         };

        $cordovaEmailComposer.open(email).then(null, function () {
          // user cancelled email
        });
      },function(error){
        console.log(error);
      });

When I check the cordova.file.dataDirectory in the console, it returns a cdvfile:// path instead of the native path. Therefore, I am unsure how to properly attach the file to an email.

Answer №1

Great news! I was able to solve the issue I was facing. Below is the code snippet that worked for me. Hopefully, it will be useful for others as well.

function generatePDF(data){
    return $q(function(resolve, reject) {
        var documentDefinition = createDocumentDefinition(data);
        var pdfDoc = pdfMake.createPdf(documentDefinition)
        .getBuffer(function(buffer){
            var utf8Array = new Uint8Array(buffer); // Convert to UTF-8... 
            binaryData = utf8Array.buffer; // Convert to Binary...
            resolve(binaryData);
        });
    });
}

In the controller section,

pdfGenerator.generatePDF(reportBody)
    .then(function(pdfData){
        $ionicLoading.hide();
        $cordovaFile.writeFile(cordova.file.externalApplicationStorageDirectory,'mydoc.pdf',pdfData,true).then(function(success){
            console.log("File created");
        })
        var email = {
           to: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d606c754d60787e79687f606c6363236968">[email protected]</a>',
           cc: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="791c0b10121839140c0a0d1c0b14181717571d1c">[email protected]</a>',
           bcc: ['<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bad0d5d2d4faded5df94d9d5d7">[email protected]</a>', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e040f000b2e0a010b400d0103">[email protected]</a>'],
           attachments: [externalApplicationStorageDirectory+'mydoc.pdf'],
           subject: 'Cordova Icons',
           body: 'How are you? Nice greetings from Leipzig',
           isHtml: true
         };

        $cordovaEmailComposer.open(email).then(null, function () {
          // user cancelled email
        });
},function(error){
    console.log(error);
});

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

The angular-bootstrap-datetimepicker does not automatically close after selecting a date

I am currently utilizing the datepicker from https://github.com/dalelotts/angular-bootstrap-datetimepicker. However, I have noticed that the datepicker control does not automatically close... <div class="dropdown-toggle my-toggle-select" id="dLabel1" r ...

Unexpected lag causing delays in jQuery animations

I am attempting to implement a "hover" effect using jQuery. Everything seems to be working fine, except for a strange delay that occurs only the first time the complete callback is triggered - oddly enough, this is the only instance where it reaches the pr ...

The synergy between HTML and JavaScript: A beginner's guide to frontend coding

I have primarily focused on server-side development of enterprise applications (Java EE, Spring framework). However, I am now exploring client-side technologies for better understanding (not necessarily to become an expert). I have studied HTML and CSS th ...

Steps for integrating Stanford's NLP into a web application

I have successfully developed a project utilizing Stanford's NLP API and models. Now, I am looking to integrate this Java-based project onto the web. After seeing the demo provided by Stanford-NLP, I am curious about the process they use to achieve th ...

Change the background color of the accordion header

Is there a way to dynamically change the color of an accordion based on the status of the current item in the list? I'm trying to implement something like ng-class="{status: item.status}" (where I have set testClass: true) The issue I'm facing ...

Collection of components displayed in a row - Bootstrap 4

In order to meet the requirement, the label must be positioned above the input element, and the group consisting of each label and input element should be displayed inline with one another. I have managed to achieve this using the following code snippet, ...

You cannot define headers once they have been sent to the client. If you encounter a NextJS redirect issue, consider using res

I encountered an error when redirecting to a link from NextJS -> _app.js -> getInitialProps. I am trying to cache the last user language in cookies and redirect to it when the page is reloaded. It's working and the user is redirected, but I&apos ...

Encountering a problem when providing an array as a parameter to the setData

I am currently working on a project to create a dynamic Pie Chart that can switch between two different data series using a button. Initially, I had success passing values directly to the setData() function when the button is clicked, as shown in this wor ...

How can I execute route-specific middleware in advance of param middleware in Express v4?

Let me share a unique situation in my routing setup where I need to trigger a middleware before the parameter middleware is executed: router.param('foo', function (req, res, next, param) { // Accessing the param value ... next() }) router ...

Transferring window object between different pages

When you navigate from Page A to Page B, and then to Page C, the connection between all three pages can be utilized for efficient page management. For instance, once Page C is fully loaded, Page A can be automatically closed. To seamlessly transition from ...

Instructions on retrieving basic array information from Firebase and fetching it

Being a beginner, I am currently focusing on learning Firebase instead... Here is a simple HTML code snippet that I created: <div class="container" id="msgs"> </div> I am trying to load data from F ...

Animating elements on a webpage can be achieved by using both

Is there a way to create an animation that moves objects based on button clicks? For example, when the "Monday" button is pressed, the object with the correct color will move down. If any other button like "Tuesday" is clicked, the previous object will mov ...

What is the process for entering a menu and displaying the information without storing it in the database?

https://i.sstatic.net/N8MnO.png In my project, I have a form input menu and quantity section (highlighted by the yellow line in the image). Once the user submits the data, it is displayed on a table (highlighted by the red line in the image), but it is no ...

MongoDB was successfully updated, however the changes are not being displayed on the redirected

I have implemented the delete action in Node/Express as a web framework, where it is structured within a higher-level route: .delete((req, res) => { db.collection('collection-name').findOneAndDelete({ topic_title: req.body.topic_title}, ...

What are some ways to connect my CSS styles without encountering a MIME error?

Working on a Nodejs - Express - Vanillajs project, I encountered an issue when testing my routes. The index page failed to load CSS, displaying the following error message: Refused to apply style from 'http://localhost:3000/public/css/bootstrap.min. ...

transmitting an array from JavaScript to PHP

Struggling with passing an array from JavaScript to PHP for a school assignment. I'm still learning and can't seem to figure out what's missing. Any help would be greatly appreciated. This is the code I've tried: if(bets.length > ...

Fill various dropdowns with a list or array of values discreetly without displaying the populated values on the visible interface

I have an array with values 1,2,3,4. Using an add function, I am able to create multiple dropdowns. By default, the first dropdown always has a value of one when initially set up. When we press add and populate the second dropdown with values 2,3,4, tho ...

Electron generates a unique landing page for your first launch

Can you help me create a feature on a webpage that only appears once and then never shows again? Similar to the "Never show me again" checkbox in Visual Studio Code upon first launch. ...

Counting the number of PHP inputs in a field

Hello, I am using a PHP script from Steve Dawson's website. To display the output on my HTML page, I am utilizing this AJAX script: <script> $.ajax({ type:'GET', url:'http://www.solariserat.se/count.php', data: ...

What is the best way to prevent Firefox from storing the data of a textarea in the local environment?

I have been developing a website locally, and I have noticed that there are numerous <textarea> elements present on the site. One issue I am facing is that whenever I reload the site, the content within the <textarea> remains the same. This pe ...