使用 node.js 和 pdf.js 将 pdf 转换为 html 文件

7
我希望使用pdf.js将pdf转换为html页面。Pdf.js能够在浏览器中完成此操作,但是否可以在后端取得由浏览器呈现的html页面,从而将n页的pdf转换为n个html文件?我正在使用node.js作为后端。我已尝试过pdf2html和其他类似的npm模块,但它们的效果不佳,并且在处理某些pdf时存在问题。谢谢您的建议。

您的解决方案在这里-> https://bytescout.com/articles/cloud-api-pdf-to-html-javascript-convert-pdf-to-html-from-uploaded-file-node-js - Anand Choudhary
这不是免费的!:( - last_fix
pdf.js可以将PDF转换为图像(画布、PNG等),但它无法将PDF转换为HTML。 - shaochuancs
1个回答

3
也许我找到了类似的东西 - 我正在使用本地PDF文件和浏览器工作。我对现成的viewer.js / PDF.js做了一些小改动,应该可以在Node.js和浏览器中处理。
这个脚本包含通过参数指定的PDF文件,并启动浏览器。
const fs = require('fs');
const path = require('path');
const pdf = require('process').argv[2];
const chp = require('child_process');
const datauri = require(path.join(process.env.APPDATA, 'npm/node_modules', 'datauri'));
datauri(pdf, (err, content, meta) => {
    if (err) {
        throw err;
    }
    const viewerJSpath = path.join(__dirname, './viewer.js');
    let wp = fs.readFileSync(viewerJSpath, 'utf-8');
    const pdfName = 'compressed.tracemonkey-pldi-09.pdf';
    const srcPos = [wp.indexOf(pdfName)];
    srcPos.push(srcPos[0] + pdfName.length);
    let HOSTED_VIEWER_ORIGINS = wp.indexOf('HOSTED_VIEWER_ORIGINS');
    HOSTED_VIEWER_ORIGINS = wp.indexOf(']', HOSTED_VIEWER_ORIGINS);
    wp = wp.substr(0, srcPos[0]) + content +
    wp.substr(srcPos[1], HOSTED_VIEWER_ORIGINS - srcPos[1]) + ', "file://"' +
    wp.substr(HOSTED_VIEWER_ORIGINS);
    fs.writeFileSync(viewerJSpath, wp, 'utf-8');
    const c = path.join(__dirname, 'viewer.html');
    chp.execSync(c);
});

尝试将原始宽度作为下一个样式参数添加到renderTextLayer的appendText方法中,并按位置对元素进行排序,然后在TextLayerBuilder的render方法中执行next2 this.textLayerDiv.appendChild(textLayerFrag);

我的Github上提到的所有PDF.js更改,似乎只需要webbuild文件夹(除了npm i -g datauri fox example)。


使用puppeteer和稍微修改过的PDF.js,可以直接转换(适用于head/less,但元素大小略有不同)。

const fs = require('fs');
const path = require('path');
const pdf = require('process').argv[2];
const datauri = require(path.join(process.env.APPDATA, 'npm/node_modules', 'datauri'));
const puppeteer = require(path.join(process.env.APPDATA, 'npm/node_modules', 'puppeteer'));
datauri(pdf, (err, content, meta) => {
    if (err) {
        throw err;
    }
    const viewerJSpath = path.join(__dirname, './viewer');
    let wp = fs.readFileSync(viewerJSpath + 'Src.js', 'utf-8');
    const pdfName = 'compressed.tracemonkey-pldi-09.pdf';
    const srcPos = [wp.indexOf(pdfName)];
    srcPos.push(srcPos[0] + pdfName.length);
    let HOSTED_VIEWER_ORIGINS = wp.indexOf('HOSTED_VIEWER_ORIGINS');
    HOSTED_VIEWER_ORIGINS = wp.indexOf(']', HOSTED_VIEWER_ORIGINS);
    wp = wp.substr(0, srcPos[0]) + content +
    wp.substr(srcPos[1], HOSTED_VIEWER_ORIGINS - srcPos[1]) + ', "file://"' +
    wp.substr(HOSTED_VIEWER_ORIGINS);
    fs.writeFileSync(viewerJSpath + '.js', wp, 'utf-8');
    (async () => {
        const browser = await puppeteer.launch({
            // headless: false
        });
        const page = await browser.pages();
        const c = path.join(__dirname, 'viewer.html');
        await page[0].goto('file:///' + c);
        page[0].exposeFunction('reader', (elLists) => {
            fs.writeFileSync(path.join(__dirname, 'PDFtexts.txt'), JSON.stringify(elLists, null, 4));
            setTimeout(() => { browser.close(); }, 100);
        });
    })();
});

puppeteer/chromium 需要修复的问题:

const message = exception?.message; // => exception.message
page: this.pageLabel ?? this.id // => this.pageLabel || this.id

viewer.js => viewerSrc.js 的基本添加:

function webViewerPageRendered({
...
  if (pageNumber < PDFViewerApplication.pagesCount) {
    arguments[0].source.eventBus.dispatch("pagenumberchanged", {
      value: pageNumber + 1
    }); // generate all remaining pages
  }
}

class BaseViewer {
  constructor(options) {
    this.pageNo = []; // rendered pages array
...
  _setCurrentPageNumber(val, resetCurrentPageView = false) {
...
    if (this.pageNo.indexOf(val) < 0) {
      this.pageNo.push(val);
    }
    if (this.pagesCount - 1 <= this.pageNo.length) {
      window.reader(elLists); // sent result back 2 node.js
    }

结果看起来像 {页码:{元素编号:{数据}, ...}, ...},可以简单地转换为网页或进一步处理。

{
    "1": {
        "0": {
            "x": 99.9871,
            "y": 98.0496,
            "w": 557.695,
            "h": 22,
            "text": "Trace-based Just-in-Time Type Specialization for Dynamic",
            "ff": "sans-serif",
            "fs": "22.2695px",
            "cssText": "left: 99.9871px; top: 98.0496px; width: 557.695px; font-size: 22.2695px; font-family: sans-serif; transform: scaleX(0.970163);"
        },
        "1": {
            "x": 327.478,
            "y": 122.793,
            "w": 102.707,
            "h": 22,
            "text": "Languages",
            "ff": "sans-serif",
            "fs": "22.2695px",
            "cssText": "left: 327.478px; top: 122.793px; width: 102.707px; font-size: 22.2695px; font-family: sans-serif; transform: scaleX(0.932262);"
        },
...
    "2": {
        "0": {
            "x": 393.677,
            "y": 90.3408,
            "w": 192.909,
            "h": 11,
            "text": "1 for (var i = 2; i < 100; ++i) {",
            "ff": "monospace",
            "fs": "11.1347px",
            "cssText": "left: 393.677px; top: 90.3408px; width: 192.909px; font-size: 11.1347px; font-family: monospace; transform: scaleX(0.875232);"
        },
        "1": {
            "x": 67.0588,
            "y": 91.7599,
            "w": 173.346,
            "h": 11,
            "text": "Hence, recording and compiling a trace",
            "ff": "sans-serif",
            "fs": "11.1347px",
            "cssText": "left: 67.0588px; top: 91.7599px; width: 173.346px; font-size: 11.1347px; font-family: sans-serif; transform: scaleX(0.895175);"
        },

1
在线演示在此 - PDF 下载已更改为 HTM 下载(文本层)https://eltomjan.github.io/JStoolsSPAdemos/pdf2htm/web/viewer.html - Tom
完美的工作!!那么我该如何使用您的解决方案将PDF转换为HTML呢?我可以通过CMD命令进行操作吗,还是需要使用一些JS命令创建HTML文件? - Demetry Pascal
1
还不确定,但是我查了一下我的github,有一个简单的Node.js脚本,我曾经在我盲人朋友的机器上使用过它作为默认PDF阅读器的批处理文件,以获得最佳的屏幕阅读器体验。它使用puppeteer进行自动化(而不是使用过于安全的常见浏览器)。Mozilla曾有过这样的争论:“像这样的东西的问题很可能是在许多文档中它的工作效果并不好,还要考虑到PDF文档可以使用从左到右、从右到左或从上到下的阅读顺序,以及代码的性能/可维护性的问题。” - Tom
1
一般来说,像 https://github.com/mozilla/pdf.js/issues/6269 这样的问题可能是在这里前进的最合理方式。 - Tom
全新的https://github.com/eltomjan/ETEhomeTools/blob/master/HTM_HTA/Responsive2CSV.js基于这些脚本,将响应式HTML/表格转换为XL。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接