我使用的是 jsPDF 从连贯的HMTL字符串生成PDF文档。
我需要使用这个方法而不是 getElementById()
因为我是使用TypeScript动态拉动HTML的。
我已经能够从HTML字符串中生成PDF文档,问题是文本如何显示在PDF上--它在屏幕右侧拖尾(如下图)。
我一直没有找到这个具体问题的答案,并尝试了各种方法来解决这个问题(如下图所示),但收效甚微。
我希望有一个更简单的方法,在jsPDF库中使用右边距、文本包装或其他格式化功能,有人能告诉我吗?
起初,我以为在PDF中加入 margin
和 width
下面的选项可以纠正这种情况。但事实并非如此。
TypeScript代码(主函数)。
generatePdf() {
console.log('Generating PDF');
// (orientation: portrait, units: pt, PDF page size: A4)
const doc = new jspdf('p', 'pt', 'a4');
const editor1Content = this.getEditorHtml(this.editorComponent1); // HTML string
const editor2Content = this.getEditorHtml(this.editorComponent2); // HTML string
const source = editor1Content + editor2Content; // combined HTML string
console.log('source: ', source);
// source is the HTML string or DOM elem ref. HTML String in this case.
// width - max width of content on PDF
// 0.5, 0.5 - margin left, margin top
const margins = {top: 60, bottom: 30, left: 30, width: 595};
const pdfDocument = doc.fromHTML(source, margins.left, margins.top, { width: margins.width, },
// tslint:disable-next-line:only-arrow-functions
function(dispose) {
doc.save('news-summary.pdf'); // Generated PDF
}, margins
);
}
经过一些研究,我发现jsPDF的函数 splitTextToSize()
. 我用这个方法把字符串分割成一个字符串数组,然后用换行符再次连接。<br>
标签。
这样做有部分效果,但 糟糕的格式化的PDF,并采取了新的行,当不需要。 由于该方法的限制。
TypeScript代码(使用splitTextToSize())。
const editor1ContentSplitArray = doc.splitTextToSize(editor1Content, 850);
const source = editor1ContentSplitArray.join('<br>');
编辑关于这个问题的一些额外信息。
我从另一个网站复制上述文字,并将其粘贴到一个富文本编辑器中(CKEditor 5
),然后我有一个按钮 onClick
函数包含上面的TypeScript代码来进行转换。
你不需要连接字符串数组。
尝试将字符串数组插入到 doc.fromHtml
或使用 doc.text
作为doc.text同时接受字符串和字符串数组作为参数。
在这里,你需要做什么。
generatePdf() {
console.log('Generating PDF');
const doc = new jspdf('p', 'pt', 'a4');
const editor1Content = this.getEditorHtml(this.editorComponent1); // HTML string
const editor2Content = this.getEditorHtml(this.editorComponent2); // HTML string
const concatEditorContent = editor1Content + editor2Content; // combined HTML string
const margins = {top: 60, bottom: 30, left: 30, width: 595};
const source = doc.splitTextToSize(concatEditorContent, 850);
const pdfDocument = doc.fromHTML(source, margins.left, margins.top, { width: margins.width })
function(dispose) {
doc.save('news-summary.pdf'); // Generated PDF
}, margins);
}