Skip to main content
Participating Frequently
December 7, 2023
Answered

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

  • December 7, 2023
  • 2 replies
  • 1313 views

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)
}
}
Correct answer try67

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);
	}
}

2 replies

try67
Community Expert
Community Expert
December 7, 2023

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.

Participating Frequently
December 7, 2023

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.

try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
December 7, 2023

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);
	}
}
Bernd Alheit
Community Expert
Community Expert
December 7, 2023

The name of the function is deletePages.