3

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/compressed.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 commonObjs is empty: pdf.js get info about embedded fonts

Md. Abu Taher
  • 17,395
  • 5
  • 49
  • 73
Himanshu
  • 2,384
  • 2
  • 24
  • 42
  • 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 Feb 24 '19 at 16:58

2 Answers2

4

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 command 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.com/a/52611536/6161265
function run(...cmd) {
  return new Promise((resolve, reject) => {
    var { spawn } = require("child_process");
    var command = spawn(...cmd);
    var result = "";
    command.stdout.on("data", function(data) {
      result += data.toString();
    });
    command.on("close", function(code) {
      resolve(result);
    });
    command.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: enter image description here

Md. Abu Taher
  • 17,395
  • 5
  • 49
  • 73
  • I am not happy that I do not have enough time right now to comment out the code. – Md. Abu Taher Feb 25 '19 at 02:15
  • 1
    Only suggestions might be to just use spawnSync if you aren't running this as part of a host service, since it'd be easier than the span and collecting I/O. Also, may want to collect all the data as a buffer, appending to the end, and then toString the entire result. – Tracker1 Feb 25 '19 at 18:49
  • Thanks for the suggestions, I plan to rewrite, comment and optimize the code, this was just a proof of concept. :) – Md. Abu Taher Feb 25 '19 at 19:18
  • Thanks. I was looking for font names for any given text but this is a great starting point and answers what was asked. – Himanshu Feb 26 '19 at 07:39
1

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

Craig.Feied
  • 2,617
  • 2
  • 16
  • 25