Example using cairo and Pango (Linux/macOS):
Use weasyprint or xhtml2pdf with HTML/CSS that already handles Khmer shaping. 2. Extracting Text from Khmer PDFs Using PyMuPDF (fitz) PyMuPDF handles Khmer Unicode extraction well.
c.save() data = "ចំណងជើង": "របាយការណ៍ប្រចាំឆ្នាំ", "កាលបរិច្ឆេទ": "២០២៥-០៣-០១"
layout = pangocairo_context.create_layout() layout.set_text("កម្ពុជា") layout.set_font_description(pango.FontDescription("Khmer OS 12")) python khmer pdf
Khmer script (អក្សរខ្មែរ) presents unique challenges when generating or extracting PDFs programmatically. Unlike Latin-based scripts, Khmer requires correct rendering of subscripts, diacritics, and vowel ordering. Python offers several libraries to handle these tasks, but careful font and encoding choices are critical. 1. Generating PDFs with Khmer Text Using reportlab Reportlab is a powerful PDF generation library, but it does not natively support complex script shaping. To generate correct Khmer PDFs:
import cairo import pangocairo surface = cairo.PDFSurface("shaped_khmer.pdf", 200, 100) context = cairo.Context(surface) pangocairo_context = pangocairo.CairoContext(context) pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
pangocairo_context.update_layout(layout) pangocairo_context.show_layout(layout) surface.finish() For scanned Khmer PDFs, convert to images then use Tesseract with Khmer language pack. Example using cairo and Pango (Linux/macOS): Use weasyprint
y = 800 for key, value in content.items(): c.drawString(50, y, f"key: value") y -= 20
from pypdf import PdfReader reader = PdfReader("khmer_document.pdf") for page in reader.pages: print(page.extract_text()) Khmer requires reordering of vowels and diacritics. Use pyftsubset + harfbuzz (via weasyprint or cairo ) for proper shaping.
with open(data_yaml, 'r', encoding='utf-8') as f: content = yaml.safe_load(f) c = canvas.Canvas("khmer_sample.pdf"
import fitz # PyMuPDF doc = fitz.open("khmer_document.pdf") for page in doc: text = page.get_text() print(text) pdfplumber extracts text while preserving layout, good for Khmer.
c = canvas.Canvas("khmer_sample.pdf", pagesize=A4) c.setFont('KhmerFont', 14) c.drawString(100, 750, "សួស្តីពិភពលោក") # "Hello World" in Khmer c.save() ⚠️ Ensure the TrueType font supports Khmer and is placed in your working directory. fpdf2 can embed Unicode fonts, but complex scripts like Khmer often break due to lack of proper shaping.
© 2023 Disk Imager. Копирование материалов сайта разрешается только с указанием ссылки на источник