-
Notifications
You must be signed in to change notification settings - Fork 0
/
OperationReorder.js
46 lines (40 loc) · 1.76 KB
/
OperationReorder.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
const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk');
const fs = require('fs');
const getPageRangeForReorder = (startingPage, endingPage) => {
// Specify order of the pages for an output document.
const pageRanges = new PDFToolsSdk.PageRanges();
// Add pages 3 to 4.
if(startingPage === endingPage) pageRanges.addSinglePage(startingPage);
else pageRanges.addPageRange(startingPage, endingPage);
return pageRanges;
};
module.exports = async function reorderPage(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),
reorderPagesOperation = PDFToolsSdk.ReorderPages.Operation.createNew();
// Set operation input from a source file, along with specifying the order of the pages for
// rearranging the pages in a PDF file.
const input = PDFToolsSdk.FileRef.createFromLocalFile(`uploads/${baseFile}`);
const pageRanges = getPageRangeForReorder(startingPage, endingPage);
reorderPagesOperation.setInput(input);
reorderPagesOperation.setPagesOrder(pageRanges);
// Execute the operation and Save the result to the specified location.
let status = await reorderPagesOperation.execute(executionContext)
.then(async (result) => {
if (fs.existsSync(`./output/${baseFile}`)){
await fs.unlinkSync(`./output/${baseFile}`);
}
result.saveAsFile(`output/${baseFile}`)
return true
})
return (status ? true:false)
} catch (err) {
return false
}
}