I am using jsPDF to generate PDF documents from concatenated HMTL Strings.
I need to use this method rather than getElementById()
as I am pulling the HTML dynamically using TypeScript.
I have been able to generate the PDF document from the HTML String, the issue is how the text displays on the PDF - it is trailing off the right of the screen (image below).
I have not been able to find an answer to this specific issue and have tried various methods to resolve this (explained below) with little success.
I am hoping there is a more simple approach, using a right margin, text wrapping or some other formatting capability within the jsPDF library, that someone could point me to?
Text Trailing off to the right of PDF:
Initially, I thought that adding the margin
and width
options below could correct this. But this was not the case.
TypeScript Code (main function):
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
);
}
After some research I found the jsPDF function splitTextToSize()
. I used this to split the String into a String Array and join again with line breaking <br>
tags.
This partially worked, but badly formatted the PDF and took new lines when not needed due to the restrictions of this method.
TypeScript Code (using splitTextToSize()):
const editor1ContentSplitArray = doc.splitTextToSize(editor1Content, 850);
const source = editor1ContentSplitArray.join('<br>');
Using manually inserted line breaks
EDIT Some extra information on this:
I am copying the above text from another website, pasting it into a rich text editor (CKEditor 5
), then I have a button which onClick
function contains the TypeScript code above to carry out the conversion.