admin管理员组

文章数量:1327308

I am using pdf.js to extract text from the pdf but the font name appears as g_d0_f6 etc. I need the font name to use the appropriate table for converting to Unicode. Here is the code derived from pdf2svg.js sample:-

var fs = require('fs');
var util = require('util');
var path = require('path');
var stream = require('stream');

// HACK few hacks to let PDF.js be loaded not as a module in global space.
require('./domstubs.js').setStubs(global);

var pdfjsLib = require('pdfjs-dist');

var pdfPath = process.argv[2] || '../../web/pressed.tracemonkey-pldi-09.pdf';
var data = new Uint8Array(fs.readFileSync(pdfPath));

var loadingTask = pdfjsLib.getDocument({
  data: data,
  nativeImageDecoderSupport: pdfjsLib.NativeImageDecoding.DISPLAY,
});
loadingTask.promise.then(function(doc) {
  var lastPromise = Promise.resolve(); // will be used to chain promises
  var loadPage = function (pageNum) {
    return doc.getPage(pageNum).then(function (page) {
      return page.getTextContent().then(function (textContent) {
    console.log(textContent);
        });
      });
    };

  for (var i = 1; i <= doc.numPages; i++) {
    lastPromise = lastPromise.then(loadPage.bind(null, i));
  }
  return lastPromise;
}).then(function () {
  console.log('# End of Document');
}, function (err) {
  console.error('Error: ' + err);
});

Sample output:-

{ items: 
   [ { str: 'bl fp=k osQ ckjs esa cPpksa ls ckrphr djsa & ;g LowQy esa fdl le; dk n`\'; gS\\ cPps',
       dir: 'ltr',
       width: 396.2250000000001,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 'D;k dj jgs gSa\\ cPps dkSu&dkSu ls [ksy] [ksy j',
       dir: 'ltr',
       width: 216.1650000000001,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 'g',
       dir: 'ltr',
       width: 6.42,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 's gSa\\ fp=k esa fdrus cPps gSa vkSj fdrus',
       dir: 'ltr',
       width: 173.865,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 'cM+s gSa\\ vkil esa dkSu D;k ckr dj jgk gksxk\\ cPpksa ls fp=k esa lcosQ fy, uke lkspus',
       dir: 'ltr',
       width: 396.54000000000013,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 'dks dgasaA',
       dir: 'ltr',
       width: 40.74,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 'csVh cpkvks',
       dir: 'ltr',
       width: 66.725,
       height: 17,
       transform: [Array],
       fontName: 'g_d0_f2' },
     { str: 'csVh i<+kvksA',
       dir: 'ltr',
       width: 66.75899999999999,
       height: 17,
       transform: [Array],
       fontName: 'g_d0_f2' },
     { str: '2018-19',
       dir: 'ltr',
       width: 36.690000000000005,
       height: 10,
       transform: [Array],
       fontName: 'g_d0_f3' } ],
  styles: 
   { g_d0_f1: 
      { fontFamily: 'sans-serif',
        ascent: 0.837,
        descent: -0.216,
        vertical: false },
     g_d0_f2: 
      { fontFamily: 'sans-serif',
        ascent: 0.786,
        descent: -0.181,
        vertical: false },
     g_d0_f3: 
      { fontFamily: 'sans-serif',
        ascent: 0.9052734375,
        descent: -0.2119140625,
        vertical: false } } }

And here is the pdf that uses embedded fonts: .pdf

Here is a related question but the suggested monObjs is empty: pdf.js get info about embedded fonts

I am using pdf.js to extract text from the pdf but the font name appears as g_d0_f6 etc. I need the font name to use the appropriate table for converting to Unicode. Here is the code derived from pdf2svg.js sample:-

var fs = require('fs');
var util = require('util');
var path = require('path');
var stream = require('stream');

// HACK few hacks to let PDF.js be loaded not as a module in global space.
require('./domstubs.js').setStubs(global);

var pdfjsLib = require('pdfjs-dist');

var pdfPath = process.argv[2] || '../../web/pressed.tracemonkey-pldi-09.pdf';
var data = new Uint8Array(fs.readFileSync(pdfPath));

var loadingTask = pdfjsLib.getDocument({
  data: data,
  nativeImageDecoderSupport: pdfjsLib.NativeImageDecoding.DISPLAY,
});
loadingTask.promise.then(function(doc) {
  var lastPromise = Promise.resolve(); // will be used to chain promises
  var loadPage = function (pageNum) {
    return doc.getPage(pageNum).then(function (page) {
      return page.getTextContent().then(function (textContent) {
    console.log(textContent);
        });
      });
    };

  for (var i = 1; i <= doc.numPages; i++) {
    lastPromise = lastPromise.then(loadPage.bind(null, i));
  }
  return lastPromise;
}).then(function () {
  console.log('# End of Document');
}, function (err) {
  console.error('Error: ' + err);
});

