Skip to content

PDF text extraction can fail in complex shaping scenarios #4225

Open

Description

@mm-tea

Description

Compiling a pdf with non-latin (in this case specifically devanagari) text in it can sometimes result is strange text encoding. This results in text that is not properly selectable. The part of the font that is selectable differs across pdf viewers, and sometimes introduces non-existent characters into the selection.

Minimal Working Example:

#set text(font: "Siddhanta")

आ रु॒क्मैरा यु॒धा नर॑ ऋ॒ष्वा ऋ॒ष्टीर॑सृक्षत ।

अन्वे॑नाँ॒ अह॑ वि॒द्युतो॑ म॒रुतो॒ जज्झ॑तीरिव भा॒नुर॑र्त॒ त्मना॑ दि॒वः ॥

(explicitly states font for repeatability)
typst output

This results in the following chunk of selectable text in Ubuntu's Document Viewer:
अा
ैरा युध
ा नर॑ ऋ॒ ष्वा ऋ॒ ीर॑ सृक्षत ꠰
अन्वे॑नाँ॒ अह॑ व॒ ुताे॑ म॒ ताे॒ जज्झ॑ती रव भा॒नुर॑त॒ त्मना॑ द॒वः ꠱

In other pdf viewers the output may be different, e.g. firefox gives:
अा ˳॒ƨैरा यु॒धा नर॑ ऋ॒ष्वा ऋ॒ʆीर॑सृक्षत ꠰
अन्वे॑ नाँ॒ अह॑ Vव॒ȭुताे॑ म॒˳ताे॒ जज्झ॑तीRरव भा॒नुर॑तA॒ त् मना॑ Tद॒वः ꠱
(notice the introduced latin characters)

It seems that this is not an inherent limitation of pdf itself, LuaLaTeX can generate properly functioning pdfs. A minimal working example is provided for LaTeX as well:

\documentclass[a4paper]{article}

\usepackage{fontspec}
\setromanfont{Siddhanta}

\begin{document}

आ रु॒क्मैरा यु॒धा नर॑ ऋ॒ष्वा ऋ॒ष्टीर॑सृक्षत ।

अन्वे॑नाँ॒ अह॑ वि॒द्युतो॑ म॒रुतो॒ जज्झ॑तीरव भनर॑र्त॒ त्मना॑ दि॒वः ॥

\end{document}

LaTeX output

Because of this it seems that it is possible to do this in such a way that makes the text encoding work in pdfs.

Reproduction URL

No response

Operating system

Linux

Typst version

  • I am using the latest version of Typst

