我正在编写一份谷歌文档,其中一个标题分布在由 Enter(
\n
)分隔的多行中,我希望将其转换为软返回(Shift + Enter
),我可以手动执行此操作,但它非常繁琐做了 100 个这样的标题,想检查它们是否是一种使用谷歌应用程序脚本自动执行此操作的方法,这是我迄今为止尝试过的方法,但没有成功:
尝试1
function convertHeading6ToSoftWrap() {
var body = DocumentApp.getActiveDocument().getBody();
var heading4Elements = body.getParagraphs().filter(function (paragraph) {
return paragraph.getHeading() == DocumentApp.ParagraphHeading.HEADING4;
});
heading4Elements.forEach(function (element) {
var text = element.getText();
element.clear();
element.setAttributes({
'LINE_SPACING': 1.5,
'SPACING_AFTER': 0,
'SPACING_BEFORE': 0
});
element.appendText(text);
});
}
尝试2
function convertHeading6ToSoftWrap() {
var body = DocumentApp.getActiveDocument().getBody();
var heading4Elements = body.getParagraphs().filter(function (paragraph) {
return paragraph.getHeading() == DocumentApp.ParagraphHeading.HEADING4;
});
heading4Elements.forEach(function (element) {
var text = element.getText();
element.clear();
applySoftWrap(text, body);
});
}
function applySoftWrap(text, body) {
var lines = text.split("\n");
lines.forEach(function (line, index) {
if (index > 0) {
body.appendParagraph(line);
} else {
body.appendParagraph(line);
}
});
}
任何提示或线索都将受到高度赞赏。
说明问题的示例文档 - https://docs.google.com/document/d/18w49xpuRQ9igGeyNPSa4PDhv_lqyrWHHVCL8k7DlCnY/edit?usp=sharing
---- 更新----- 感谢您的建议和评论,下面的代码将硬返回合并到软 H4 中,但问题是它将所有 H4 合并为一个,即被多个新行分隔的那些,如果它们之间有文本其他非 H4 段落仍然合并为一:
function convertHeading4ToSoftWrap() {
var body = DocumentApp.getActiveDocument().getBody();
var paragraphs = body.getParagraphs();
var mergedText = '';
var isFirstHeading4 = true;
paragraphs.forEach(function (paragraph) {
try {
if (paragraph.getHeading() === DocumentApp.ParagraphHeading.HEADING4) {
if (isFirstHeading4) {
mergedText = paragraph.getText();
isFirstHeading4 = false;
} else {
mergedText += '\n' + paragraph.getText();
paragraph.removeFromParent(); // Remove the redundant paragraph
}
}
} catch (error) {
console.error('Error processing paragraph:', error);
}
});
// Create a new paragraph with the merged Heading 4 text
var mergedParagraph = body.appendParagraph(mergedText);
// Set the new paragraph as Heading 4
mergedParagraph.setHeading(DocumentApp.ParagraphHeading.HEADING4);
}
这是一个使用软回车将两行 HEADING4 行合并为一个段落的示例。
function test() {
try {
let doc = DocumentApp.getActiveDocument();
let body = doc.getBody();
let paragraphs = body.getParagraphs();
let i = paragraphs.length-1; // start from the bottom
let head2 = null;
while( i >= 0 ) {
let paragraph = paragraphs[i];
if( paragraph.getHeading() === DocumentApp.ParagraphHeading.HEADING4 ) {
if( head2 ) {
// join the 2 lines together
paragraph.appendText(String.fromCharCode(13));
paragraph.appendText(head2.getText());
body.removeChild(head2);
head2 = null;
}
else {
head2 = paragraph;
}
}
else {
head2 = null;
}
i--;
}
}
catch(err) {
console.log(err);
}
}