Files

331 lines
18 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from pathlib import Path
import threading
import pytest
from pypdf import PdfReader, PdfWriter
from pypdf.generic import (DictionaryObject,NameObject,NumberObject,ArrayObject,FloatObject,TextStringObject,ByteStringObject,DecodedStreamObject,ContentStream)
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.pdf_styles import apply_pdf_style, decode_legacy_text, contrast_rgb
def legacy_pdf(path,text="注意事项 输入网络 Ω μ ± ×"):
writer=PdfWriter();page=writer.add_blank_page(width=640,height=220)
font=DictionaryObject({NameObject("/Type"):NameObject("/Font"),NameObject("/Subtype"):NameObject("/Type1"),NameObject("/BaseFont"):NameObject("/Courier-Bold"),NameObject("/Encoding"):NameObject("/WinAnsiEncoding")})
page[NameObject("/Resources")]=DictionaryObject({NameObject("/Font"):DictionaryObject({NameObject("/F1"):writer._add_object(font)})})
stream=ContentStream(None,writer)
stream.operations=[
([FloatObject(1),FloatObject(1),FloatObject(1)],b"rg"),
([NumberObject(0),NumberObject(0),NumberObject(640),NumberObject(220)],b"re"),([],b"f"),
([FloatObject(0),FloatObject(1),FloatObject(1)],b"RG"),
([NumberObject(20),NumberObject(25)],b"m"),([NumberObject(600),NumberObject(25)],b"l"),([],b"S"),
([FloatObject(1),FloatObject(1),FloatObject(0)],b"rg"),
([],b"BT"),([NameObject("/F1"),NumberObject(14)],b"Tf"),
([NumberObject(1),NumberObject(0),NumberObject(0),NumberObject(1),NumberObject(20),NumberObject(120)],b"Tm"),
([ByteStringObject(text.encode("gbk"))],b"Tj"),([],b"ET"),
]
page[NameObject("/Contents")]=writer._add_object(stream)
annotation=DictionaryObject({NameObject("/Type"):NameObject("/Annot"),NameObject("/Subtype"):NameObject("/Link"),NameObject("/Rect"):ArrayObject([NumberObject(10),NumberObject(10),NumberObject(30),NumberObject(20)]),NameObject("/A"):DictionaryObject({NameObject("/S"):NameObject("/URI"),NameObject("/URI"):TextStringObject("https://example.invalid")})})
page[NameObject("/Annots")]=ArrayObject([writer._add_object(annotation)])
writer.add_outline_item("Power",0)
with Path(path).open("wb") as out:writer.write(out)
def test_legacy_gbk_bytes_decode_without_guessing_ascii():
text="注意事项 Ω μ ± ×"
assert decode_legacy_text(text.encode("gbk"), legacy_gbk=True)==(text,True)
assert decode_legacy_text(b"R1 10K")==("R1 10K",False)
def test_palette_preserves_white_and_darkens_cyan_and_yellow():
assert contrast_rgb((1,1,1),text=True)==(1,1,1)
assert max(contrast_rgb((1,1,0),text=True))<.4
cyan=contrast_rgb((0,1,1),text=True)
assert max(cyan)<.5
tinted=contrast_rgb((0,1,0),text=False)
assert min(tinted)>.8
def test_original_mode_does_not_touch_bytes(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file);before=file.read_bytes()
report=apply_pdf_style(file,ExportOptions())
assert file.read_bytes()==before and not report.modified
def test_high_contrast_preserves_vectors_page_box_annotations_outline(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
before=PdfReader(file);box=list(before.pages[0].mediabox)
report=apply_pdf_style(file,ExportOptions(print_theme="high_contrast"))
after=PdfReader(file)
assert report.modified and report.color_ops>0
assert list(after.pages[0].mediabox)==box
assert after.outline[0].title=="Power"
assert after.pages[0]['/Annots'][0].get_object()['/A']['/URI']=="https://example.invalid"
operators=[op for _,op in ContentStream(after.pages[0].get_contents(),after).operations]
assert b"m" in operators and b"l" in operators and b"S" in operators
assert len(after.pages[0].get('/Resources',{}).get('/XObject',{}))==0
def test_arial_with_cjk_fallback_recovers_real_chinese(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
report=apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True))
reader=PdfReader(file,strict=True);text=reader.pages[0].extract_text()
assert "注意事项" in text and "输入网络" in text
assert "Ω" in text and "μ" in text and "±" in text and "×" in text
assert report.repaired_strings==1 and report.fallback_strings==1
assert reader.outline[0].title=="Power"
assert reader.pages[0]['/Annots'][0].get_object()['/A']['/URI']=="https://example.invalid"
def test_pre_cancel_never_modifies_pdf(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file);before=file.read_bytes()
cancel=threading.Event();cancel.set()
with pytest.raises(InterruptedError):
apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True),cancel)
assert file.read_bytes()==before
def test_normal_western_accent_is_not_guessed_as_chinese():
assert decode_legacy_text("école".encode("cp1252"))==("école",False)
def test_compound_text_requires_explicit_support_not_silent_success(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
r=PdfReader(file);w=PdfWriter();w.clone_document_from_reader(r)
page=w.pages[0];stream=ContentStream(page.get_contents(),w)
stream.operations=[([ArrayObject([operands[0]])],b'TJ') if op==b'Tj' else (operands,op) for operands,op in stream.operations]
page[NameObject('/Contents')]=w._add_object(stream)
with file.open('wb') as out:w.write(out)
before=file.read_bytes()
with pytest.raises(ValueError,match="TJ"):
apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True))
assert file.read_bytes()==before
def test_nonprinting_native_control_does_not_require_missing_font_glyph(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file,"A\r注意事项")
report=apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True))
assert "注意事项" in PdfReader(file).pages[0].extract_text()
assert report.repaired_strings==1
def test_high_contrast_sets_readable_minimum_stroke_without_moving_path(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
r=PdfReader(file);w=PdfWriter();w.clone_document_from_reader(r)
page=w.pages[0];stream=ContentStream(page.get_contents(),w)
stream.operations.insert(0,([FloatObject(.01)],b'w'))
page[NameObject('/Contents')]=w._add_object(stream)
with file.open('wb') as out:w.write(out)
apply_pdf_style(file,ExportOptions(print_theme="high_contrast"))
after=PdfReader(file);ops=ContentStream(after.pages[0].get_contents(),after).operations
widths=[float(a[0]) for a,o in ops if o==b'w']
assert widths and min(widths)>=.35
assert ([NumberObject(20),NumberObject(25)],b'm') in ops
assert ([NumberObject(600),NumberObject(25)],b'l') in ops
def rewrite_operations(file, transform):
reader=PdfReader(file); writer=PdfWriter(); writer.clone_document_from_reader(reader)
page=writer.pages[0]; stream=ContentStream(page.get_contents(),writer)
stream.operations=transform(stream.operations)
page[NameObject('/Contents')]=writer._add_object(stream)
with file.open('wb') as output: writer.write(output)
@pytest.mark.parametrize("raw,text",[(b"\xb1\xd7","±×"),(b"\xb5\xb1","µ±"),(b"\xc9\xc9","ÉÉ")])
def test_declared_winansi_never_guessed_as_gbk(raw,text):
assert decode_legacy_text(raw)==(text,False)
def test_gbk_repair_requires_explicit_font_mapping():
with pytest.raises(ValueError,match="字体"):
ExportOptions(legacy_gbk=True)
@pytest.mark.parametrize("color,operator",[([0],b'g'),([0,0,0,1],b'k')])
def test_high_contrast_tracks_gray_and_cmyk_text_after_white_fill(tmp_path,color,operator):
file=tmp_path/'native.pdf'; legacy_pdf(file,'LABEL')
rewrite_operations(file,lambda ops: [([NumberObject(v) for v in color],operator) if o==b'rg' and a==[1,1,0] else (a,o) for a,o in ops])
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file); ops=ContentStream(r.pages[0].get_contents(),r).operations
begin=next(i for i,(_,o) in enumerate(ops) if o==b'BT')
assert ops[begin+1][1]==b'rg'
assert max(float(v) for v in ops[begin+1][0])<.4
@pytest.mark.parametrize("operator",[b'Tc',b'Tw'])
def test_nonzero_text_spacing_fails_before_staging_replacement(tmp_path,operator):
file=tmp_path/'native.pdf'; legacy_pdf(file,'A A')
rewrite_operations(file,lambda ops: [(a,o) for a,o in ops] + [])
rewrite_operations(file,lambda ops: [(a,o) for a,o in ops[:1]]+[( [NumberObject(5)],operator)]+ops[1:])
before=file.read_bytes()
with pytest.raises(ValueError,match='间距'):
apply_pdf_style(file,ExportOptions(font_mapping='arial'))
assert file.read_bytes()==before
def test_tinted_palette_is_idempotent():
color=contrast_rgb((0,1,1),text=False)
assert contrast_rgb(color,text=False)==color
def test_font_mapping_keeps_declared_winansi_symbols(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'ASCII')
raw='±× µ±'.encode('cp1252')
rewrite_operations(file,lambda ops:[([ByteStringObject(raw)],o) if o==b'Tj' else (a,o) for a,o in ops])
report=apply_pdf_style(file,ExportOptions(font_mapping='arial'))
assert '±× µ±' in PdfReader(file).pages[0].extract_text()
assert report.repaired_strings==0
def test_unknown_original_font_advance_fails_safe(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
r=PdfReader(file);w=PdfWriter();w.clone_document_from_reader(r)
w.pages[0]['/Resources']['/Font']['/F1'].get_object()[NameObject('/BaseFont')]=NameObject('/UnknownNoMetrics')
with file.open('wb') as out:w.write(out)
before=file.read_bytes()
with pytest.raises(ValueError,match='字宽'):
apply_pdf_style(file,ExportOptions(font_mapping='arial'))
assert file.read_bytes()==before
def test_explicit_gbk_retains_standalone_declared_winansi_symbol():
assert decode_legacy_text(b"\xa3",legacy_gbk=True)==("£",False)
@pytest.mark.parametrize('width,height,panel',[(.2,12,False),(70,40,True)])
def test_high_contrast_distinguishes_stroke_glyph_fills_from_panels(tmp_path,width,height,panel):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
path_ops=[([NumberObject(0),NumberObject(1),NumberObject(1)],b'rg'),([NumberObject(30),NumberObject(40),FloatObject(width),FloatObject(height)],b're'),([],b'f')]
rewrite_operations(file,lambda ops:path_ops+ops)
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file);color=None
for args,op in ContentStream(r.pages[0].get_contents(),r).operations:
if op==b'rg':color=tuple(float(x) for x in args)
if op==b'f':break
assert (min(color)>.8) if panel else (max(color)<.5)
def test_scaled_rectangle_glyph_is_not_mistaken_for_large_panel(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
path_ops=[([FloatObject(.01),NumberObject(0),NumberObject(0),FloatObject(.01),NumberObject(0),NumberObject(0)],b'cm'),([NumberObject(0),NumberObject(1),NumberObject(1)],b'rg'),([NumberObject(30),NumberObject(40),NumberObject(70),NumberObject(400)],b're'),([],b'f')]
rewrite_operations(file,lambda ops:path_ops+ops)
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file);color=None
for args,op in ContentStream(r.pages[0].get_contents(),r).operations:
if op==b'rg':color=tuple(float(x) for x in args)
if op==b'f':break
assert max(color)<.5
def test_minimum_stroke_is_in_physical_points_after_scaled_transform(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
prefix=[([FloatObject(.01),NumberObject(0),NumberObject(0),FloatObject(.01),NumberObject(0),NumberObject(0)],b'cm'),([FloatObject(.1)],b'w')]
rewrite_operations(file,lambda ops:prefix+ops)
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file);width=None
for args,op in ContentStream(r.pages[0].get_contents(),r).operations:
if op==b'w':width=float(args[0])
if op==b'S':break
assert width*.01>=.35
@pytest.mark.parametrize("mapping", ["arial", "simsun", "msyh"])
def test_font_only_repair_preserves_reference_colors_widths_and_geometry(tmp_path, mapping):
file = tmp_path / "native.pdf"
legacy_pdf(file)
writer = PdfWriter(clone_from=file)
page = writer.pages[0]
stream = ContentStream(page.get_contents(), writer)
# Explicit hairline, a thicker emphasis stroke, and red/blue/teal/green
# reference colors must survive even when Chinese text is repaired.
additions = [([NumberObject(0)], b"w")]
for color in ((1,0,0), (0,0,1), (0,.5,.5), (0,.5,0), (0,0,.5), (.5,0,.5)):
additions += [([FloatObject(v) for v in color], b"RG"),
([NumberObject(20), NumberObject(50)], b"m"),
([NumberObject(600), NumberObject(50)], b"l"), ([], b"S")]
additions += [([FloatObject(1.2)], b"w")]
stream.operations = additions + stream.operations
page[NameObject("/Contents")] = writer._add_object(stream)
with file.open("wb") as out:
writer.write(out)
tracked = {b"rg", b"RG", b"g", b"G", b"k", b"K", b"w", b"cm", b"m", b"l", b"re", b"S", b"f", b"Tm"}
def graphics(reader):
return [(tuple(operands), op) for operands, op in ContentStream(reader.pages[0].get_contents(), reader).operations if op in tracked]
before = PdfReader(file)
expected = graphics(before)
box = list(before.pages[0].mediabox)
report = apply_pdf_style(file, ExportOptions(font_mapping=mapping, legacy_gbk=True, print_theme="original"))
after = PdfReader(file)
assert report.modified and report.repaired_strings == 1
assert report.color_ops == 0
assert graphics(after) == expected
assert list(after.pages[0].mediabox) == box
assert "注意事项" in after.pages[0].extract_text()
def test_stroke_search_text_is_not_reported_as_visible_font_repair(tmp_path):
file=tmp_path/'stroke.pdf';legacy_pdf(file,'注意事项')
writer=PdfWriter();writer.clone_document_from_reader(PdfReader(file))
font=writer.pages[0]['/Resources']['/Font']['/F1'].get_object()
font[NameObject('/BaseFont')]=NameObject('/fstroke0')
font[NameObject('/Widths')]=ArrayObject([NumberObject(600)]*256)
font[NameObject('/FirstChar')]=NumberObject(0)
with file.open('wb') as stream:writer.write(stream)
before=file.read_bytes()
with pytest.raises(ValueError,match='笔画'):
apply_pdf_style(file,ExportOptions(font_mapping='arial',legacy_gbk=True))
assert file.read_bytes()==before
def test_used_form_stroke_font_cannot_bypass_repair_validation(tmp_path):
file=tmp_path/'form-stroke.pdf';legacy_pdf(file,'注意事项')
writer=PdfWriter();writer.clone_document_from_reader(PdfReader(file));page=writer.pages[0]
font=page['/Resources']['/Font']['/F1'].get_object()
font[NameObject('/BaseFont')]=NameObject('/fstroke0')
font[NameObject('/Widths')]=ArrayObject([NumberObject(600)]*256)
font[NameObject('/FirstChar')]=NumberObject(0)
form=DecodedStreamObject();form.set_data(page.get_contents().get_data())
form.update({NameObject('/Type'):NameObject('/XObject'),NameObject('/Subtype'):NameObject('/Form'),NameObject('/BBox'):ArrayObject([NumberObject(0),NumberObject(0),NumberObject(640),NumberObject(220)]),NameObject('/Resources'):page['/Resources']})
page[NameObject('/Resources')]=DictionaryObject({NameObject('/XObject'):DictionaryObject({NameObject('/X1'):writer._add_object(form)})})
content=DecodedStreamObject();content.set_data(b'/X1 Do');page[NameObject('/Contents')]=writer._add_object(content)
with file.open('wb') as out:writer.write(out)
before=file.read_bytes()
with pytest.raises(ValueError,match='笔画'):
apply_pdf_style(file,ExportOptions(font_mapping='arial',legacy_gbk=True))
assert file.read_bytes()==before
@pytest.mark.parametrize('family,advance',[
('Helvetica',31.892),('Courier-Bold',33.6),
])
def test_standard14_fonts_use_exact_afm_advance_without_guessing(family,advance):
from mentor_pdf_export.pdf_styles import _old_width
font=DictionaryObject({NameObject('/BaseFont'):NameObject('/'+family),NameObject('/Subtype'):NameObject('/Type1'),NameObject('/Encoding'):NameObject('/WinAnsiEncoding')})
assert _old_width(font,b'Wi12',14)==pytest.approx(advance)
def test_unknown_font_without_metrics_is_still_rejected():
from mentor_pdf_export.pdf_styles import _old_width
assert _old_width(DictionaryObject({NameObject('/BaseFont'):NameObject('/UnknownNoMetrics')}),b'Wi12',14) is None
def test_hidden_ascii_strokes_survive_mixed_chinese_repair_without_overlay(tmp_path):
file=tmp_path/'mixed.pdf';legacy_pdf(file,'注意事项')
writer=PdfWriter();writer.clone_document_from_reader(PdfReader(file));page=writer.pages[0]
font=DictionaryObject({NameObject('/Type'):NameObject('/Font'),NameObject('/Subtype'):NameObject('/TrueType'),NameObject('/BaseFont'):NameObject('/fstroke5'),NameObject('/Encoding'):NameObject('/WinAnsiEncoding'),NameObject('/FirstChar'):NumberObject(0),NameObject('/Widths'):ArrayObject([NumberObject(600)]*256)})
page['/Resources']['/Font'][NameObject('/F2')]=writer._add_object(font)
stream=ContentStream(page.get_contents(),writer)
stream.operations.extend([
([],b'BT'),([NameObject('/F1'),NumberObject(14)],b'Tf'),([ByteStringObject(b'POWER')],b'Tj'),([],b'ET'),
([],b'BT'),([NumberObject(3)],b'Tr'),([NameObject('/F2'),NumberObject(14)],b'Tf'),([ByteStringObject(b'POWER')],b'Tj'),([],b'ET'),([NumberObject(0)],b'Tr'),
])
stream.get_data();page[NameObject('/Contents')]=writer._add_object(stream)
with file.open('wb') as out:writer.write(out)
before=PdfReader(file);old=[(a,op) for a,op in ContentStream(before.pages[0].get_contents(),before).operations if op in (b'm',b'l',b're',b'RG',b'rg',b'Tr')]
report=apply_pdf_style(file,ExportOptions(font_mapping='arial',legacy_gbk=True,print_theme='reference'))
result=PdfReader(file)
assert '注意事项' in result.pages[0].extract_text()
assert report.font_strings==2 and report.preserved_ascii_stroke_strings==1
ops=ContentStream(result.pages[0].get_contents(),result).operations
assert old==[(a,op) for a,op in ops if op in (b'm',b'l',b're',b'RG',b'rg',b'Tr')]
assert any(op==b'Tj' and (a[0].original_bytes if hasattr(a[0],'original_bytes') else bytes(a[0]))==b'POWER' for a,op in ops)