novato
novato

Reputation: 173

Generate pdf with pdfmake in iframe tag

I have this JS and i would do like to generate pdf in a iframe tag using this js (made with pdfmake)

  function start(){
  var docDefinition = {
  content: [
    {
      table: {
       multiple pages

        headerRows: 1,
        widths: [ '*', 'auto', 100, '*' ],

        body: [
          [ 'First', 'Second', 'Third', 'The last one' ],
          [ 'Value 1', 'Value 2', 'Value 3', 'Value 4' ],
          [ { text: 'Bold value', bold: true }, 'Val 2', 'Val 3', 'Val 4' ]
        ]
      }
    }
  ]
  };

   pdfMake.createPdf(docDefinition).open();

}

Show the pdf in this iframe:

  <frameset cols="25%,*,25%">
      <frame src="">
  </frameset>

When i click in this button:

<button type="submit" name="save" class="btn btn-default" onclick="start();">Savw</button>

thanks.

Upvotes: 2

Views: 4450

Answers (2)

Anis Saddoud
Anis Saddoud

Reputation: 9

    const targetElement = document.querySelector('#iframeContainer');
    const pdfDocGenerator = pdfMake.createPdf(docDefinition);
    pdfDocGenerator.getBuffer(function (buffer) {
        const dataUrl = URL.createObjectURL(new Blob([buffer], {
            type: "application/pdf"
        }));
        const iframe = document.createElement('iframe');
        iframe.src = dataUrl;
        iframe.width = "300px";
        iframe.height = docDefinition.pageSize.height;
        targetElement.appendChild(iframe);
 
        iframe.contentWindow.print();
    });

Upvotes: 0

Raven-Blue Dragon
Raven-Blue Dragon

Reputation: 614

I think my setup is slightly different but try this - something similar worked for me.

First, put an id on <frame src="" id="foo"> then replace

// pdfMake.createPdf(docDefinition).open();
var doc = pdfMake.createPdf(docDefinition);
var f = document.getElementById('foo');
var callback = function(url) { f.setAttribute('src',url); }
doc.getDataUrl(callback, doc);

The getDataUrl function runs the callback function with the generated url as argument. That callback should set the src attribute on your frame. My callback also includes console.log(url); so I can see what's happening.

Upvotes: 6

Related Questions