【问题标题】:Display line breaks as `\n` in pdf to text conversion using pdf.js在使用 pdf.js 的 pdf 到文本转换中将换行符显示为 `\n`
【发布时间】:2017-06-05 19:36:00
【问题描述】:

我使用本教程 http://ourcodeworld.com/articles/read/405/how-to-convert-pdf-to-text-extract-text-from-pdf-with-javascript 中的代码来设置 pdf 到文本的转换。

在这个网站https://mozilla.github.io/pdf.js/ 上查看了有关如何格式化转换的一些提示,但找不到任何东西。我只是想知道是否有人知道在使用 pdf.js 解析文本时如何将换行符显示为\n

提前致谢。

【问题讨论】:

  • 你试过用\\r替换任何​​\r\n\\n类似string.replace('\r','\\r').replace('\n','\\n');吗?注意:对于那些不知道\r的人(回车)在某些环境(即 windows)中通常与换行符配对
  • 是的,我试过了。除了 \n 永远不存在。我担心 pdf.js 会忽略换行符。

标签: javascript pdf pdf.js pdftotext


【解决方案1】:

在 PDF 中,没有使用控制字符(例如 '\n')来控制布局这样的事情——PDF 中的字形使用精确坐标定位。使用文本 y 坐标(可以从变换矩阵中提取)来检测线条变化。

var url = "https://cdn.mozilla.net/pdfjs/tracemonkey.pdf";
var pageNumber = 2;
// Load document
PDFJS.getDocument(url).then(function (doc) {
  // Get a page
  return doc.getPage(pageNumber);
}).then(function (pdfPage) {
  // Get page text content
  return pdfPage.getTextContent();
}).then(function (textContent) {
  var p = null;
  var lastY = -1;
  textContent.items.forEach(function (i) {
    // Tracking Y-coord and if changed create new p-tag
    if (lastY != i.transform[5]) {
      p = document.createElement("p");
      document.body.appendChild(p);
      lastY = i.transform[5];
    }
    p.textContent += i.str;
  });
});
<script src="https://npmcdn.com/pdfjs-dist/build/pdf.js"></script>

【讨论】:

    猜你喜欢
    • 2019-10-24
    • 2013-05-23
    • 2014-04-07
    • 2018-01-08
    • 2020-10-25
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多