Sample output:-

{ items: 
   [ { str: 'bl fp=k osQ ckjs esa cPpksa ls ckrphr djsa & ;g LowQy esa fdl le; dk n`\'; gS\\ cPps',
       dir: 'ltr',
       width: 396.2250000000001,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 'D;k dj jgs gSa\\ cPps dkSu&dkSu ls [ksy] [ksy j',
       dir: 'ltr',
       width: 216.1650000000001,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 'g',
       dir: 'ltr',
       width: 6.42,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 's gSa\\ fp=k esa fdrus cPps gSa vkSj fdrus',
       dir: 'ltr',
       width: 173.865,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 'cM+s gSa\\ vkil esa dkSu D;k ckr dj jgk gksxk\\ cPpksa ls fp=k esa lcosQ fy, uke lkspus',
       dir: 'ltr',
       width: 396.54000000000013,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 'dks dgasaA',
       dir: 'ltr',
       width: 40.74,
       height: 15,
       transform: [Array],
       fontName: 'g_d0_f1' },
     { str: 'csVh cpkvks',
       dir: 'ltr',
       width: 66.725,
       height: 17,
       transform: [Array],
       fontName: 'g_d0_f2' },
     { str: 'csVh i<+kvksA',
       dir: 'ltr',
       width: 66.75899999999999,
       height: 17,
       transform: [Array],
       fontName: 'g_d0_f2' },
     { str: '2018-19',
       dir: 'ltr',
       width: 36.690000000000005,
       height: 10,
       transform: [Array],
       fontName: 'g_d0_f3' } ],
  styles: 
   { g_d0_f1: 
      { fontFamily: 'sans-serif',
        ascent: 0.837,
        descent: -0.216,
        vertical: false },
     g_d0_f2: 
      { fontFamily: 'sans-serif',
        ascent: 0.786,
        descent: -0.181,
        vertical: false },
     g_d0_f3: 
      { fontFamily: 'sans-serif',
        ascent: 0.9052734375,
        descent: -0.2119140625,
        vertical: false } } }

And here is the pdf that uses embedded fonts: http://ncert.nic.in/textbook/pdf/ahhn101.pdf

Here is a related question but the suggested monObjs is empty: pdf.js get info about embedded fonts

Share Improve this question edited Feb 25, 2019 at 2:16 Md. Abu Taher 18.9k5 gold badges57 silver badges78 bronze badges asked Feb 11, 2019 at 12:32 HimanshuHimanshu 2,4543 gold badges25 silver badges42 bronze badges 1
  • 1 "I need the font name to use the appropriate table for converting to Unicode" - in general one cannot determine that from the font name at all. – mkl Commented Feb 24, 2019 at 16:58
Add a ment  | 

2 Answers 2

Reset to default 4 +50

Note: The answer below does not have anything to do with pdf.js, however it answers the question, Extract Font Name from PDF.

I did not find a solution yet, so I went ahead and grabbed mutool, which has has the following mand to get the font information per page.

mutool info -F input.pdf 0-2147483647

Then I grabbed the spawn function, hacked the output through some regex and pattern matching to return the data.

const extractFontData = async str => {
  const getMatches = str => {
    const regex = /Page (\d+):\nFonts \((\d+)\):/;
    const match = str.match(regex);
    if (match) {
      return { page: match[1], fonts: match[2] };
    }
    return {};
  };

  const singleFont = fontData => {
    const match = fontData.match(/\+([a-zA-Z0-9_-]+[.,]?[a-zA-Z0-9_-]+)/);
    return match && match[1];
  };

  return str
    .split("Page ")
    .map(singlePageData => {
      const { page, fonts } = getMatches(`Page ` + singlePageData);
      if (fonts) {
        const split = singlePageData.split("\n").filter(e => e.length);
        const fontList = split.slice(2).map(singleFont);
        return { page, fonts, fontList };
      }
    })
    .filter(e => e);
};

// Taken and adjusted from: https://stackoverflow./a/52611536/6161265
function run(...cmd) {
  return new Promise((resolve, reject) => {
    var { spawn } = require("child_process");
    var mand = spawn(...cmd);
    var result = "";
    mand.stdout.on("data", function(data) {
      result += data.toString();
    });
    mand.on("close", function(code) {
      resolve(result);
    });
    mand.on("error", function(err) {
      reject(err);
    });
  });
}

async function wrapper(filePath) {
  const data = await run("mutool", ["info", "-F", filePath, "0-2147483647"]);
  return extractFontData(data);
}

Sample usage:

wrapper("ahhn101.pdf").then(data => console.log(data));

Result:

I think you were on the right track: page.monObjs is where the actual font name is found. However, page.monObjs only gets populated when the page's text/operators are accessed, so you'll find it empty if you look before that happens.

本文标签: javascriptExtract Font Name from PDFStack Overflow