转换 PDF 以获得矢量化文本 ("convert all text to outlines")

Convert PDF to get vectorized text ("convert all text to outlines")

我正在使用 nodejs 并且正在处理 PDF。我想做的一件事是 勾勒出 PDF 的所有字体 (这样以后就不能用鼠标光标选择它们了) .

我尝试了 pdftkflatten 命令(使用节点包装器),但我没有得到我想要的。

我可能会使用 inkscape(命令行),但我什至不确定如何使用。我真的在寻找使用 nodejs.

最简单的方法

可能还有一首使用 ghostscript 的曲目:。需要注意的一件值得注意的事情是我不使用磁盘上的文件,而是使用 Buffer 对象,因此在本地保存 PDF 然后使用 gs 命令会很痛苦。

非常感谢。

我终于跟上了@KenS的方式:

import util from 'util';
import childProcess from 'child_process';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { v4 as uuidv4 } from 'uuid';

const exec = util.promisify(childProcess.exec);

const unlinkCallback = (err) => {
  if (err) {
    console.error(err);
  }
};

const deleteFile = (path: fs.PathLike) => {
  if (fs.existsSync(path)) {
    fs.unlink(path, unlinkCallback);
  }
};

const createTempPathPDF = () => path.join(os.tmpdir(), `${uuidv4()}.pdf`);

const convertFontsToOutlines = async (buffer: Buffer): Promise<Buffer> => {
  const inputPath = createTempPathPDF();
  const outputPath = createTempPathPDF();
  let bufferWithOutlines: Buffer;

  fs.createWriteStream(inputPath).write(buffer);

  try {
    // ! ghostscript package MUST be installed on system
    await exec(`gs -o ${outputPath} -dNoOutputFonts -sDEVICE=pdfwrite ${inputPath}`);

    bufferWithOutlines = fs.readFileSync(outputPath);
  } catch (e) {
    console.error(e);

    bufferWithOutlines = buffer;
  }

  deleteFile(inputPath);
  deleteFile(outputPath);

  return bufferWithOutlines;
};