fix: repair Chinese PDF text and sync native component selection

This commit is contained in:
阿白叔 committed 2026-10-11 10:53:02 +08:00
1 parent 734a10b5c7
commit 12ce0c4140
23 files changed
+988 -5

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
from pathlib import Path
import threading
import pytest
from pypdf import PdfReader, PdfWriter
from pypdf.generic import ArrayObject, ByteStringObject, ContentStream, DictionaryObject, FloatObject, NameObject, NumberObject
from dx_productivity.features.pdf_export import exporter
from dx_productivity.features.pdf_export.models import ExportScope, PdfExportSettings
def legacy_pdf(path, text='输入网络 输出网络 Ω μ ± ×', *, raw=None, compound=False):
writer = PdfWriter()
page = writer.add_blank_page(640, 240)
font = DictionaryObject({NameObject('/Type'): NameObject('/Font'), NameObject('/Subtype'): NameObject('/Type1'),
NameObject('/BaseFont'): NameObject('/Courier'), NameObject('/Encoding'): NameObject('/WinAnsiEncoding')})
page[NameObject('/Resources')] = DictionaryObject({NameObject('/Font'): DictionaryObject({NameObject('/F1'): writer._add_object(font)})})
stream = ContentStream(None, writer)
value = ByteStringObject(raw if raw is not None else text.encode('gbk'))
stream.operations = [([NumberObject(1), NumberObject(0), NumberObject(0)], b'RG'),
([NumberObject(10), NumberObject(20)], b'm'), ([NumberObject(600), NumberObject(20)], b'l'), ([], b'S'),
([], b'BT'), ([NameObject('/F1'), NumberObject(14)], b'Tf'),
([FloatObject(80)], b'Tz'), ([NumberObject(20), NumberObject(120)], b'Td'),
([ArrayObject([value])], b'TJ') if compound else ([value], b'Tj'), ([], b'ET')]
page[NameObject('/Contents')] = writer._add_object(stream)
writer.add_outline_item('Main Sheet Analog', 0)
with Path(path).open('wb') as output:
writer.write(output)
def test_chinese_repair_embeds_unicode_and_keeps_native_vectors_and_bookmark(tmp_path):
from dx_productivity.features.pdf_export.text_repair import repair_text
file = tmp_path / 'native.pdf'
legacy_pdf(file)
before = PdfReader(file)
geometry = [(a, o) for a, o in ContentStream(before.pages[0].get_contents(), before).operations if o in (b'RG', b'rg', b'm', b'l', b'S', b'Td')]
result = repair_text(file, 'chinese', threading.Event())
after = PdfReader(file, strict=True)
assert '输入网络 输出网络 Ω μ ± ×' in after.pages[0].extract_text()
assert after.outline[0].title == 'Main Sheet Analog'
assert geometry == [(a, o) for a, o in ContentStream(after.pages[0].get_contents(), after).operations if o in (b'RG', b'rg', b'm', b'l', b'S', b'Td')]
assert list(before.pages[0].mediabox) == list(after.pages[0].mediabox)
assert result['repaired_strings'] == 1
for font in after.pages[0]['/Resources']['/Font'].values():
font = font.get_object()
if font.get('/Subtype') == '/Type0':
assert font['/ToUnicode'].get_data()
assert font['/DescendantFonts'][0]['/FontDescriptor']['/FontFile2'].get_data()
def test_western_mode_keeps_engineering_symbols_without_gbk_guess(tmp_path):
from dx_productivity.features.pdf_export.text_repair import repair_text
file = tmp_path / 'symbols.pdf'
legacy_pdf(file, raw='±× µ± ÉÉ'.encode('cp1252'))
repair_text(file, 'western', threading.Event())
assert '±× µ± ÉÉ' in PdfReader(file).pages[0].extract_text()
def test_unsupported_text_and_cancellation_preserve_staging_bytes(tmp_path):
from dx_productivity.features.pdf_export.text_repair import repair_text
file = tmp_path / 'compound.pdf'
legacy_pdf(file, compound=True)
before = file.read_bytes()
with pytest.raises(ValueError, match='TJ'):
repair_text(file, 'chinese', threading.Event())
assert file.read_bytes() == before
cancel = threading.Event()
cancel.set()
with pytest.raises(InterruptedError):
repair_text(file, 'chinese', cancel)
assert file.read_bytes() == before
def test_native_mode_preserves_bytes_and_uses_original_mapping(tmp_path):
from dx_productivity.features.pdf_export.text_repair import repair_text
file = tmp_path / 'native.pdf'
legacy_pdf(file)
before = file.read_bytes()
repair_text(file, 'original', threading.Event())
assert file.read_bytes() == before
assert '-udx' not in exporter.build_command(Path('sch2pdf.exe'), Path('Demo.prj'), file, ExportScope.PROJECT)
assert '-udx' in exporter.build_command(Path('sch2pdf.exe'), Path('Demo.prj'), file, ExportScope.PROJECT, text_mode='original')
def test_exporter_repairs_text_before_publishing(tmp_path, monkeypatch):
source = tmp_path / 'source'
(source / 'database').mkdir(parents=True)
project = source / 'Demo.prj'
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir ".\\database"\n')
engine = tmp_path / 'sch2pdf.exe'
engine.touch()
settings = PdfExportSettings(project, ExportScope.CURRENT_PAGE, 'Main', tmp_path / 'output', engine_path=engine)
def native(command, *_args, **_kwargs):
assert '-udx' not in command
legacy_pdf(Path(command[command.index('-a') + 1]))
return 0
monkeypatch.setattr(exporter, 'run_engine', native)
result = exporter.export_project(settings, threading.Event(), active_block_name='Main', active_sheet_name='Analog', local_app_data=tmp_path / 'state')
assert result.state == 'success', result.message
assert '输入网络' in PdfReader(result.output_path).pages[0].extract_text()
assert (result.run_dir / 'text-check.json').is_file()