Skip to content
Closed
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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,18 @@ You may add `html2pdf`-specific page-breaks to your document by adding the CSS c
</div>
```

In converse you can add the CSS class `html2pdf__page-break-avoid` to any element. During PDF creation if it is detected that the start of an element with this class will be on a different page than the end, then a page break element will be inserted before it so it starts on a new page.

```html
<div id="element-to-print">
<span>I'm on page 1!</span>
<figure class="html2pdf__page-break-avoid">
<img src="img.jpg">
<figcaption>Don't page break in this image.</figcaption>
</figure>
</div>
```

### Image type and quality

You may customize the image type and quality exported from the canvas by setting the `image` option. This must be an object with the following fields:
Expand Down
22 changes: 22 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,28 @@ html2pdf.makeContainer = function(source, pageSize) {
el.style.height = pxPageHeight - (clientRect.top % pxPageHeight) + 'px';
}, this);

// Enable avoiding page-breaks in the middle of elements.
var pageBreakAvoids = source.querySelectorAll('.html2pdf__page-break-avoid');
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As @adbahrani pointed out, source should be this.prop.container.

Array.prototype.forEach.call(pageBreakAvoids, function (el) {
var clientRect = el.getBoundingClientRect();
var startPageNum = Math.floor(clientRect.top / pxPageHeight);
var endPageNum = Math.floor(clientRect.bottom / pxPageHeight);
if(endPageNum > startPageNum){
/*
* Add a page-break element before the current element with
* the height computed so elements further down can properly
* avoid page-breaks if possible.
*/
var pageBreak = createElement("div", {
style: {
height: (pxPageHeight - (clientRect.top % pxPageHeight) + 'px'),
display: "block"
}
});
el.parentElement.insertBefore(pageBreak, el);
}
}, this);

// Return the container.
return container;
};
Expand Down