Я хочу, чтобы верхний трубопровод был ближе к изображению, когда фотография размещена в верхней части страницы. Трубопровод появляется на предыдущей странице, но находится на той же высоте, что и другой нижний трубопровод. < /P>
У меня есть ошибки в коде. Я не знаю, что делать.def procesar_imagenes_html(doc):
script_dir = os.path.dirname(os.path.abspath(__file__))
attachments_dir = os.path.join(script_dir, ".attachments")
if not os.path.isdir(attachments_dir):
os.makedirs(attachments_dir)
print(f"{attachments_dir}")
else:
print(f"Directory .attachments found: {attachments_dir}")
img_pattern = re.compile(r'\(a href="[^"]+"\)\(img src="([^"]+)"[^>]*\/\)\(\/a\)')
paragraphs = list(doc.Paragraphs)
for paragraph in paragraphs:
match = img_pattern.search(paragraph.Range.Text)
if match:
img_url = match.group(1)
print(f"{img_url}")
try:
response = requests.get(img_url)
if response.status_code == 200:
img_name = unquote(os.path.basename(img_url))
img_name = img_name.replace(' ', '_')
img_path = os.path.join(attachments_dir, img_name)
with open(img_path, 'wb') as img_file:
img_file.write(response.content)
print(f"{img_path}")
match_range = paragraph.Range.Duplicate
match_range.Start = paragraph.Range.Start + match.start()
match_range.End = paragraph.Range.Start + match.end()
match_range.Delete()
paragraph.Range.InsertParagraphBefore()
table = doc.Tables.Add(paragraph.Range, 3, 1)
table.Borders.Enable = False # No borders
cell_sup = table.Cell(1, 1)
cell_sup.Range.Text = "|"
cell_sup.Range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphLeft
cell_sup.Range.ParagraphFormat.SpaceBefore = 0
cell_sup.Range.ParagraphFormat.SpaceAfter = 0
cell_img = table.Cell(2, 1)
image = cell_img.Range.InlineShapes.AddPicture(
FileName=img_path,
LinkToFile=False,
SaveWithDocument=True
)
if image.Height > max_height:
image.Height = max_height
cell_img.Range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter
cell_inf = table.Cell(3, 1)
cell_inf.Range.Text = "|"
cell_inf.Range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphLeft
cell_inf.Range.ParagraphFormat.SpaceBefore = 0
cell_inf.Range.ParagraphFormat.SpaceAfter = 0
table.Columns.AutoFit()
print(f"Image inserted: {img_name}")
else:
print(f"Error downloading image: {img_url}")
except Exception as e:
print(f"Error processing image {img_url}: {e}")
procesar_imagenes_html(doc)
< /code>
Описание: < /p>
Я работаю над сценарием Python, который обрабатывает документ Word (.docx) и заменяет определенные текстовые шаблоны на изображения, загруженные с URL. Проблема в том, что когда я вставляю изображение в начале документа, трубопровод (табличная ячейка с символом «|»), расположенная в верхнем левом углу изображения, появляется на предыдущей странице и имеет другой размер.import os
import re
import requests
from urllib.parse import unquote
import win32com.client as win32
def procesar_imagenes_html(doc):
script_dir = os.path.dirname(os.path.abspath(__file__))
attachments_dir = os.path.join(script_dir, ".attachments")
if not os.path.isdir(attachments_dir):
os.makedirs(attachments_dir)
print(f"Directory created: {attachments_dir}")
else:
print(f"Directory .attachments found: {attachments_dir}")
img_pattern = re.compile(r'\(a href="[^"]+"\)\(img src="([^"]+)"[^>]*\/\)\(\/a\)')
paragraphs = list(doc.Paragraphs)
for paragraph in paragraphs:
match = img_pattern.search(paragraph.Range.Text)
if match:
img_url = match.group(1)
print(f"Image URL: {img_url}")
try:
response = requests.get(img_url)
if response.status_code == 200:
img_name = unquote(os.path.basename(img_url))
img_name = img_name.replace(' ', '_')
img_path = os.path.join(attachments_dir, img_name)
with open(img_path, 'wb') as img_file:
img_file.write(response.content)
print(f"Image saved to: {img_path}")
# Delete the matched text
match_range = paragraph.Range.Duplicate
match_range.Start = paragraph.Range.Start + match.start()
match_range.End = paragraph.Range.Start + match.end()
match_range.Delete()
# Insert a new table with the image
paragraph.Range.InsertParagraphBefore()
table = doc.Tables.Add(paragraph.Range, 3, 1)
table.Borders.Enable = False # No borders
# Configure the table cells
cell_sup = table.Cell(1, 1)
cell_sup.Range.Text = "|"
cell_sup.Range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphLeft
cell_sup.Range.ParagraphFormat.SpaceBefore = 0
cell_sup.Range.ParagraphFormat.SpaceAfter = 0
cell_img = table.Cell(2, 1)
image = cell_img.Range.InlineShapes.AddPicture(
FileName=img_path,
LinkToFile=False,
SaveWithDocument=True
)
max_height = 200 # Adjust this value as needed
if image.Height > max_height:
image.Height = max_height
cell_img.Range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter
cell_inf = table.Cell(3, 1)
cell_inf.Range.Text = "|"
cell_inf.Range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphLeft
cell_inf.Range.ParagraphFormat.SpaceBefore = 0
cell_inf.Range.ParagraphFormat.SpaceAfter = 0
table.Columns.AutoFit()
print(f"Image inserted: {img_name}")
else:
print(f"Error downloading image: {img_url}")
except Exception as e:
print(f"Error processing image {img_url}: {e}")
# Example usage
# doc = win32.Dispatch("Word.Application").Documents.Open("path/to/document.docx")
# procesar_imagenes_html(doc)
< /code>
Проблема: < /p>
Когда я вставляю изображение в начале документа, я хочу, чтобы только верхний трубопровод (тот, над изображением в верхнем левом углу), имел тот же размер, что и нижний трубопровод. В настоящее время верхний трубопровод появляется на предыдущей странице и имеет другой размер. ограничения. Вы можете создать свой собственный шаблон Word для проверки кода. Я ожидал, что верхний трубопровод появится на той же странице, что и изображение, и будет такой же размер, что и нижний трубопровод. Тем не менее, верхний трубопровод все еще появляется на предыдущей странице и имеет другой размер.
Подробнее здесь: https://stackoverflow.com/questions/795 ... g-win32com
Проблема с позиционированием изображений и трубопроводов в документах Word с использованием Win32com ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение