Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix page break issue when document has images #531

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/plugin/pagebreaks.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Worker from '../worker.js';
import { objType, createElement } from '../utils.js';
import { createElement, loadImages } from '../utils.js';

/* Pagebreak plugin:

Expand Down Expand Up @@ -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;
Expand Down
32 changes: 32 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}