node-html-pdf icon indicating copy to clipboard operation
node-html-pdf copied to clipboard

Error: write EPIPE

Open grimurd opened this issue 9 years ago • 53 comments

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                                    [email protected]\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?

grimurd avatar Jun 03 '15 16:06 grimurd

I didn't have a look at your html yet, but there are some errors that don't get catched in your code. You're always using next like this.

function(err, html) {
  if (err) {
    next(err);
  }
 //...
}

In a case of an error, your code continues with the execution. To prevent this, you have to return the error like here:

function(err, html) {
  if (err) {
    return next(err);
  }
 //...
}

marcbachmann avatar Jun 04 '15 21:06 marcbachmann

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

marcbachmann avatar Jun 30 '15 21:06 marcbachmann

Have same issue.

    html=Twig.twig({data: html}).render({
        bodys: config.list.map(function(item){
            return input.row[item.id].body;
        })
    });
    var options = { filename: dest, format: 'Letter'};
    console.log('Create pdf..');//Last console log before error
    pdf.create(html, options).toFile(function(err, res){
        if(err){
              console.error(err);
              callback(err);
        }
        console.log('Pdf file:',res.filename);
        callback(err, dest_file);
    });

This code working on my local machine (Win8), but on server (Debian) I got this error and server fault..

events.js:85
       throw er; // Unhandled 'error' event
Error: write EPIPE
    at exports._errnoException (util.js:746:11)
    at WriteWrap.afterWrite (net.js:775:14)

I check path to file, its like this:

local: c:...path_to_project..\engine../public/reports/..filename.pdf server: /var/...path_to_project../engine/../public/reports/..filename.pdf

Paths like this works correctly in another places (generate images) What i can do with this problem? Have no idea..

aka-darth avatar Aug 20 '15 12:08 aka-darth

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

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?

frapontillo avatar Aug 21 '15 16:08 frapontillo

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.

skastr0 avatar Sep 22 '15 19:09 skastr0

same problem and running npm instal on html-pdf doesn't fix it.. anyone have found how to solve this ?

sovanna avatar Nov 09 '15 16:11 sovanna

sudo apt-get install libfontconfig

sovanna avatar Nov 09 '15 18:11 sovanna

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": [],

moconchobhair avatar Feb 15 '16 05:02 moconchobhair

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

danieldiekmeier avatar Feb 22 '16 01:02 danieldiekmeier

Hi marc

I am facing the EPIPE error once i have deployed my app to Amazon EC2 (Ubuntu 14.04.3 LTS). This works totally fine on my dev box, which is running Windows 10.

My app is a meteor app and it is deployed to EC2 using mupx.

I used to get the EOENT error and following the instructions here and other places, i did execute sudo apt-get install libfontconfig and after that the error changed to EPIPE

Here are my config options

pdfConfigOptions = {"directory": "/opt/<appname>/tmp", "format": "A4", "orientation": "portrait", "border": "0", "type": "pdf", "quality": "75" "timeout": 30000}

Here is my code invoking the pdf creation. (I removed the code that deals with the returned buffer as part of debugging)

