Search code examples
javascriptform-data

Convert DOM to native HTML in javascript


I need to send some HTML to a service that converts HTML to PDF. the service accepts a payload that is form-data (a file).

how can I take some of the HTML from the DOM, and convert it into a file, which I can use in my 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'});

I get this error The format of the request must be of multipart/form-data type.


Solution

  • I got it working here is the solution - NOTE This is an Angular 8 solution, but vanilla javascript is pretty close

    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);
      }