DEV Community

Discussion on: Generate a PDF from HTML with puppeteer

Collapse
 
anduser96 profile image
Andrei Gatej

I've gone through something similar a few days ago... and it took me a while to figure it out.

Here's my approach, without using puppeteer.
I'm using Vue in this case, but I'm pretty sure the concept is applicable in other cases as well.

// Client
<template>
    // Use CSS to give it full width & height
    <div class="c-file">
        <iframe
            class="c-file__display"
            v-if="src"
            :src="src"
        />
    </div>
</template>

<script>
/* ... */
 async created () {
  const config = { headers: new Headers({
            'Content-Type': 'application/json',
            }), 
            method: "POST",
            body: JSON.stringify(body) // Dynamic data
        }
        fetch(url, config)
            .then(res => res.blob())
            .then(res => {

                const blob =  new Blob([res], { type: 'application/pdf' });
                this.src = URL.createObjectURL(blob, { type: 'application/pdf' })
            })
 }
</script>

  // Server
  /* ... */
   const pdf = require('html-pdf')
   // Generate HTML string
   const content = getPDFContent(req.body.data);


   res.setHeader('Content-Type', 'application/pdf')
   pdf.create(content).toStream( (err, stream) => {
      stream.pipe(res);
   });

Collapse
 
vladejs profile image
Vladimir López Salvador • Edited

html-pdf uses phantomjs under the hood. Where is your app hosted? It didn't work for me on Docker based cloud providers like Now

Collapse
 
anduser96 profile image
Andrei Gatej

The app isn’t hosted (yet), it is all on localhost. I haven’t tried docker nor used cloud providers too often, but I’m really curious about why this approach wouldn’t work.

Please let me know if you find a solution!

Thread Thread
 
mrsaints profile image
Ian L.

We've had success hosting a similar Puppeteer-based converter using Google Cloud Functions (I don't work for Google): github.com/Courtsite/shuttlepdf. There is a bit of latency, but it is a reasonable trade-off for ease of deployment, scalability, and reliability.

Thread Thread
 
vladejs profile image
Vladimir López Salvador

Well, in my case, phantomjs wasn't found by the library on my docker based hosting.

There is a dockerized phantom available but you should have full access the deployment Dockerfile in order to tell it to install on the process.

Overall I would recommend going away from html-pdf because it's not maintained anymore

Thread Thread
 
mrsaints profile image
Ian L. • Edited

Generally speaking, you should probably avoid Phantomjs. With headless Chromium, there really isn't any need for it. Indeed, I think it is no longer maintained.