node-html-pdf: Error: write EPIPE

I’m using nunjucks to render a template into a string, i then try to convert that html to a pdf file however everytime i get this error:

Error: write EPIPE
    at errnoException (net.js:905:11)
    at Object.afterWrite (net.js:721:19)

Here is the code i use to create the pdf file:

                        nunjucks.render(path.join(__dirname, '../views/mail/receipt.html'), {
                                __: res.__,
                                query: req.query,
                                payment: payment
                            }, function(err, html) {
                                if (err) {
                                    next(err);
                                }
                                htmlPdf.create(html, {
                                    type: 'pdf'
                                }).toBuffer(function(erro, fileBuffer) {
                                    // Code never gets this far, errors out before it happens and the error object is still null.
                                    if (erro) {
                                        next(erro);
                                    }

                                    var transporter = nodemailer.createTransport({
                                        host: config.email.host,
                                        port: config.email.port,
                                        secure: config.email.secure
                                    });

                                    transporter.sendMail({
                                        from: config.email.from,
                                        to: payment.receipt_email,
                                        subject: res.__({
                                            phrase: 'Receipt_Email_Subject',
                                            locale: payment.lang
                                        }),
                                        attachments: [{
                                            filename: 'receipt.pdf',
                                            content: fileBuffer,
                                            contentType: 'application/pdf'
                                        }],
                                        text: 'test'
                                    }, function(error, info) {
                                        if (error) {
                                            next(error);
                                        }

                                        res.json(info);
                                    });
                                });
                            });

Here is the HTML string that is generated by nunjucks, not the most readable i know but figured i should post it like it is instead of trying to make it prettier

<!DOCTYPE html>\n<html lang="en">\n    <head>\n        <meta charset="utf-8">\n        <meta content="IE=edge" http-equiv="X-UA-Compatible">\n        <meta content="width=device-width, initial-scale=1" name="viewport">\n        <title>Snerpa WiFi Receipt</title>\n        <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"\n            rel="stylesheet">\n    </head>\n    <body>\n        <div class="container">\n            <div class="row">\n                <div class="col-xs-6 col-sm-5 col-md-4 col-lg-3">\n                    <img src="http://wifi.snerpa.is/assets/images/wifi_logo.png" class="img-responsive" alt="WiFi Logo">\n                </div>\n            </div>\n            <div class="row">\n                <div class="col-xs-12">\n                    <div class="invoice-title">\n                        <h2>Invoice</h2>\n                        <h3 class="pull-right">Pöntun # 0575741</h3>\n                    </div>\n                    <hr>\n                        <div class="row">\n                            <div class="col-xs-6">\n                                <address>\n                                    <strong>Greiðslumáti:</strong><br>\n                                    VISA 999999******9999<br>\n                                    grimurd@snerpa.is\n                                </address>\n                            </div>\n                            <div class="col-xs-6 text-right">\n                                <address>\n                                    <strong>Dagsetning:</strong><br>\n                                    03.06.2015<br><br>\n                                </address>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n                <div class="row">\n                    <div class="col-md-12">\n                        <div class="panel panel-default">\n                            <div class="panel-heading">\n                                <h3 class="panel-title"><strong>Samantekt</strong></h3>\n                            </div>\n                            <div class="panel-body">\n                                <div class="table-responsive">\n                                    <table class="table table-condensed">\n                                        <thead>\n                                            <tr>\n                                                <td><strong>Vara</strong></td>\n                                                <td class="text-center"><strong>Verð</strong></td>\n                                                <td class="text-center"><strong>Magn</strong></td>\n                                                <td class="text-right"><strong>Samtals</strong></td>\n                                            </tr>\n                                        </thead>\n                                        <tbody>\n                                            \n                                            <tr>\n                                                <td>Snerpa WiFi 1 Klst Aðgangur</td>\n                                                <td class="text-center">€1</td>\n                                                <td class="text-center">1</td>\n                                                <td class="text-right">€1</td>\n                                            </tr>\n                                            \n                                        </tbody>\n                                    </table>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n                <style>\n                    .invoice-title h2,\n                    .invoice-title h3 {\n                        display: inline-block;\n                    }\n\n                    .table> tbody> tr> .no-line {\n                        border-top: none;\n                    }\n\n                    .table> thead> tr> .no-line {\n                        border-bottom: none;\n                    }\n\n                    .table> tbody> tr> .thick-line {\n                        border-top: 2px solid;\n                    }\n                </style>\n            </body>\n        </html>\n

