如何使用Adobe PDF Services进行2次(或更多)调用并跳过使用文件系统(介于两者之间?)



调用Adobe PDF Services,获取结果并保存它非常简单,例如:

// more stuff above
exportPdfOperation.execute(executionContext)
.then(result => result.saveAsFile(output))

但是,如果我想做两个或更多的操作,我是否需要继续将结果保存到文件系统并将其重新提供给API(这甚至是一个词;(?

所以这也让我绊倒了。在大多数演示中,您将看到:

result => result.saveAsFile()

接近尾声。然而,传递给已完成承诺的对象result是一个FileRef对象,然后可以用作另一个调用的输入。

下面是一个示例,它获取一个输入Word文档并调用API方法来创建PDF。然后,它接受它并在它上面运行OCR。包装API调用的两个方法都返回FileRefs,所以最后我在它上面使用saveAsFile。(注意,这个演示使用的是SDK的v1,它将使用相同的w/v2。(

const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk');
const fs = require('fs');
//clean up previous
(async ()=> {
// hamlet.docx was too big for conversion
const input = './hamlet2.docx';
const output = './multi.pdf';
const creds = './pdftools-api-credentials.json';
if(fs.existsSync(output)) fs.unlinkSync(output);
let result = await createPDF(input, creds);
console.log('got a result');
result = await ocrPDF(result, creds);
console.log('got second result');
await result.saveAsFile(output);
})();
async function createPDF(source, creds) {
return new Promise((resolve, reject) => {
const credentials =  PDFToolsSdk.Credentials
.serviceAccountCredentialsBuilder()
.fromFile(creds)
.build();
const executionContext = PDFToolsSdk.ExecutionContext.create(credentials),
createPdfOperation = PDFToolsSdk.CreatePDF.Operation.createNew();
// Set operation input from a source file
const input = PDFToolsSdk.FileRef.createFromLocalFile(source);
createPdfOperation.setInput(input);
let stream = new Stream.Writable();
stream.write = function() {
}

stream.end = function() {
console.log('end called');
resolve(stream);
}
// Execute the operation and Save the result to the specified location.
createPdfOperation.execute(executionContext)
.then(result => resolve(result))
.catch(err => {
if(err instanceof PDFToolsSdk.Error.ServiceApiError
|| err instanceof PDFToolsSdk.Error.ServiceUsageError) {
reject(err);
} else {
reject(err);
}
});
});
}
async function ocrPDF(source, creds) {
return new Promise((resolve, reject) => {
const credentials =  PDFToolsSdk.Credentials
.serviceAccountCredentialsBuilder()
.fromFile(creds)
.build();
const executionContext = PDFToolsSdk.ExecutionContext.create(credentials),
ocrOperation = PDFToolsSdk.OCR.Operation.createNew();
// Set operation input from a source file.
//const input = PDFToolsSdk.FileRef.createFromStream(source);
ocrOperation.setInput(source);
let stream = new Stream.Writable();
stream.end = function() {
console.log('end called');
resolve(stream);
}
// Execute the operation and Save the result to the specified location.
ocrOperation.execute(executionContext)
.then(result => resolve(result))
.catch(err => reject(err));
});
}

相关内容

最新更新