Extracting text from pdfs with embedded fonts
14:26 04 Jun 2024

I need to extract text from pdf files - seems simple enough. Here is my problem.

When i open the pdf in a pdfviewer like Adobe Acrobat I see the text as normal text i can read it.

When i use iText7 for example to extract text i get texts like this one R!"ina sa$!m!js even though it should be Rēķina saņēmējs

The problem is the embedded fonts where the character ! is the unicode char but when the font is applied it is rendered as ē.

Any ideas how to handle this. I tried to extract the fonts themselves from the pdf like this

using System;
using System.IO;
using iText.IO.Source;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas.Parser;
using iText.Kernel.Pdf.Canvas.Parser.Listener;

class PdfFontExtractor
{
private string pdfPath;
private string outputDir;

public PdfFontExtractor(string pdfPath, string outputDir)
{
    this.pdfPath = pdfPath;
    this.outputDir = outputDir;

    if (!Directory.Exists(outputDir))
    {
        Directory.CreateDirectory(outputDir);
    }
}

public void ExtractFonts()
{
    using (PdfReader reader = new PdfReader(pdfPath))
    {
        using (PdfDocument pdfDoc = new PdfDocument(reader))
        {
            for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)
            {
                PdfPage page = pdfDoc.GetPage(i);
                ExtractFontsFromPage(page);
            }
        }
    }
}

private void ExtractFontsFromPage(PdfPage page)
{
    PdfDictionary resources = page.GetResources().GetResource(PdfName.Font);

    foreach (PdfName fontName in resources.KeySet())
    {
        PdfDictionary fontDict = resources.GetAsDictionary(fontName);
        ExtractFont(fontDict);
    }
}

private void ExtractFont(PdfDictionary fontDict)
{
    PdfDictionary fontDescriptor = fontDict.GetAsDictionary(PdfName.FontDescriptor);
    if (fontDescriptor != null)
    {
        PdfStream fontFileStream = null;

        if (fontDescriptor.ContainsKey(PdfName.FontFile))
            fontFileStream = fontDescriptor.GetAsStream(PdfName.FontFile);
        else if (fontDescriptor.ContainsKey(PdfName.FontFile2))
            fontFileStream = fontDescriptor.GetAsStream(PdfName.FontFile2);
        else if (fontDescriptor.ContainsKey(PdfName.FontFile3))
            fontFileStream = fontDescriptor.GetAsStream(PdfName.FontFile3);

        if (fontFileStream != null)
        {
            byte[] fontData = fontFileStream.GetBytes();

            if (fontData.Length > 1000)
            {
                string fontName = fontDict.GetAsName(PdfName.BaseFont).GetValue();
                fontName = fontName + ".ttf";

                string fontPath = Path.Combine(outputDir, fontName);
                File.WriteAllBytes(fontPath, fontData);
                Console.WriteLine($"Extracted font: {fontPath}");
            }
            else
            {
                Console.WriteLine(
                    $"Skipped invalid font: {fontDict.GetAsName(PdfName.BaseFont).GetValue()}"
                );
            }
        }
    }
}

}

It creates the files but they cannot be opened them. I know it is possible to extract them using online tools like i2PDF Maybe my code needs something.

My approach would be:

  1. extract the fonts from the pdf
  2. create images from the glyphs in the fonts
  3. OCR the images and compare to the unicode chars the glyphs represent
  4. change the text in the returned pdf text based on the gathered data

This is not a one off and the incoming pdf are with variations, so i want to automate this that i can give the program a pdf and it can return the correct text.

Solution is not manditory in c#. Python could be good as well.

c# pdf itext itext7