I’ve been stuck at this for hours and can’t see that im doing anything wrong, any ideas?

About this issue

  • Original URL
  • State: open
  • Created 9 years ago
  • Comments: 53 (3 by maintainers)

Most upvoted comments

sudo apt-get install libfontconfig

I was getting the EPIPE error as well with an app running in docker containers on ec2s. In my case, it turned out not to be the fontconfig lib, but rather needing to npm rebuild phantomjs-prebuilt in my Dockerfile.

for the record, yum install fontconfig if you are using centOS

sudo apt-get install libfontconfig fixed it for me, thanks @sovanna!

Same, getting it for node 10 as well on AWS Lambda

Started getting this error after upgrading lambda environment from node 8 to node 10.x. Anyone know how to fix this on AWS lambda?

Went back to node 8

How can i fix this error on lambda functions ? Below is error i see in CloudWatch logs for my function

Error: write EPIPE at exports._errnoException (util.js:1018:11) at WriteWrap.afterWrite (net.js:800:14)
Error: write EPIPE
at exports._errnoException (util.js:1018:11)
at WriteWrap.afterWrite (net.js:800:14)

My code for pdf creation is below

const templatePath = __dirname+'/templaate.hbs';
fs.readFile(templatePath, {encoding: 'utf-8'}, function (error, html) {
  if(!error){
    pdf.create(html, options).toBuffer(function(err, buffer){
      //Upload to s3 bucket from received buffer
    });
  }
});

Can anyone help with this?

Not sure if this helps but I started encountering this exact same EPIPE issue while attempting to troubleshoot my rendering issue.

It was recommended elsewhere to add the following lines to the options but doing so is what causes the EPIPE issue for me. Removing these lines resolves the EPIPE issue.

“phantomPath”: “./node_modules/phantomjs/bin/phantomjs”, “phantomArgs”: [],

Anyone coming here for AWS lambda node 10 environment, After some investigation, I found that in case of AWS lambda, the issue is the environment and not node itself. Many OS shared libraries and fonts available in Lambda Node 8 environment are not present in Lambda Node 10 environment. (libXrender, libpng, libjpeg etc)… This is the cause of error.

There is a way to add these shared libraries into the lambda layer which would fix the problem The first comment in this article explains how to do it. https://tech.mybuilder.com/compiling-wkhtmltopdf-aws-lambda-with-bref-easier-than-you-think/

Provide my solution: Hope to help more people

The problem is on Linux OS You can use fc-list first to check if there is a font library installed

If the instruction is invalid, you can install the font according to the version

Ubuntu / Debian sudo apt-get install libfontconfig

Centos / Redhat sudo yum install fontconfig

I had the same error

Error: write EPIPE
    at errnoException (net.js:905:11)
    at Object.afterWrite (net.js:721:19)

followed by this one

