Dynamically generated documents may accidentally contain empty pages for a variety of technical reasons. Consistent cleanup is necessary to maintain clean documents.

TX Text Control provides a C# solution for removing empty pages already TX Text Control .NET: Removing Empty Pages. However, implementing this in JavaScript provides more flexibility for web environments. By using JavaScript methods to remove empty pages, you can streamline your documents. They will be free of unwanted page break or section break characters.

Learn More

This article explains why to avoid forced page breaks in document templates and how to create templates that automatically adjust to the content using other word processing features.

Document Templates Tip: Say No to Forced Page Breaks

Scenario: Forced Page Breaks

Consider the following example where one paragraph contains a forced page break (red circle) and the next paragraph always starts on a new page (green circle) because the ParagraphFormat.setPageBreakBefore TX Text Control .NET Server for ASP.NET
JavaScript API
ParagraphFormat Object
setPageBreakBefore Method
Sets whether the paragraph is always displayed on top of a page.
property is set to true. This scenario would result in a blank page in the middle of a document.

Removing Page Breaks

JavaScript Solution

The removeEmptyPages function is an asynchronous JavaScript function that manages documents by iterating through each page in reverse order to check if the content length is one, which usually indicates a page break or section break. If a page is empty, it is deleted, and the function proceeds to check the previous page.

This is achieved by recursion, where the processPage function calls itself for the next page until all pages have been processed. Recursion is a technique used to solve a problem by creating a function that calls itself repeatedly until it reaches a base condition.

function removeEmptyPages() {
TXTextControl.pages.getCount(function(count) {
function processPage(index) {
if (index < 0) {
return;
}
TXTextControl.pages.elementAt(index, function(page) {
page.getLength(function(length) {
// Check if the page is empty.
if (length === 1) {
page.getStart(function(start) {
TXTextControl.select(start - 1, length, function() {
TXTextControl.selection.setText('', function() {
// After deleting, continue with the next page
processPage(index - 1);
});
});
});
} else {
processPage(index - 1);
}
});
});
}
// Start processing from the last page
processPage(count - 1);
});
}
view raw test.js hosted with ❤ by GitHub

Conclusion

Removing empty pages from documents is a common requirement when generating documents dynamically. By using JavaScript, you can implement a solution that removes empty pages from documents created with TX Text Control.