Код: Выделить всё
import re
from unicodedata import normalize
from docx import Document
from wand.image import Image
from wand.drawing import Drawing
from wand.font import Font
doc = Document("P.docx")
docText = []
for para in doc.paragraphs:
docText.append(para.text)
fullText = "\n".join(docText)
ct = 242
def get(source, begin, end):
try:
start = source.index(len(begin)) + len(begin)
finish = source.index(len(end), len(start))
return source[start:finish]
except ValueError:
return ""
def capitalize(string):
cap = ("".join(j[0].upper() + j[1:]) for j in string)
return cap
def find_matches(text):
return capitalize(
[
m
for m in re.findall(
r"^[^0-9]\s+([^.;]+\s*)+[.;]+", normalize("NFKD", text), re.MULTILINE
)
]
)
with Image(width=400, height=1000, pseudo='xc:white') as canvas:
left, top, width, height = 2, 2, 395, 131
for match in find_matches(text=fullText):
ct += 1
with Drawing() as context:
context.fill_color = 'black'
context.rectangle(left=left, top=top, width=width, height=height)
context.fill_color = 'white'
context.rectangle(left=(left+2), top=(top+2), width=(width-4), height=(height-4))
canvas.font = Font('/System/Library/Fonts/timesnewroman.ttf')
context(canvas)
canvas.caption(match + '\n' + str(ct), left=(left+5), top=top, width=(width-10), height=height,
gravity='center')
top += 135
canvas.crop(bottom=top)
canvas.save(filename='patdrawTest.png')
[img]https:// i.sstatic.net/VCjRs.png[/img]
Проблема, очевидно, заключается в отсутствии единообразия, когда дело касается размера шрифта. Вот как должен выглядеть мой вывод (игнорируя текст внутри полей):
[img]https://i.sstatic.net /naQy1.png[/img]
Единственное, что меня беспокоит, это убедиться, что весь текст имеет одинаковый размер шрифта (размер 12 отлично подходит) с этими рамками изменение размера текста. Спасибо за любую помощь!
РЕДАКТИРОВАТЬ
Из предоставленного ответа вот мой текущий код:
Код: Выделить всё
import re
from unicodedata import normalize
from docx import Document
from wand.image import Image
from wand.drawing import Drawing
doc = Document("P.docx")
docText = []
for para in doc.paragraphs:
docText.append(para.text)
fullText = "\n".join(docText)
ct = 242
def get(source, begin, end):
try:
start = source.index(len(begin)) + len(begin)
finish = source.index(len(end), len(start))
return source[start:finish]
except ValueError:
return ""
def capitalize(string):
cap = ("".join(j[0].upper() + j[1:]) for j in string)
return cap
def find_matches(text):
return capitalize(
[
m
for m in re.findall(
r"^[^0-9]\s+([^.;]+\s*)+[.;]+", normalize("NFKD", text), re.MULTILINE
)
]
)
def to_chunks(words, size):
for idx in range(0, len(words), size):
yield words[idx:idx + size]
def rebuild_text(words, size):
return "\n".join([" ".join(w) for w in to_chunks(words, size)])
target_width = 396
target_height = 0
y_offset = 0
y_padding = 10
x_padding = 5
with Image(width=1000, height=1000, pseudo='xc:white') as img:
for match in find_matches(text=fullText):
ct += 1
with Drawing() as ctx:
ctx.font_size = 16
ctx.text_alignment = 'center'
words = match.split(" ")
words.append("\n" + str(ct))
word_count = len(words)
while True:
temp_text = rebuild_text(words, word_count)
metrics = ctx.get_font_metrics(img, temp_text, multiline=True)
if metrics.text_width > target_width:
word_count -= 1
else:
text = temp_text
target_height = int(metrics.text_height + 0.5)
break
ctx.push()
ctx.fill_color = 'white'
ctx.stroke_width = 4
ctx.stroke_color = 'black'
ctx.rectangle(0, y_offset + y_padding, width=2*x_padding+target_width,
height=2*y_padding+target_height)
ctx.pop()
ctx.text(x_padding + (target_width // 2), 4*y_padding+y_offset, text)
ctx(img)
y_offset = target_height + 4*y_padding
img.trim()
img.save(filename='patdrawdemoTest.png')
[img]https://i.sstatic .net/bA9UC.png[/img]
Я не совсем понимаю, как исправить странный интервал. Первый и третий блоки кажутся отличными, однако между первым и вторым блоком есть странное белое пространство, границы по бокам неровные, а также есть еще два блока, которые должны быть там, как показано на рисунке. оригинальный пост. Любая помощь будет принята с благодарностью!
Подробнее здесь: https://stackoverflow.com/questions/680 ... ize-in-pyt