From 79f515fe1a6af1b587e491e33ff25d4dc00de5e5 Mon Sep 17 00:00:00 2001 From: Mahmoud Kassah Date: Mon, 14 Mar 2022 20:20:15 +0300 Subject: [PATCH] fix: fix page break issue when document has images --- src/plugin/pagebreaks.js | 15 +++++++++++++-- src/utils.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/plugin/pagebreaks.js b/src/plugin/pagebreaks.js index 5a4dc2b..236e09d 100644 --- a/src/plugin/pagebreaks.js +++ b/src/plugin/pagebreaks.js @@ -1,5 +1,5 @@ import Worker from '../worker.js'; -import { objType, createElement } from '../utils.js'; +import { createElement, loadImages } from '../utils.js'; /* Pagebreak plugin: @@ -37,7 +37,18 @@ Worker.template.opt.pagebreak = { }; Worker.prototype.toContainer = function toContainer() { - return orig.toContainer.call(this).then(function toContainer_pagebreak() { + var prereqs = [ + function waitLoadImages() { + var root = this.prop.container; + var images = root.querySelectorAll("img"); + + return loadImages(images); + } +]; + + return orig.toContainer.call(this) + .thenList(prereqs) + .then(function toContainer_pagebreak() { // Setup root element and inner page height. var root = this.prop.container; var pxPageHeight = this.prop.pageSize.inner.px.height; diff --git a/src/utils.js b/src/utils.js index ce0c413..84c723d 100644 --- a/src/utils.js +++ b/src/utils.js @@ -76,3 +76,35 @@ export const unitConvert = function unitConvert(obj, k) { export const toPx = function toPx(val, k) { return Math.floor(val * k / 72 * 96); } + + +// make sure all images finish loading (even though some of them failed to load) then fire the callback +export function loadImages(images) { + if (images.length > 0) { + var loadedImages = 0; + var promiseResolve; + + var promise = new Promise(function (resolve) { + promiseResolve = resolve; + }); + + images.forEach(function wait_images_loading(img) { + var newImg = new Image(); + + const onFinishLoading = function () { + loadedImages++; + if (loadedImages === images.length) { + promiseResolve(); + } + }; + + newImg.onload = onFinishLoading; + newImg.onerror = onFinishLoading; + + var src = img.getAttribute("src"); + newImg.src = src; + }); + + return promise; + } +}