Pdf-lib Cannot assign to read only property 'toString' of object '#<PDFHeader>'

Describe the problem/error/question

i install the pdf-lib package ,but i can load the package but i meet “read-only” issue in my function node

What is the error message (if any)?

Cannot assign to read only property ‘toString’ of object ‘#’

Please share your workflow

(Select the nodes on your canvas and use the keyboard shortcuts CMD+C/CTRL+C and CMD+V/CTRL+V to copy and paste the workflow.)
{
  "nodes": [
    {
      "parameters": {
        "jsCode": "const { PDFDocument } = require('pdf-lib');\n\nconst pdfDoc = await PDFDocument.create();\nconst page = pdfDoc.addPage([595, 842]); // A4 尺寸\n\nconst pdfBytes = await pdfDoc.save();\n\nreturn [{\n  json: { success: true },\n  binary: {\n    pdf: {\n      data: Buffer.from(pdfBytes).toString('base64'),\n      mimeType: 'application/pdf',\n      fileName: 'test.pdf'\n    }\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2352,
        -64
      ],
      "id": "db2107fc-03ab-48e6-bd4f-0b00dea91f88",
      "name": "Code in JavaScript1"
    }
  ],
  "connections": {},
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "a545fd9bd4bf905b43d43c3de86ab58622dd3d9f1a986335ff25660bc9de5203"
  }
}

Share the output returned by the last node

Information on your n8n setup

  • n8n version: 2.4.7
  • Database (default: SQLite): default
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app): docker
  • Operating system: ubuntu
1 Like

I’d try this to see if it works:

const { PDFDocument } = require('pdf-lib');


const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage([595, 842]);

const pdfBytes = await pdfDoc.save();

const theBuffer = Buffer.from(pdfBytes); 

const finalBuffer = theBuffer.toString('base64'); 

return [{
    json: { success: true },
    binary: {
        pdf: {
            data: finalBuffer,
            mimeType: 'application/pdf',
            fileName: 'test.pdf'
        }
    }
}];

@tengfei86 Welcome!
Change your code by splitting the Buffer.from(pdfBytes).toString('base64') chain into separate steps as shown below, which resolves the read-only property conflict within n8n’s sandboxed environment