Error creating pdf [Error: /opt/app_name/app/programs/server/npm/npm-container/node_modules/html-pdf/node_modules/phantomjs/lib/phantom/bin/phantomjs: 4: /opt/app_name/app/programs/server/npm/npm-container/node_modules/html-pdf/node_modules/phantomjs/lib/phantom/bin/phantomjs: Syntax error: Unterminated quoted string

It is caused by phantomjs’s executable being of a wrong architecture. If you have this error you can use this to check if the binary matches your system.

$ file /path/phantomjs

Running npm install on html-pdf should fix this.

I assume this was a syntax error. So I’m closing this for now.

i am facing same issue but still not able to get the answer Error: write EPIPE 0|hb Api | at afterWrite Dispatched (internal/stream_base_commons.js:156:25) 0|hb Api | at writeGeneric (internal/stream_base_commons.js:147:3) 0|hb Api | at Socket._writeGeneric (net.js:787:11) 0|hb Api | at Socket._write (net.js:799:8) 0|hb Api | at writeOrBuffer (internal/streams/writable.js:358:12) 0|hb Api | at Socket.Writable.write (internal/streams/writable.js:303:10) 0|hb Api | at PDF.PdfExec [as exec] (/var/www/html/hbv2Api/node_modules/html-pdf/lib/pdf.js:141:15) 0|hb Api | at PDF.PdfToFile [as toFile] (/var/www/html/hbv2Api/node_modules/html-pdf/lib/pdf.js:83:8) 0|hb Api | at /var/www/html/hbv2Api/app/helper/pdfHelper.js:6:39 0|hb Api | at new Promise (<anonymous>) 0|hb Api | at generatePdf (/var/www/html/hbv2Api/app/helper/pdfHelper.js:5:16) 0|hb Api | at exports.getInvoice (/var/www/html/hbv2Api/app/modules/controllers/orders.controller.js:1465:13) 0|hb Api | at processTicksAndRejections (internal/process/task_queues.js:95:5) { 0|hb Api | errno: -32, 0|hb Api | code: ‘EPIPE’, 0|hb Api | syscall: ‘write’ 0|hb Api | }

libfontconfig

Any idea what exactly libfontconfig is used for?

I got this issue running in Docker. Solution: I had to update my Dockerfile to:

FROM ubuntu:16.04
RUN apt-get update -qq && \
    apt-get upgrade -yqq && \
    apt-get install curl -yqq && \
    curl -sL https://deb.nodesource.com/setup_lts.x | bash - && \
    apt-get install  nodejs -yqq && \
    apt-get install bzip2 -yqq && \
    apt-get install build-essential chrpath libssl-dev libxft-dev libfreetype6-dev libfreetype6 libfontconfig1-dev libfontconfig1 -yqq

WORKDIR /app
COPY . .


# RUN npm install
RUN npm install --only=prod
CMD ["node", "keystone.js"]

Indeed, PhantomJS is by default compiled for the platform where npm install is ran. This causes issues when npm install is ran on a different platform than where it is being used (e.g. when you build node_modules locally on your Windows/MacOS environment and then push it to an Linux environment).

PhantomJS addresses this issue on the GitHub README.md here.

For me setting the environment variables to:

PHANTOMJS_PLATFORM="linux"
PHANTOMJS_ARCH="x64"

before running npm install fixed the issue as I was running the code on AWS Lambda (linux x64) but compiling it on MacOS.

I have the same problem on Windows and cant get html-pdf to work after packing to asar. Anyone found a workaround on this issue?

same here windows – though this happened after updating to gulp4. it worked in gulp3.

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at Socket._writeGeneric (net.js:768:25)
    at Socket._write (net.js:787:8)
    at doWrite (_stream_writable.js:396:12)
    at writeOrBuffer (_stream_writable.js:382:5)
    at Socket.Writable.write (_stream_writable.js:290:11)
    at Socket.write (net.js:711:40)
    at PDF.PdfExec [as exec] (C:\Users\gsdajs1\Repos\dri-dtm-config\node_modules\html-pdf\lib\pdf.js:141:15)
    at PDF.PdfToBuffer [as toBuffer] (C:\Users\gsdajs1\Repos\dri-dtm-config\node_modules\html-pdf\lib\pdf.js:44:8)
    at DestroyableTransform._transform (C:\Users\gsdajs1\Repos\dri-dtm-config\node_modules\gulp-html-pdf\index.js:19:8)
    at DestroyableTransform.Transform._read (C:\Users\gsdajs1\Repos\dri-dtm-config\node_modules\readable-stream\lib\_stream_transform.js:182:10)

installing phantomjs-prebuilt globally did not resolve this, hoped it would. ~still stuck~.

update! (windows) removing phantomPath from pdf(options) worked! (after a global install pf phantom, not sure if related)

This will work 100 % – follow this it worked for me …

https://www.vultr.com/docs/how-to-install-phantomjs-on-ubuntu-16-04

One more solution:

Update selinux policy by changing phantomjs file to bin_t type semanage fcontext -a -t bin_t '/opt/phantomjs/bin/phantomjs

After adding new type to selinux policy you need to update the file permissions sudo /sbin/restorecon -v /opt/phantomjs/bin/phantomjs

Now you need to allow httpd daemon to change its resource limits by setting the boolean sudo setsebool -P httpd_setrlimit 1

Hope it helps ( :

“Generating PDF with Electron.js” https://medium.com/@ishwar.rimal/generating-pdf-with-electron-js-31b59ac93249 On Tue 17 Apr, 2018, 2:22 PM Tommy Riska, notifications@github.com wrote:

I have the same problem on Windows and cant get html-pdf https://www.npmjs.com/package/html-pdf to work after packing to asar. Anyone found a workaround on this issue?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/marcbachmann/node-html-pdf/issues/35#issuecomment-381906293, or mute the thread https://github.com/notifications/unsubscribe-auth/AQre_sOeBANyBy0gpupkCeiC7XVRXh94ks5tpa1NgaJpZM4E2tGm .

I had this problem in Docker as well, I was binding the source code into the container as a volume (for easy development). The problem was that I had built the original npm packages on the host and mapped them into the container (it seems that even npm didn’t rebuild the needed packages for the container).

The solution was similar to @kevinbror except I had to rebuild everything from inside the container with $ npm rebuild

UPDATE: solved my issue after a reboot. Yep, you read that right. 🔫

I don’t know if the error is the same, but it surely looks very related to how the interaction with phantomjs is made: I am spawning my Node process (that uses node-html-pdf) from a C# application, and it looks like child.stdin.write fails with EPIPE.

Error: write EPIPE
    at exports._errnoException (util.js:746:11)
    at Socket._writeGeneric (net.js:690:26)
    at Socket._write (net.js:709:8)
    at doWrite (_stream_writable.js:301:12)
    at writeOrBuffer (_stream_writable.js:288:5)
    at Socket.Writable.write (_stream_writable.js:217:11)
    at Socket.write (net.js:634:40)
    at PDF.module.exports.PDF.exec (C:\Users\fpontillo\AppData\Roaming\npm\node_modules\my-module\node_modules\html-pdf\lib\pdf.js:136:26)
    at PDF.module.exports.PDF.toStream (C:\Users\fpontillo\AppData\Roaming\npm\node_modules\my-module\node_modules\html-pdf\lib\pdf.js:66:19)
    at Promise.post (C:\Users\fpontillo\AppData\Roaming\npm\node_modules\my-module\node_modules\q\q.js:1161:36)
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: spawn phantomjs ENOENT
    at exports._errnoException (util.js:746:11)
    at Process.ChildProcess._handle.onexit (child_process.js:1053:32)
    at child_process.js:1144:20
    at process._tickCallback (node.js:355:11)

The child process is of course phantomjs, and it crashes here (I am using version 2.0.0):

return child.stdin.write(JSON.stringify({
        html: this.html,
        options: this.options
      }) + '\n', 'utf8');

My setup is Windows 8.1 x64, Node 0.12.7 and phantomjs 2.0.0 (manually installed, not via npm).

For reference, here’s my C# code I am using to launch the PDF generation:

var process = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "myapp",
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true
    }
};

try {
    process.Start();
    // write the JSON report to the standard input
    process.StandardInput.WriteLine(jsonReport);
    process.StandardInput.Close();
    // wait for exit
    process.WaitForExit();
    if (process.ExitCode != 0) {
        // THIS IS WHERE IT ERRORS
        Console.WriteLine(@"{0}", process.StandardError.ReadToEnd());
    }
    Console.WriteLine(@"stdout: {0}", process.StandardOutput.ReadToEnd());
} catch (Exception ex) {
    Console.WriteLine(ex.StackTrace);
}

Do you have any idea of what could cause the issue?