-
Notifications
You must be signed in to change notification settings - Fork 0
/
OperationDelete.js
47 lines (41 loc) · 1.79 KB
/
OperationDelete.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk');
const fs = require('fs');
const getPageRangesForDeletion = (startingPage, endingPage) => {
// Specify pages for deletion.
const pageRangesForDeletion = new PDFToolsSdk.PageRanges();
if(startingPage === endingPage) pageRangesForDeletion.addSinglePage(startingPage);
else pageRangesForDeletion.addPageRange(startingPage, endingPage);
return pageRangesForDeletion;
};
module.exports = async function deletePage(baseFile, startingPage, endingPage){
try {
// Initial setup, create credentials instance.
const credentials = PDFToolsSdk.Credentials
.serviceAccountCredentialsBuilder()
.fromFile("pdftools-api-credentials.json")
.build();
// Create an ExecutionContext using credentials and create a new operation instance.
const executionContext = PDFToolsSdk.ExecutionContext.create(credentials),
deletePagesOperation = PDFToolsSdk.DeletePages.Operation.createNew();
// Set operation input from a source file.
const input = PDFToolsSdk.FileRef.createFromLocalFile(`uploads/${baseFile}`);
deletePagesOperation.setInput(input);
// Delete pages of the document (as specified by PageRanges).
const pageRangesForDeletion = getPageRangesForDeletion(startingPage, endingPage);
deletePagesOperation.setPageRanges(pageRangesForDeletion);
// Execute the operation and Save the result to the specified location.
let status = await deletePagesOperation.execute(executionContext)
.then(async result => {
if (fs.existsSync(`./output/${baseFile}.pdf`)){
await fs.unlinkSync(`./output/${baseFile}.pdf`);
}
await result.saveAsFile(`output/${baseFile}.pdf`)
return true
})
return (status ? true:false)
} catch (err) {
return ({
success: false
})
}
}