@Don_Sudak

Как корректно добавить текст в PDF файл?

Пытаюсь написать скрипт для изменения текста в pdf файлах
Нашёл несколько примеров в интернете, но они либо путают расположение элементов(по слоям?)
Первый код переносит все элементы кроме текста корректно. Текст он помещает под них и текста не видно

from PyPDF2 import PdfFileWriter, PdfFileReader
from io import BytesIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4

buffer = BytesIO()

# create a new PDF with Reportlab
p = canvas.Canvas(buffer, pagesize=A4)
p.drawString(100, 100, "holaaaaaaaaaaaa")
p.showPage()
p.save()

#move to the beginning of the StringIO buffer
buffer.seek(0)
newPdf = PdfFileReader(buffer)

#######DEBUG NEW PDF created#############
pdf1 = buffer.getvalue()
open('pdf1.pdf', 'wb').write(pdf1)
#########################################
# read your existing PDF
existingPdf = PdfFileReader(open('{путь до файла}', 'rb'))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existingPdf.getPage(0)
page.mergePage(newPdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = open('output.pdf', 'wb')
output.write(outputStream)
outputStream.close()


Второй пример при переносе путает и текст и элементы (но только если текст присутствует в файле. Если текста нет то блиоки переносятся корректно). При добавлении текста отдельно он снова уходит на нижний слой и его не видно.

doc = fitz.open("{путь до файла}")
page = doc[0]
paths = page.get_drawings()  # extract existing drawings
# this is a list of "paths", which can directly be drawn again using Shape
# -------------------------------------------------------------------------
#
# define some output page with the same dimensions
outpdf = fitz.open()
outpage = outpdf.new_page(width=page.rect.width, height=page.rect.height)
shape = outpage.new_shape()  # make a drawing canvas for the output page
# --------------------------------------
# loop through the paths and draw them
# --------------------------------------

for path in paths:
    # ------------------------------------
    # draw each entry of the 'items' list
    # ------------------------------------
    for item in path["items"]:  # these are the draw commands
        if item[0] == "l":  # line
            shape.draw_line(item[1], item[2])
        elif item[0] == "re":  # rectangle
            shape.draw_rect(item[1])
        elif item[0] == "qu":  # quad
            shape.draw_quad(item[1])
        elif item[0] == "c":  # curve
            shape.draw_bezier(item[1], item[2], item[3], item[4])
        else:
            raise ValueError("unhandled drawing", item)
    # ------------------------------------------------------
    # all items are drawn, now apply the common properties
    # to finish the path
    # ------------------------------------------------------
    shape.finish(
        fill=path["fill"],  # fill color
        color=path["color"],  # line color
        dashes=path["dashes"],  # line dashing
        even_odd=path.get("even_odd", True),  # control color of overlaps
        closePath=path["closePath"],  # whether to connect last and first point
        lineJoin=path["lineJoin"],  # how line joins should look like
        lineCap=max(path["lineCap"]),  # how line ends should look like
        width=path["width"],  # line width
        stroke_opacity=path.get("stroke_opacity", 1),  # same value for both
        fill_opacity=path.get("fill_opacity", 1),  # opacity parameters
        )
# all paths processed - commit the shape to its page

shape.commit()
outpdf.save("drawings-page-0.pdf")


При попытке просто добавить текст к шейпу или странице(в существующем pdf файле) он помещается за элемнтами и его снова не виндо
Подскажите пожалуйста как закинуть текст в нужное место страницы pdf файла поверх других элементов
  • Вопрос задан
  • 423 просмотра
Решения вопроса 1
@Don_Sudak Автор вопроса
Благодаря Adamos нашёл свою ошибку
Текст просто сливался с фоном
В моём случае достаточно просто
shape.insert_textbox(
    rect,
    text,
    fontname = "helv",
    fontsize = 25,
    rotate = 0,
    color = (1 ,1, 1),
)
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы