在PDF文档处理中,我们经常需要统一注释的显示样式。虽然注释右键菜单中提供了”设置当前属性为默认”功能,但对于接口设置的富文本格式,此功能可能无法生效。以下是实现将当前富文本格式设置为默认格式的完整方案:
实现步骤
1. 扩展注释右键菜单
在pdfui构造函数的外观参数中,添加一个名为”设置当前富文本为默认”的新菜单项。这一扩展将增强右键菜单的功能性,为用户提供更直观的格式设置选项。
appearance: UIExtension.appearances.AdaptiveAppearance.extend({
getDefaultFragments: function () {
// 定义需要移除“居中”项的注释类型列表
const annotTypes = [
'typewriter', 'callout', 'textbox',
];
const fragments = [];
annotTypes.forEach(type => {
// 使用字符串拼接而不是模板字符串语法
fragments.push({
target: 'fv--' + type + '-contextmenu',
action: UIExtension.UIConsts.FRAGMENT_ACTION.APPEND,
template: `
<contextmenu-item name="x-user-custom-contextmenu-item">设置当前富文本属性为默认</contextmenu-item>
`,
config: [{
target: 'x-user-custom-contextmenu-item',
callback: setDefaultRichTextProperty
}]
});
});
return fragments;
}
}),
2. 建立状态跟踪机制
定义全局变量来准确记录两个关键状态:
- 用户是否选择了”设置当前富文本为默认”选项
- 当前设定的默认富文本格式内容
//全局变量记录是否设置当前属性为默认,并且记录当前富文本格式。
var isDefaultRichTextProperty = false;
var richTextStyle
async function setDefaultRichTextProperty() {
// 获取当前注释的组件对象
console.log(this)
const currentAnnotComponent = this.component.parent.currentTarget;
if (currentAnnotComponent) {
// 获取底层的注释对象
const annot = currentAnnotComponent.annot;
// 获取注释信息
const annotInfo = annot.getInfo();
if(annotInfo.richText.length > 0)
{
richTextStyle = annotInfo.richText[0].richTextStyle
}
// 您可以在此处使用获取到的属性,例如打印到控制台或进行其他操作
console.log('注释:', annotInfo);
}
isDefaultRichTextProperty = !isDefaultRichTextProperty;
console.log(isDefaultRichTextProperty)
}
3. 在annotationUpdated监听事件中,加入之恶能判断逻辑:
- 检测用户是否已激活”设置当前富文本为默认”选项
- 当注释内容发生变化时,自动将全局变量中存储的默认富文本格式应用到当前注释
pdfui.eventEmitter.on(PDF.constant.DataEvents.annotationUpdated, (annots, PDFPage, AnnotUpdatedType) =>
{
//判断是否是记录富文本格式的注释
if(isDefaultRichTextProperty == true && richTextStyle)
{
annots.forEach(async annot =>{
let info = annot.getInfo()
console.log(info)
console.log(AnnotUpdatedType)
if(AnnotUpdatedType === 'content-updated' && info.richText.length === 0 )
{
annot.setContent('');
await annot.addRichText([{
content: info.content ? info.content : '\u200C',
richTextStyle: {
font: {
name: richTextStyle.fontName,
},
textSize: richTextStyle.textSize,
textAlignment: richTextStyle.textAlignment,
textColor: richTextStyle.textColor,
isBold: richTextStyle.isBold,
isItalic: richTextStyle.isItalic,
isUnderline: richTextStyle.isUnderline,
isStrikethrough: richTextStyle.isStrikethrough,
cornerMarkStyle: richTextStyle.cornerMarkStyle,
}
}]);
}
})
}
})
通过这一流程,我们可以有效解决接口设置的富文本格式无法通过常规方法设为默认的问题,确保文档中所有注释保持统一的富文本样式。