Activity

  1. added
    bug
    on May 22, 2024
  2. added
    pdf
    text
    on May 22, 2024
  3. self-assigned this
    on May 22, 2024
  4. LaurenzV commented on Jun 7, 2024

    @LaurenzV
    Collaborator

    Wow! This must have been one of the weirdest things I've ever debugged.

    Okay so basically, when you turn some text into glyphs, OpenType allows you to specify a "script". Depending on which script is activated and on the font, the same set of text can result in a different set of glyphs.

    So basically, in the Latex snippet you posted, what happens is that Latex does not automatically set the script that the text should be shaped with, so none is selected. However, in the case of Typst, the deva script will be detected and selected automatically. If this script is activated, then there are a couple of places where two glyphs correspond to a single codepoint, and in PDF there does not seem to be a proper way of encoding this. Try the following Latex snippet, and you will see that you will also get issues when copy-pasting from a PDF viewer:

    \documentclass{article}
    \usepackage{fontspec}
    \pagenumbering{gobble}
    
    \setmainfont{siddhanta.ttf}[Script=Devanagari]
    
    \begin{document}
    
    आ रु॒क्मैरा यु॒धा नर॑ ऋ॒ष्वा ऋ॒ष्टीर॑सृक्षत ।
    
    अन्वे॑नाँ॒ अह॑ वि॒द्युतो॑ म॒रुतो॒ जज्झ॑तीरव भनर॑र्त॒ त्मना॑ दि॒वः ॥
    
    \end{document}

    If you remove the script part, then you get the expected result. So let's do the same for Typst:

    // Some gibberish script that doesn't exist in the font.
    #set text(font: "Siddhanta", script: "none")
    
    आ रु॒क्मैरा यु॒धा नर॑ ऋ॒ष्वा ऋ॒ष्टीर॑सृक्षत ।
    
    अन्वे॑नाँ॒ अह॑ वि॒द्युतो॑ म॒रुतो॒ जज्झ॑तीरिव भा॒नुर॑र्त॒ त्मना॑ दि॒वः ॥

    and now copy-pasting works as expected... So I don't think there is much we can do to change the behavior in PDF, as you can see this can also be reproduced in Latex, it's just this quirk in how OpenType features are selected that causes that difference to appear... So I'll go ahead and close this issue (feel free to comment again if you have another issue, though).

  5. khaledhosny commented on Jun 9, 2024

    @khaledhosny

    Try Renderer=HarfBuzz and LuaTeX, it should give bettter results here (it basically applies the solution I suggested in my comment on #526).

  6. LaurenzV commented on Jun 9, 2024

    @LaurenzV
    Collaborator

    Thanks, I'll look into it!

  7. Enivex commented on Jun 9, 2024

    @Enivex
    Collaborator

    Try Renderer=HarfBuzz and LuaTeX, it should give bettter results here (it basically applies the solution I suggested in my comment on #526).

    I honestly thought this was the default when using LuaHBTeX

  8. LaurenzV commented on Jun 9, 2024

    @LaurenzV
    Collaborator

    Indeed, seems like at least in Chrome and Acrobat it works when changing to renderer (not in Preview and Firefox, but that's presumably on them), so I guess we will still have to figure something out.. Thanks for the hint!

  9. khaledhosny commented on Jun 9, 2024

    @khaledhosny

    I honestly thought this was the default when using LuaHBTeX

    Unfortunately it is not. Other than using HarfBuzz for shaping, this renderer/mode also tries hard to make text extraction from PDF more reliable, for cases like the one here.

    LibreOffice is another application to check for PDF text extraction issues, it uses a similar mechanism (I wrote the code in both cases).

    Pango with cairo backend should be checked as well as I believe it does something similar (I was not involved with that one and I haven't tested it in a long time, so my information might be outdated).

  10. changed the title [-]Font encoding issues for non-latin text[/-] [+]PDF text extraction fails in complex shaping scenarios[/+] on Jul 15, 2024
  11. changed the title [-]PDF text extraction fails in complex shaping scenarios[/-] [+]PDF text extraction can fail in complex shaping scenarios[/+] on Jul 15, 2024
  12. Waelwindows commented on Sep 4, 2024

    @Waelwindows

    I can replicate this with Arabic with the following snippet

    #set text(lang: "ar")
    == صحفيّة - دَوليَّة
    <صحفية---دولية>
      \"صحفيّة\" \(نسبة إلى \"صحيفة\" مفرد) و\"دَولي\". بل الأصح ان تستخدم
      \"صَحفي\" و\"دَولي\"

    It renders correctly,
    Screenshot 2024-09-04 at 9 53 00 AM

    I'm giving the results from the macos "Preview" app. Firefox and Chromium produces similar but slightly different results.
    The default font on macOS produces almost correct text extraction, it chokes on the diacritics and the parenthesis looks wrong.

    "صحف ّية" )نسبة إلى "صحيفة" مفرد( و" َدولي". بل الأصح ان تستخدم " َصحفي" و" َدولي"
    

    However, if you sent the font to another like Amiri or Scheherazade New, you get even worse extraction
    For Amiri:

    "􏰟حفيّة" )نسبة إلى "􏰟حيفة" مفرد( و"دَولي". بل الأصح ان تستخدم " َ􏰟حفي" و"دَولي"
    

    And for Scheherazade New:

    "􏰗حف ّية" )نسبة إلى "􏰗حيفة" مفرد( و" َدولي". بل ا􏰘􏰗ح ان تستخدم " َ􏰗حفي" و" َدولي"
    

    Just like OP, I get correct text extraction from LibreOffice with the fonts above


    The workaround with unsettling the script is unacceptable as it breaks Arabic shaping, especially with other fonts.

    Screenshot 2024-09-04 at 9 58 48 AM Example with Scheherazade New.

    It does remedy the text extraction slightly:

    "صحف ّية" )نسبة إلى "صحيفة" مفرد( و" َدولي". بل الأصح ان تستخدم " َصحفي" و" َدولي"
    
  13. LaurenzV commented on Sep 4, 2024

    @LaurenzV
    Collaborator

    Just like OP, I get correct text extraction from LibreOffice with the fonts above

    Out of curiosity, do you only get correct extraction when opening it in Chrome, or also in other viewers like Firefox or Apple Preview? From my experiments, the ActualText workaround only works in Chrome/Acrobat...

  14. Waelwindows commented on Sep 4, 2024

    @Waelwindows

    For the LibreOffice export, I got mostly correct extraction from Apple Preview. The first line is Amiri, second is Scheherazade New.

    نسبة إلى "صحيفة" مفرد
    نسبة �إلى "صحيفة" مفرد
    

    Other than the tofu block, it's correct

    As for Chromium, it's slightly worse

    نسبة إلى "صحيفة" مفرد
    نسبة ٕالى "صحيفة" مفرد
    

    It's similar to Apple preview, except the إ was decomposed into ا and ٕ (combining mark).

    Firefox does the worst

    نسبة إلى"صحيفة"مفرد
    لىٕا� نسبة"صحيفة"مفرد
    

    Note there is no spacing around the quotes and "إلى" has been completely broken in Scheherazade New.

    For context, i'm using the versions of the font from nixpkgs rev c3aa7b8938b17aebd2deecf7be0636000d62a2b9.
    Specifically, Amiri 1.000 and Scheherazade New 4.000


    All behavior above, other than Firefox, is better than the current Typst 0.11.1 output

  15. LaurenzV commented on Sep 4, 2024

    @LaurenzV
    Collaborator

    Thanks!

  16. Enivex commented on Jun 26, 2025

    @Enivex
    Collaborator

    Has this been resolved now @LaurenzV ?

  17. LaurenzV commented on Jun 26, 2025

    @LaurenzV
    Collaborator

    No it hasn’t yet.

  18. Sovichea commented on Aug 25, 2026

    @Sovichea

    I have been testing an experimental approach for this class of PDF text-extraction problem.

    The idea is to keep the original Unicode sequence together with the shaped glyphs that visually represent it, instead of deriving text semantics independently from each final glyph.

    With the Devanagari example from this issue, stock Typst can produce duplicated or incorrect extracted text. With the experimental build, the original Unicode round-trips correctly in my tests with Poppler, PyMuPDF, pypdf, and PDFium.

    I have also seen the same underlying problem with Khmer and combining sequences, so this seems to be a general complex-shaping/PDF-text issue rather than something specific to Devanagari.

    As a side effect, the representation can also reduce PDF overhead for complex scripts. In a separate benchmark using ordinary, non-repeated prose, the Devanagari PDF was about 54% smaller than stock output. The benchmark also shows regressions for some scripts, so I consider this an implementation detail rather than the main result:

    https://github.com/Sovichea/typsastra/blob/main/docs/ENHANCED_UNICODE_ENGINE_BENCHMARKS_V0.2.0.md

    Experimental build:

    https://github.com/Sovichea/typsastra/releases/tag/enhanced-unicode-v0.2.0

    Krilla implementation:

    https://github.com/Sovichea/krilla/tree/pdf-logical-unit

    I am sharing this mainly as a working reference and additional data point, not necessarily as the exact upstream solution.

  19. EdgeGreg commented on Sep 26, 2026

    @EdgeGreg

    We see this on Typst 0.15.0 (through typst-py 0.15.0) when exporting tagged PDFs with pdf_standards=["ua-1"] and Noto fonts. The files pass veraPDF's PDF/UA-1 profile, but the text a reader extracts is wrong for Bengali, Arabic, Urdu (Nastaliq) and Persian. Devanagari, Gujarati and Malayalam round-trip correctly in the same setup.

    Minimal source, one file per script (only lang, font and the text change):

    #set document(title: "repro")
    #set text(lang: "bn", font: "Noto Sans Bengali", size: 18pt)
    শিক্ষার্থীর নাম

    Fonts: Noto Sans Bengali 3.011, Noto Naskh Arabic and Noto Nastaliq Urdu (unhinted TTFs from notofonts.github.io at commit f145d86), compiled with system fonts ignored. The text is a plain label ("student's name").

    Script Source (chars) pypdf 6.18 pdfminer.six
    Bengali শিক্ষার্থীর নাম (15) শিশিক্ষাক্ষার্থীর্থীর্থীর নাক্ষাম (33) শিশিক্ষাক্ষার্থীর্থীর্থী র নাক্ষাম (34)
    Arabic (Naskh) اسم الطالب (10) ب الطالباسم (11) ببلاطلا مسا (11)
    Urdu (Nastaliq) طالب علم کا نام (15) مااننن اانکم للعن بببلناانط (27) scrambled (37)
    Persian (Naskh) نام دانش‌آموز (13) زموز‌آ‌آششزن‌آ دامزن (20) scrambled (22)

    Two details that may help:

    • In the Bengali PDF the content stream has /ActualText spans for four clusters (শি, ক্ষা, র্থী, না), yet the extracted text still repeats clusters (ক্ষা reappears after না). It looks as if glyphs split from those spans, such as marks with a vertical offset, still carry the whole cluster's ToUnicode mapping.
    • The Arabic run has no /ActualText at all. Both extractors return it in drawn (visual) order, with an extra ب.

    Happy to test a fix or a nightly build against these samples.

  20. haazeem commented on Oct 21, 2026

    @haazeem

    Same on Typst 0.15.1 with Arabic (IBM Plex Sans Arabic, --pdf-standard a-2a, passes veraPDF 1.30.3). One data point that may help narrow it:

    • The ToUnicode CMap is correct and in logical order for every glyph, including multi-codepoint ones: the lam-alef ligature maps to U+0644 U+0625 (لإ), the fa-ya ligature to U+0641 U+064A (في), a letter with shadda to U+062C U+0651.
    • Readers that rebuild logical order for RTL reverse the visual run including each glyph's multi-codepoint string, so those clusters come out flipped: "الإدارة" → "اإلدارة", "في" → "يف", "غير" → "غري". Seen in pdf.js 4.10 (Firefox), MuPDF (PyMuPDF) and poppler's pdftotext. MuPDF also doubles some combining marks. pypdf keeps the clusters right but leaves words in visual order.
    • ligatures: false does not change it.

    So it looks like the fix is on the writing side: an /ActualText span (logical text) around RTL runs or around each multi-codepoint cluster, which is what readers honour over ToUnicode.

    Minimal source:

    #set text(lang: "ar", dir: rtl, font: "IBM Plex Sans Arabic")
    الإدارة المالية في 11 مهمة غير مسجّل
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugpdftext

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions