Skip to content

Commit 79f515f

Browse files
fix: fix page break issue when document has images
1 parent 2129120 commit 79f515f

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

src/plugin/pagebreaks.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import Worker from '../worker.js';
2-
import { objType, createElement } from '../utils.js';
2+
import { createElement, loadImages } from '../utils.js';
33

44
/* Pagebreak plugin:
55
@@ -37,7 +37,18 @@ Worker.template.opt.pagebreak = {
3737
};
3838

3939
Worker.prototype.toContainer = function toContainer() {
40-
return orig.toContainer.call(this).then(function toContainer_pagebreak() {
40+
var prereqs = [
41+
function waitLoadImages() {
42+
var root = this.prop.container;
43+
var images = root.querySelectorAll("img");
44+
45+
return loadImages(images);
46+
}
47+
];
48+
49+
return orig.toContainer.call(this)
50+
.thenList(prereqs)
51+
.then(function toContainer_pagebreak() {
4152
// Setup root element and inner page height.
4253
var root = this.prop.container;
4354
var pxPageHeight = this.prop.pageSize.inner.px.height;

src/utils.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,35 @@ export const unitConvert = function unitConvert(obj, k) {
7676
export const toPx = function toPx(val, k) {
7777
return Math.floor(val * k / 72 * 96);
7878
}
79+
80+
81+
// make sure all images finish loading (even though some of them failed to load) then fire the callback
82+
export function loadImages(images) {
83+
if (images.length > 0) {
84+
var loadedImages = 0;
85+
var promiseResolve;
86+
87+
var promise = new Promise(function (resolve) {
88+
promiseResolve = resolve;
89+
});
90+
91+
images.forEach(function wait_images_loading(img) {
92+
var newImg = new Image();
93+
94+
const onFinishLoading = function () {
95+
loadedImages++;
96+
if (loadedImages === images.length) {
97+
promiseResolve();
98+
}
99+
};
100+
101+
newImg.onload = onFinishLoading;
102+
newImg.onerror = onFinishLoading;
103+
104+
var src = img.getAttribute("src");
105+
newImg.src = src;
106+
});
107+
108+
return promise;
109+
}
110+
}

0 commit comments

Comments
 (0)