@@ -358,9 +358,9 @@ function splitDocument()
358358 const contentPrint = document.querySelector('.content-print')
359359
360360 // Get content body elements
361- const contentElements = contentBody?. children
361+ const contentElements = contentBody ? Array.from(contentBody. children) : []
362362
363- if (!contentElements || contentElements.length <= 0)
363+ if (contentElements.length <= 0)
364364 {
365365 return
366366 }
@@ -379,8 +379,10 @@ function splitDocument()
379379 const pages: Array<Array<Element>> = [ [] ]
380380 let absoluteTop = Number.NaN
381381
382- for (const element of contentElements)
382+ for (let elementIndex = 0; elementIndex < contentElements.length; ++elementIndex )
383383 {
384+ const element = contentElements[elementIndex]
385+
384386 if (element.tagName === 'HR')
385387 {
386388 // Start new page, as always on hr elements
@@ -406,6 +408,23 @@ function splitDocument()
406408 absoluteTop = rect.top
407409 }
408410
411+ if ([ 'H1', 'H2', 'H3', 'H4' ].includes(element.tagName))
412+ {
413+ // Check the element after the heading fits on the page
414+ const nextElement = contentElements[elementIndex + 1]
415+ if (nextElement)
416+ {
417+ const nextRect = nextElement.getBoundingClientRect()
418+ const nextContentHeight = nextRect.bottom - absoluteTop
419+ if (nextContentHeight > maxPageHeight)
420+ {
421+ // Start new page, because the next element does not fit after the heading
422+ pages.push([])
423+ absoluteTop = nextRect.top
424+ }
425+ }
426+ }
427+
409428 // Add element to the last page
410429 pages[pages.length - 1]!.push(element)
411430 }
0 commit comments