Changing a DOM structure into pure HTML using JavaScript

Looking to convert some HTML into a PDF file using a service that requires form-data as the payload.

Is there a way to extract HTML from the DOM and save it as a file for use in the payload?

<p>some other HTML</p>
    <div id="content">
      some content
    </div>

    const html = document.getElementById('content').innerHTML;

    const builder = new Blob([html], {type: 'text/html'});

Encountering an issue that states: The format of the request must be of multipart/form-data type.

Answer №1

To adjust the CSS style, you will need to make the changes manually.

      function downloadPDF(){
            var printContents = document.getElementById('content').innerHTML;
            var originalContents = document.body.innerHTML;
            document.body.innerHTML = printContents;
            window.print();
            document.body.innerHTML = originalContents;
        }
    
        function redirect() {
            window.location.href = "/user-landing-page";
    
        }

Answer №2

After some troubleshooting, I managed to get it to work. Here is the solution I came up with - Please note that this code is specific to Angular 8, although it closely resembles vanilla JavaScript

const formData = new FormData();
const html = this.myInput.nativeElement.innerHTML;
const htmlWithDoc = '<!DOCTYPE html><html lang="en"><head><title>Document</title></head><body>' + style + html + '</body></html>';

formData.append('blob', new Blob([htmlWithDoc], {type: 'text/html'}));

this._dataService.htmlToPdf(formData).subscribe(response => {
  this.saveToFileSystem(response);
});

private saveToFileSystem(response) {
 const filename = 'test'; // parts[1].split('=')[1];
 const blob = new Blob([response], { type: 'application/pdf' });
 saveAs(blob, filename);
}

htmlToPdf(payload) {
    const location = 'my API';
    return this._http.post(
      location,
      payload,
      {responseType: 'blob'}
      ).pipe(res => res);
  }

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

Encountered a runtime error while trying to insert a list item <li> into a paragraph <p> element

Take a look at this code snippet: <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication18._Default" %> <!DOCTYPE html> <html> <body> <p id="someId"></p& ...

Is there a way to change an ISO 8601 date into the format '/Date(1525687010053)/' using JavaScript?

Is there a way to convert a date value that is formatted as 9999-12-31T00:00:00Z to the format /Date(1525687010053)/ using javascript? I tried implementing the following code, but it doesn't seem to be working: var datevalue = '9999-12-31T00:00 ...

I'm encountering issues with this code for a dice game. It's strange that whenever I click the roll dice button, it disappears. Additionally, linking an .css sheet seems to cause the entire page to

I'm currently working with two separate codes: one for HTML and the other for JavaScript. I am facing an issue where the button keeps disappearing when I try to add any CSS styling to it. Even a basic CSS file seems to override everything else and lea ...

Ways in which the user can modify the city name within this inquiry

I am just beginning to learn JavaScript and I am struggling to figure out how to allow the user to change the city name in this request. Currently, it works when I manually input the city name in the code (e.g., askWeather.open("GET", "url.../london")), bu ...

Switch back and forth between adding and removing a table row using jQuery

Currently, I am developing a drop-down feature for a table that populates its data using MySQL. The functionality involves creating a new table row below the current one when a user clicks a button. However, instead of generating multiple new rows each tim ...

What is the process of incorporating a lowercase normalizer into an Elasticsearch mapping object?

I'm attempting to incorporate a normalizer with a lowercase option into my mapping object, as detailed in the official Elasticsearch documentation Below is an example of my mapping object: const schema = { date: { type: 'date' ...

Can we stub these types of functions in any manner?

One file named helperFunction.js contains the following code: module.exports = (arg1, arg2) => { \\function body } To use this function in another file named file.js, you can simply call it like this: let helperFunction = require(' ...

What is the process for assigning a background color to a specific option?

Trying to create a dropdown menu with various options and colors. Managed to set background colors for each option, but once an option is selected, the background color disappears. Is there a way to fix this issue? See my HTML example below: <select> ...

Implement Material-UI Higher Order Components in a Class-based Component

I'm in the process of incorporating material UI into my class component rather than converting everything to Hooks. I'm unsure which approach would be simpler, utilizing Hooks or adapting what I currently have. https://material-ui.com/styles/bas ...

After generating the token, where is the appropriate place to define the authorization header?

I am currently working on implementing a security system based on tokens. The challenge I am facing is determining the appropriate location to set the authorization header after generating it, in order to validate it across all of my different routes. Belo ...

The function Sync in the cp method of fs.default is not a valid function

When attempting to install TurboRepo, I encountered an issue after selecting npm. >>> TURBOREPO >>> Welcome to Turborepo! Let's get you set up with a new codebase. ? Where would you like to create your turborepo? ./my-turborepo ...

JavaScript unable to access elements during page loading

I am facing an issue with the following code: var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); v ...

What are the drawbacks of using JavaScript to load a series of images?

Currently, I am facing an issue with the loading speed of a sequence of images on my website. The javascript code I have implemented to cycle through 50 images works perfectly fine locally but becomes slow and buggy when the site is live. Despite the image ...

Accessing a template object in JavaScript using querySelector

Essentially, I am trying to querySelect a <template> from JavaScript but constantly receiving null as the result. JavaScript code: class MyImportWebcomponent extends HTMLElement { constructor() { super(); } connectedCallback() { ...

No files located by the server

My experience with writing a basic express script to serve a webpage with embedded Javascript has been quite frustrating. The server seems to struggle finding the files I provide, and what's even more aggravating is that it sometimes works but then su ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...

Using jQuery to Toggle the Height of Multiple Sections with a Single Function

I've got three different sections, each with varying heights and a simple structure like this: <section> <h2>My heading</h2> </section> What I want is for these sections to display at first, but then shrink dow ...

Using AJAX to populate a dropdown menu in a CodeIgniter application

I'm having an issue with using AJAX to populate a dropdown option. Here is the JavaScript code I am using: <script type="text/javascript"> $(document).ready(function(){ $("#sepatu").click(function(e){ e.preventDefault() ...

Guide to adding customized CSS and JavaScript to a specific CMS page on Magento

I'm trying to incorporate a lightbox for video playback on a specific page of my CMS. I've placed my CSS file in JS/MY THEME/JQUERY/PLUGIN/VENOBOX/CSS/myfile.css and the JS files in JS/MY THEME/jquery/plugins/venobox/js/myfile.js, but it doesn&ap ...

Organizing a Vue.js SPA project: Implementing Vuex store and API calls efficiently

Here is how I have organized the structure of my Vue app: components/ article/ AppList.vue common/ AppObserver.vue NoSSR.vue layout/ AppFooter.vue AppHeader.vue ui/ AppButton. ...