Skip to main content
Participating Frequently
Dec 7, 2023 10:57 AM UTC
Answered

Delete last 2 pages from every 10 pages in a pdf using javascript

I cobbled up this script to gether to Delete last 2 pages from every 10 pages in a pdf using javascript but get the error message  this.deletepages is not a function. Any help would be appreciated as I have no clue what I am doing.

 

if (app.viewerVersion < 10) {
app.addMenuItem({ cName: "Delete last 2 of every 10 pages", cUser: "Delete last 2 of every 10 pages", cParent: "Tools", 
cExec: "Deletelast2ofevery10pages(this)", cEnable: "event.rc = (event.target != null);"}); 
} else {
app.addToolButton({ cName: "Delete last 2 of every 10 pages", cLabel: "Delete last 2 of every 10 pages", cTooltext: "Delete last 2 of every 10 pages", 
cExec: "Deletelast2ofevery10pages(this)", cEnable: "event.rc = (event.target != null);"}); 
}
/* Delete last 2 of every 10 pages in the document */
// Double slash at front of line is a comment
function Deletelast2ofevery10pages(doc) {
try {
 
    for (var i = 0; i < this.numPages; i += 10)
       {
this.deletepages({nstart:i+8, nend:i+10})
       }
} 
catch(e)
{
app.alert("Processing error: "+e)
}
}
try67
try67Correct answer
Community Expert
Dec 7, 2023 3:10 PM UTC

Try this code:

 

for (var i = this.numPages-1; i>=0; i--) {
	if (/9$/.test(""+(i+1))) {
		console.println("delete pages "+(i+1)+"-"+(i+2)); 
		this.deletePages(i, i+1);
	}
}

7 replies

try67
Community Expert
Community Expert
Dec 7, 2023 11:13 AM UTC

JS is case-sensitive. So it's: deletePages, nStart, nEnd, etc.

In addition, you have a logical error in your code. When you delete pages in a loop that goes from the first pages to the last, your index variable (i) will no longer point to what used to be the old pages in the file, but to the new ones that occupy their location after the deletion. So you should start from the last page, and move backwards to the first one in your loop to avoid that.

Translate
Participating Frequently
Dec 7, 2023 11:59 AM UTC

Thank you. Yes the syntax has resolved the problem but as you mentioned, I am not getting the result I need. I will try and workout how to loop from the end to the start of the file. If you have any such examples, then that would be greatly appreciated. Many Thanks.

Translate
try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
Dec 7, 2023 3:10 PM UTC

Try this code:

 

for (var i = this.numPages-1; i>=0; i--) {
	if (/9$/.test(""+(i+1))) {
		console.println("delete pages "+(i+1)+"-"+(i+2)); 
		this.deletePages(i, i+1);
	}
}
Translate
Bernd Alheit
Community Expert
Community Expert
Dec 7, 2023 11:01 AM UTC

The name of the function is deletePages.

Translate