我使用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()。我使用这个方法将字符串拆分为String,并再次与中断行的<br>标记连接。
这部分工作,但格式错误的PDF格式,并采取了新的行时,不需要,因为这个方法的限制。
TypeScript代码(使用splitTextToSize()):
const editor1ContentSplitArray = doc.splitTextToSize(editor1Content, 850);
const source = editor1ContentSplitArray.join('<br>');使用手动插入的行中断

编辑有关以下内容的一些额外信息:
我正在从另一个网站复制上面的文本,粘贴到一个富文本编辑器(CKEditor 5)中,然后我有一个按钮,其中onClick函数包含上面的TypeScript代码来执行转换。
发布于 2020-05-15 09:20:21
您不需要加入字符串数组。
尝试将字符串数组插入到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);
}https://stackoverflow.com/questions/61680635
复制相似问题