Is it possible to attach a PDF file using just the PDF URL?

My current project involves an ionic application that performs calculations based on user inputs. Once the calculations are complete, the results are converted into a PDF using the generatePDF API call. Additionally, there is a requirement to email the generated PDF using the sendMail API, with enctype='multipart/form-data' set in the header.

I now have the URL for the generated PDF from the response of the generatePDF API. How can I attach this PDF to the email that I need to send?

If anyone has any insights or solutions, your help would be greatly appreciated!

Answer №1

Shoutout to @MissakBoyajian for the assistance! Here's how I tackled the issue:

First, I installed the File Transfer and File plugins for Ionic native.

this.platform.ready().then(() => {

      const fileTransfer: FileTransferObject = this.transfer.create();
      const pdfLocation = this.pdffile; // pdffile is the PDF URL obtained from the generatePDF API response

      fileTransfer.download(pdfLocation, this.storageDirectory + "filename.pdf").then((entry) => {
        const alertSuccess = this.alertCtrl.create({
          title: `Download Succeeded!`,
          subTitle: `PDF successfully downloaded to: ${entry.toURL()}`,
          buttons: ['Ok']
        });

        alertSuccess.present();

        this.file.readAsDataURL(this.storageDirectory, 'filename.pdf')
        .then((datafile) =>{
          this.attachpdf(id,datafile);
        })
        .catch((err) =>{
          console.log("Error: "+err);
        });

      }, (error) => {

        const alertFailure = this.alertCtrl.create({
          title: `Download Failed!`,
          subTitle: `PDF download unsuccessful. Error code: ${error.code}`,
          buttons: ['Ok']
        });
        alertFailure.present();
      });
    });

I utilized a function I found through research to convert base64 data into a blob.

public dataURItoBlob(dataURI) {
    // logic to convert dataURI to blob...
 }

After that,

public attachpdf(emailid,filetoattach){
     let headers = new Headers();
    headers.append(...);
    headers.append('enctype','multipart/form-data');

    var blob = this.dataURItoBlob(filetoattach);

    var data ={... };

    var formData = new FormData();
    formData.append("data",JSON.stringify(data));
    formData.append("doc",blob);

    this.http.post('sendMail API',formData, {headers: headers})
    .map(res => res.json())
    .subscribe(results => { 
      ...
    },
    error=>{
      ..
    }
    )
  }

Success at last!

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

Firebase has flagged the Google Authentication process with a message stating: Entry denied: The request made by this application

I have connected my domain to Firebase authentication and granted authorization for authentication access. If you want to test it out, feel free to visit this link signInWithPopup(auth, provider) .then((result) => { // This provides a Google Acc ...

Utilizing dynamic JavaScript values in URL parameters before sending

When it comes to online payments, I need to send parameters to a specific URL. The calculations on my website are done in JavaScript, but the online payment company requires PHP parameters like MD5 hashing. To address this, I attempted to create a hidden ...

Anyone have any (placeholder) fetch URL parameters that require some time to resolve?

Can anyone share any fetch URL parameters that result in a loading time of roughly 5 seconds or longer for the promise to resolve when using fetch(urlArgument);? I'm eager to experiment and learn more. ...

Utilize Javascript to refine JSON data strings

Currently, I am tackling a small project and facing a minor JS issue. The JSON string that I have looks like this: var jsObj = { "templates": { "form0": { "ID": "MyAlertNew", "isVisible": "true", ...

Angular 6: TypeError - The function you are trying to use is not recognized as a valid function, even though it should be

I'm currently facing a puzzling issue where I'm encountering the ERROR TypeError: "_this.device.addKeysToObj is not a function". Despite having implemented the function, I can't figure out why it's not functioning properly or callable. ...

Issue encountered while attempting to start a project using Ionic

After cloning a repository using the git clone command and running npm install, I encountered a message with warnings about vulnerabilities: npm WARN deprecated" and at the end it says "55 vulnerabilities (3 low, 12 moderate, 36 high, 4 critical) To addres ...

The concept of recursively exporting modules in Node.js modules

Looking for a way to recursively export all .hbs files in a NodeJS 14+ project main JS. I attempted the following: module.exports = () => ({ partial : __dirname + "/../partial/**.hbs", helper : __dirname + "/../helper/*.js" } ...

Creating a function within a module that takes in a relative file path in NodeJs

Currently, I am working on creating a function similar to NodeJS require. With this function, you can call require("./your-file") and the file ./your-file will be understood as a sibling of the calling module, eliminating the need to specify the full path. ...

Toggle checkbox feature in Bootstrap not functioning properly when placed within ng-view

When attempting to embed a bootstrap toggle checkbox within <ng-view></ng-view>, an issue arises where a regular HTML checkbox is displayed instead of the expected bootstrap toggle. Strangely, the same checkbox functions as a bootstrap toggle w ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

The concept of looping within Angular directives

Exploring various recursive angular directive Q&A's can lead to different solutions that are commonly utilized: Creating HTML incrementally based on runtime scope state Check out this example [Stack Overflow discussion] Here's another exa ...

Step-by-step process for adding .env file and hosting React app on Netlify

My React application is currently on GitHub, and I am looking to host it on Netlify. I am uncertain about the placement of my .env file, which holds all the necessary API credentials. ...

When working on my asp.net webform, I incorporated an AgreementCheckBox along with a CustomValidator. However, I encountered an issue where the error message

Code for AgreementCheckBox: <asp:CheckBox ID="AgreementCheckBox" runat="server" ForeColor="Black" Text="Please agree to our terms and conditions!" /> Code for AgreementCustomValidator: <asp:CustomValidator ID="AgreementCustomValidator" runat=" ...

Is there a way to adjust the padding temporarily?

Important Note: Despite the misleading title of my question, it doesn't accurately reflect my actual query (sort of). Below is the code snippet in question: .one{ background-color: gray; } .two{ padding: 20px; } <div class = "one"> < ...

Analyzing vast datasets from contrasting perspectives

Looking for a way to compare two different data storages that contain the same data. The data in question is: const object1 = { "name": "John", "age": "30", "height": "180 cm", "stand ...

Tips for fixing the "Module not found" issue when executing a Node.js application

My Node.js application is encountering an issue when I try to run it using the npm start command. It appears to be failing to locate the entry point file, which results in a "Cannot find module" error. Here's the error message I'm seeing: > P ...

Is there a way for me to identify the value within useCallback without any intermediaries?

How can I ensure that console.log('success') is triggered when the ids of myFood[myFood.length - 1]?.id and viewableItems[viewableItems.length - 1]?.item?.id match? Despite both values being equal, there seems to be an issue preventing console.l ...

The validation for the start and end dates in the datepicker is not functioning properly when

I have integrated a bootstrap date picker into my website. However, I am encountering an issue where the end date validation does not update when I change the start date after the initial selection. <script type="text/javascript" src="htt ...

A technique for simultaneously replacing two values in a single call to the replace function

Is there a way to replace two or more instances at once with a single replace call? I have not attempted anything yet, as I am unsure of how to proceed. let links = { _init: "https://%s.website.com/get/%s", } Here, you can see that I have a link wi ...

What steps can I take to ensure that the information in my Cart remains consistent over time?

I recently built a NextJS application integrating the ShopifyBuy SDK. My implementation successfully fetches products from the store and displays them to users. Users can navigate to product pages and add items to their cart. However, I encountered an iss ...