Files
wpep/tools/gp/cli/handlers.ts
T

114 lines
3.3 KiB
TypeScript

import { DocuBuilder, IndexBuilder } from "../pdf_builder/builder.ts";
export async function generate_pdf() {
const cfg = JSON.parse(await Deno.readTextFile("config.json"));
for (const config of cfg.settings) {
const builder = new DocuBuilder(config);
try {
await builder.with_browser();
console.debug(`Processing config: ${JSON.stringify(config)}`);
builder.with_files_sync(config.journal.from_directory);
await builder.as_html_page();
await builder.build_as_pdf(config.playwright);
} finally {
await builder.close_browser();
}
}
}
export async function generate_md() {
const cfg = JSON.parse(await Deno.readTextFile("config.json"));
try {
for (const config of cfg.settings) {
const builder = new DocuBuilder(config);
console.debug(`Processing config: ${JSON.stringify(config)}`);
builder.with_files_sync(config.journal.from_directory);
await builder.as_markdown();
const markdownPath = config.md?.path ?? config.markdown_output;
if (!markdownPath) {
throw new Error("Missing markdown output path in config. Use md.path.");
}
await builder.build_as_raw(markdownPath);
}
} finally {
// No browser to close in this function
}
}
export async function add_index_to_pdf(insert_index_after_page: number = 1) {
const config = JSON.parse(await Deno.readTextFile("config.json"));
for (const cfg of config.settings) {
console.log(`Adding index to PDF ${cfg.playwright.path}...`);
const indexBuilder = new IndexBuilder(
cfg.playwright.path,
cfg.journal.from_directory,
);
await indexBuilder.build_index();
const _html = indexBuilder.as_html_page();
//console.log(html);
await indexBuilder.html2pdf({
"path": "./tmps/index.pdf",
"format": "A4",
"printBackground": true,
});
//console.log(indexBuilder.indexed_map);
const insertedIndexPages = await indexBuilder
.combine_index_pdf_to_main_pdf(
undefined,
insert_index_after_page,
);
await indexBuilder.add_pdf_outline({
inserted_index_pages: insertedIndexPages,
});
await Deno.remove("./tmps/index.pdf");
}
}
export async function use_qpdf() {
const config = JSON.parse(await Deno.readTextFile("config.json"));
for (const cfg of config.settings) {
if (cfg.pdf.use_qpdf?.enabled) {
console.log(`Using qpdf to linearize PDF ${cfg.playwright.path}...`);
const outputPath = cfg.playwright.path.replace(
/\.pdf$/,
"_linearized.pdf",
);
const qpdfArgs = [
cfg.playwright.path,
cfg.pdf.use_qpdf.options,
outputPath,
];
const cmd = new Deno.Command(
"qpdf",
{
args: qpdfArgs,
stdout: "piped",
stderr: "piped",
},
);
const child = cmd.spawn();
for await (const chunk of child.stdout) {
console.log(new TextDecoder().decode(chunk));
}
const status = await child.status;
console.log(`Status: ${status.code}`);
if (status.code === 0) {
await Deno.remove(cfg.playwright.path);
await Deno.rename(outputPath, cfg.playwright.path);
console.log(`Successfully linearized PDF: ${cfg.playwright.path}`);
} else {
console.error(`Failed to linearize PDF: ${cfg.playwright.path}`);
}
}
}
}