var pdfCreator = Meteor.npmRequire('html-pdf'); let pdf = pdfCreator.create(html, this.pdfConfigOptions); pdf.toBuffer(function (err, buffer) { //This line fails with the following error });

events.js:72 throw er; // Unhandled 'error'event ^ Error: write EPIPE at errnoException(net.js:905:11) at Object.afterWrite (net.js:721:19)

FYI: My code had Meteor.bindEnvironment around the callback function, but i removed that while testing to figure out what is causing these errors. This clearly is happening while html-pdf is trying to create the pdf using phantom,

phantom is installed on the image, See below ubuntu@ip-<0.0.0.0>/opt/$ sudo find . -name "phantom" ./last/bundle/programs/server/npm/npm-container/node_modules/html-pdf/node_modules/phantomjs-prebuilt/lib/phantom ./current/bundle/programs/server/npm/npm-container/node_modules/html-pdf/node_modules/phantomjs-prebuilt/lib/phantom

Any help in pointing me to the right direction to either fix this or identify the issue is greatly appreciated.

Thanks a lot in advance for your time S

srawther avatar Mar 31 '16 02:03 srawther

I was facing same EPIPE issue while generating pdf

@sovanna's "sudo apt-get install libfontconfig" worked for me

Thanks Buddy

aju9316 avatar Aug 07 '16 18:08 aju9316

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

areinmeyer avatar Nov 02 '16 20:11 areinmeyer

I was getting following error while exporting pdf on my centOS system.

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

After running yum install fontconfig , now pdf is generating but its content is not visible. It is a simple html table.

Same case is working on my ubuntu system.

bansalritesh18 avatar Nov 11 '16 07:11 bansalritesh18

@bansalritesh18

Try adding the following via yum

freetype*
fontconfig
urw-fonts

I have the above 3 in my Dockerfile that I'm using with this module. These seemed to resolve my issues with fonts or styling.

areinmeyer avatar Nov 14 '16 15:11 areinmeyer

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.

kevinbror avatar Nov 28 '16 17:11 kevinbror

I had the same thing as @kevinbror and got it working by rebuilding phantomjs. (Everything worked fine in my macbook, but when I cloned the my git to Ubuntu, running my node server there was resulting the EPIPE error.)

latvaaho avatar Feb 20 '17 12:02 latvaaho

are you pushing your node_modules to git? Don't do that. All the platform specific modules won't work unless you run npm rebuild.

marcbachmann avatar Feb 20 '17 13:02 marcbachmann

I am not that novice :-) My 'base project' is templated by swagger-node-express and it's default .gitignore keeps node modules out of git among other artefact files. However, I might have had a really old phantom version on my ubuntu machine from some other project I have been doing previously with angular app's test automation. But I have seen people's repos with node_modules as well as other library stuff so that is a valid concern you raised 👍

latvaaho avatar Feb 20 '17 15:02 latvaaho

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

emmetog avatar Mar 10 '17 14:03 emmetog

I am having the same issue on macOS

uncaughtException: { Error: write EPIPE
    at exports._errnoException (util.js:1022:11)
    at WriteWrap.afterWrite [as oncomplete] (net.js:804:14) code: 'EPIPE', errno: 'EPIPE', syscall: 'write' }

tried every possible solution suggested on web. doesn't got any luck. any suggestions ?

And when i try to convert the HTML from terminal it works fine. :(

FaheemAlam avatar Mar 30 '17 12:03 FaheemAlam

You just have to install libfontconfig1package. For debian users: sudo apt-get install libfontconfig1

rimiti avatar Apr 26 '17 16:04 rimiti

Hi, I am using html-pdf npm package for my electron app. It was working perfect in both development and production environment. But now after using ASAR to pack my code, it stopped working in production. Gives Error

Uncaught Error: write EPIPE at exports._errnoException (util.js:1022) at Socket._writeGeneric (net.js:715) at Socket._write (net.js:734) at doWrite (_stream_writable.js:332) at writeOrBuffer (_stream_writable.js:318) at Socket.Writable.write (_stream_writable.js:245) at Socket.write (net.js:661) at PDF.PdfExec [as exec] (C:\Project\Project-win32-ia32\resources\app.asar\node_modules\html-pdf\lib\pdf.js:136) at PDF.PdfToFile [as toFile] (C:\Project\Project-win32-ia32\resources\app.asar\node_modules\html-pdf\lib\pdf.js:83) at generatePdf (:1155:43)

The solution mentioned by others i.e. to install libfontconfig is not applicable here since there is not libfontconfig package in npm.

Being a nube I expect to be clarified if i failed to understand things from the error msg or from the above discussions.

P.S: I am well aware that ASAR pack are read only. So the path for pdf is outside it. But still the same problem. Does html-pdf perform any write operation other then the final write to the file path specified?

ishwarrimal avatar May 25 '17 05:05 ishwarrimal

@ishwarrimal any chance you figured out a solution to this issue with electron? Dealing with this now...

danmckeon avatar Dec 14 '17 04:12 danmckeon

hi @danmckeon, since html-pdf package was doing some write operation internally, the only solution for me was moving out this package from node-modules and keeping it one level outside the current directory and giving the absolute path. But with that included, the installer size was getting huge. Hence later i found out that electron on itself has provide a tool for printing pdf. So using that it was very easy for me.

I would prefer the second approach (using inbuilt tool) but if you want to know more about the first approach please let me know.

Hope this helps.

ishwarrimal avatar Dec 14 '17 06:12 ishwarrimal

@ishwarrimal I noticed that tool, but every PDF I create with Chromium (including with the Electron tool) is huge. Did you find a workaround for that?

danmckeon avatar Dec 14 '17 13:12 danmckeon

@sovanna you are the boss! save my day Thanks!

rodrigoraya avatar Jan 17 '18 02:01 rodrigoraya

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?

byt3b4ndit avatar Apr 17 '18 08:04 byt3b4ndit

“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, [email protected] 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 .

ishwarrimal avatar Apr 17 '18 09:04 ishwarrimal

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

work0407506 avatar Apr 18 '18 08:04 work0407506

@work0407506 👍

rimiti avatar Apr 18 '18 08:04 rimiti