使用pdf-lib添加文本注释时触发‘Expected a string object’错误求助
解决pdf-lib添加便签注释时“Expected a string object”错误
问题原因
你代码里直接将原生JavaScript字符串赋值给Contents属性,但PDF规范要求注释的内容必须是PDF字符串对象,而非普通JS字符串,这导致PDF阅读器解析时抛出类型错误。
修复方案
需要使用pdf-lib提供的PDFString.from()方法,将普通JS字符串转换为符合PDF规范的字符串对象,替换原代码中Contents的赋值逻辑:
// 确保先导入PDFString import { PDFString } from 'pdf-lib'; function addNote(props) { // Add a PDF Annotation "sticky note" to a page /* @param text Text of note @param x X position of note icon @param y Y position of note icon @param width Width of note icon @param height Height of note icon */ // Add a PDF Annotation object: const annotation = pdfDoc.context.obj({ Type: 'Annot', Subtype: 'Text', Open: false, // Is the annotation open by default? Name: 'Note', // Determines the icon to place in the document. Rect: [ props.x, props.y, props.x + props.width, props.y + props.height ], // The position of the annotation // 关键修改:将普通字符串转为PDF字符串对象 Contents: PDFString.from(props.text) }); const annotationRef = pdfDoc.context.register(annotation); // Register the annotation in the document. console.log("Annotation added:", annotationRef); // Find the Annots dictionary on the current page and add the new annotation to it. const annots = page.node.lookup(PDFName.of('Annots'), PDFArray); annots.push(annotationRef); }
额外注意事项
- 确认
props.text是有效的非空字符串,避免传入undefined或null导致新的解析问题; - 若你的代码是CommonJS模块(使用
require),导入方式改为:const { PDFString } = require('pdf-lib');
内容的提问来源于stack exchange,提问作者Ryan Griggs
相关产品推荐
相关产品推荐

