Files
pdfer/lib/renderer.ts
2021-02-25 00:34:45 +01:00

52 lines
1.4 KiB
TypeScript

import { mkdir, writeFile } from 'fs'
import { spawn } from 'child_process'
import { v1 as uuidv1 } from 'uuid'
import { getDirPath, getDocPath } from './utils';
function copyToTemp(id: string, texDocument: string): Promise<string> {
return new Promise((resolve, reject) => {
const dirPath = getDirPath(id);
mkdir(dirPath, (err) => {
if (err) {
reject(err);
return;
}
const docPath = getDocPath(id);
writeFile(docPath, texDocument, (err) => {
if (err) {
reject(err);
}
resolve(id);
});
});
});
}
function generateDoc(id: string) {
return new Promise((resolve, reject) => {
const pdflatex = spawn('pdflatex', ['-interaction', 'nonstopmode', getDocPath(id)], { cwd: getDirPath(id) });
pdflatex.stderr.on('data', (data) => {
console.error('onData', data);
});
pdflatex.on('close', (code) => {
if (code > 0) {
reject(`pdflatex returned with code ${code}`);
return;
}
console.log(`PDF ${id} generated`);
resolve(id);
});
});
}
export default function(texDocument: string) {
const id = uuidv1();
return copyToTemp(id, texDocument)
.then(generateDoc);
};