使用pdf.js在pdf到文本转换中将换行符显示为`\ n` [英] Display line breaks as `\n` in pdf to text conversion using pdf.js

查看:467
本文介绍了使用pdf.js在pdf到文本转换中将换行符显示为`\ n`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了本教程中的代码

I used the code from this tutorial http://ourcodeworld.com/articles/read/405/how-to-convert-pdf-to-text-extract-text-from-pdf-with-javascript to set up the pdf to text conversion.

在此站点上浏览了所有内容 https://mozilla.github.io/pdf.js/获取有关如何设置转换格式的一些提示,但找不到任何内容.我只是想知道是否有人在使用pdf.js解析文本时如何将换行符显示为\n的想法.

Looked all over on this site https://mozilla.github.io/pdf.js/ for some hints as to how to format the conversion, but couldn't find anything. I am just wondering if anyone has any idea of how to display line breaks as \n when parsing text using pdf.js.

先谢谢了.

推荐答案

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

In PDF there no such thing as controlling layout using control chars such as '\n' -- glyphs in PDF positioned using exact coordinates. Use text y-coordinate (can be extracted from transform matrix) to detect a line change.

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>

这篇关于使用pdf.js在pdf到文本转换中将换行符显示为`\ n`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