[英]new line not registered in docx.js
我正在使用 docxjs 庫。 我正在嘗試將換行符添加到即時生成的文檔中,但我不確定如何執行此操作。 \n
字符被忽略。 如何在我的文檔中添加換行符?
我要添加換行符的段落:
new Paragraph( {
text: '\n',
children: [
...Object.entries( dataItem ).map( ([fieldName, fieldValue]) => new Paragraph( {
text: fieldName,
children: Object.entries( fieldValue ).map( ([dataSource, dataValue]) => new Paragraph( {
text: dataSource,
children: Object.values( dataValue ).map( value => new Paragraph(value) )
}) )
}) ),
new Paragraph( {text: '_', children: [new PageBreak()]} )
]
} )
我認為該段落在文本中等於換行符。 不是嗎?
doc.addSection({
properties: {},
children: [
new Paragraph({
children: [
new TextRun("First line"),
],
}),
new Paragraph({
children: [], // Just newline without text
}),
new Paragraph({
children: [
new TextRun("Second line"),
],
}),
],
});
docxjs 庫在此處具有用於換行的內置功能。 首先,我們需要拆分行,然后我們可以在TextRun
object 上使用break
屬性:
const lines = "This sentence\n is breaked\n into three lines"
const textRuns = lines.split("\n").map(line=>new TextRun({break:1,text:line}))
const paragraph = new Paragraph({children: textRuns})
這是一個較晚的答案,但是接受的答案不允許您動態添加換行符,盡管它確實對我有所幫助,但我無法讓 Haris Wirabrata 工作。 我的解決方案通過標記(在本例中為“break”)將文本拆分為一個數組,然后循環遍歷該數組以將 textRun 元素添加到段落元素。 請注意帶有 break 參數的額外 textRun ,請參閱此處的文檔。 下面的示例代碼。
function getTextPara(textElement) {
var docx = require("docx");
var fs = require('fs');
var text;
var para = new docx.Paragraph({
children: [
]
});
var cleanTextArray = testElement.split("<break>");
for (var i = 0; i < cleanTextArray.length; i++) {
text = new docx.TextRun({
text: cleanTextArray[i],
});
para.addChildElement(text);
text = new docx.TextRun({
text: "",
break: 1,
});
para.addChildElement(text);
}
return para;
}
const paragraphs = yourText.split("\n")
.map(line => new docx.Paragraph({
children: [new docx.TextRun({ text: line, size: 24, font: 'Arial' })]
}));
const doc = new docx.Document();
doc.addSection({
properties: {},
children: paragraphs
});
此 function 可幫助您保留新行並使用 blob 下載您的 docx 文件。
將您的文本傳遞給generateDoc function,如下所示
const ExampleText = "This sentence\n is breaked\n into three lines \n Faizan bhai"
generateDoc(ExampleText);
function generate(text) {
const textString = text.split("\n").map(line=>new docx.TextRun({break:1,text:line}))
const doc = new docx.Document({
sections: [{
properties: {},
children: [
new docx.Paragraph({children: textString})
],
}]
});
docx.Packer.toBlob(doc).then(blob => {
downloadBlob(blob, "example.docx");
});
}
function downloadBlob(blob, name = 'file.docx') {
const blobUrl = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = blobUrl;
link.download = name;
document.body.appendChild(link);
link.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
})
);
document.body.removeChild(link);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.