4

I'm trying to write a PDF file to disc from a Node.js application. I can create the file but when I open it, it's blank. It's not 0 size so obviously data is being written to it, but I need to figure out how to see the data I expect to see when I open it.

The data for the PDF is coming from a 3rd party HTML-to-PDF conversion API. In the response it returns, I see this in the data property:

response.data = '%PDF-1.4\n' +
    '1 0 obj\n' +
    '<<\n' +
    '/Title (��)\n' +
    '/Creator (��)\n' +
    '/Producer (��\x00Q\x00t\x00 \x004\x00.\x008\x00.\x006)\n' +
    '/CreationDate (D:20201109233748Z)\n' +
    '>>\n' +
    'endobj\n' +
    '3 0 obj\n' +
    '<<\n' +
    '/Type /ExtGState\n' +
    ...
    ...
    ...
    'startxref\n' +
    '16917\n' +
    '%%EOF\n'

Then I write it to disc like this:

            fs.writeFile('./letter.pdf', res.data, (err) => {
                if (err) {
                    console.log('Failed to save file; err=', err);
                    return null;
                }
                console.log('successfully saved file');
            });

But when I open it, it's a blank document.

I've gotten this data back from two providers so far:

...and I've had the same problem with both. I take this to mean the data I get back is pretty standard and not corrupt, and it's up to me to format it and massage it in some way before saving it to disc.

Does anyone know what I need to do with the data before saving it to a file?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
gib65
  • 1,709
  • 3
  • 24
  • 58

1 Answers1

0

Make sure you treat it as a binary file.

fs.writeFile('result.pdf', binary_file, "binary", function () {})

If you would rather work with a base64 string or URL, check out https://docamatic.com.

drs
  • 1,165
  • 3
  • 13
  • 19