Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Highlight text with Reportlab

38 views
Skip to first unread message

Beetle Cad

unread,
Aug 6, 2024, 4:38:58 AM8/6/24
to reportlab-users
Hi to all,
I am programming a project that make several PDFs with Python + Reportlab.

Before the program, I worked manually creating word files, where I highlighted the keywords that I found only in certain positions and not all the keywords in the text.

I can create PDFs with the text but on Reportlab there is no way to highlight the text that I print and that respects certain conditions.

I would like to understand if anyone has solved this problem or has any ideas.

Many thanks

Vyacheslav Vyacheslav

unread,
Mar 3, 2025, 2:04:53 PMMar 3
to reportlab-users
from faker import Faker
from reportlab.lib.enums import TA_LEFT

from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import (
SimpleDocTemplate,
Paragraph,
)
from reportlab.lib.pagesizes import A4


def create_pdf(
output_file: str,
text: str,
pagesize: tuple[float, float] = A4,
) -> None:
"""
Генерирует PDF-документ с заголовком и текстом
:param output_file: имя выходного PDF-файла
:param text: текст
:param pagesize: размер документа
:return: None
"""

# Создаём упрощённый шаблон документа с отступами
doc = SimpleDocTemplate(
filename=output_file,
pagesize=pagesize,
leftMargin=20, # Отступ слева
rightMargin=20, # Отступ справа
topMargin=20, # Отступ сверху
bottomMargin=20, # Отступ снизу
)

# Создаём стиль для параграфа с текстом (подчёркивание и частичное выделение)
body_style_3 = ParagraphStyle(
name="BodyStyle3",
fontSize=13,
alignment=TA_LEFT,
)

# Разбиваем текст на части для выделения
words = text.split() # Разделяем текст на слова
highlighted_part = " ".join(words[2:5]) # Выделяем слова с 3-го по 5-е
before_part = " ".join(words[:2])
after_part = " ".join(words[5:])
highlighted_text = f"{before_part} <font backcolor='yellow'>{highlighted_part}</font> {after_part}"

# Создаём объекты параграфов
body_text_3 = Paragraph(text=f'{highlighted_text}', style=body_style_3)

# Добавляем созданные элементы
elements = [
body_text_3,
]

doc.build(flowables=elements)
print(f"PDF сохранён в {output_file}")


if __name__ == "__main__":
fake = Faker()
create_pdf(
output_file='highlighted_text.pdf',
text=fake.paragraph(nb_sentences=15),
)

Может быть эта идея поможет тебе
вторник, 6 августа 2024 г. в 11:38:58 UTC+3, beet...@gmail.com:
Reply all
Reply to author
Forward
0 new messages