3

我正在尝试通过打开 PDF、添加文本框并保存来向 pdf 添加文本。当我运行代码时,什么也没有发生。在桌面上,它显示文件已更新,但没有显示任何文本。

这是代码:

import fitz 
doc = fitz.open("/Users/khaylablack/Desktop/participant_certificate.pdf")           
page = doc[0]                         # choose some page
rect = fitz.Rect(50, 100, 200, 200)   # rectangle (left, top, right, bottom) in pixels

text = "absolutely not"

rc = page.insertTextbox(rect, text, fontsize = 48, # choose fontsize (float)
                   fontname = "Times-Roman",       # a PDF standard font
                   fontfile = None,                # could be a file on your system
                   align = 1)                      # 0 = left, 1 = center, 2 = right

#doc.saveIncr()   # update file. Save to new instead by doc.save("new.pdf",...)
doc.save("/Users/khaylablack/Desktop/watermarked_participant_cert.pdf")
4

2 回答 2

4

使用 insertTextbox() 方法时,您必须确保您创建的 rect 可以包含文本,因为如果没有,您最终将不会显示任何文本。一种方法是检查您的实现的文本长度,如下所示:

text = "absolutely not"
text_lenght = fitz.getTextlength(text, fontname="Times-Roman", fontsize=48))

text_length 将为 270.67。

但是你拥有的矩形宽度只有 150 (200-50)。此外,即使改变矩形的宽度也不起作用,因为它仍然太短,所以你还需要增加它的高度。您可以做的另一件事就是更改您正在使用的字体大小。这两个替代方案将如下所示:

  • 备选方案 1,更大的矩形:
fontsize_to_use = 48

text = "absolutely not"
fontname_to_use = "Times-Roman"

text_lenght = fitz.getTextlength(text, 
                                 fontname=fontname_to_use, 
                                 fontsize=fontsize_to_use)

rect_x1 = 50
rect_y1 = 100
rect_x2 = rect_x1 + text_lenght + 2  # needs margin
rect_y2 = rect_y1 + fontsize_to_use + 2  # needs margin


rect = (rect_x1, rect_y1, rect_x2, rect_y2)

## Uncomment if you wish to display rect
# page.drawRect(rect,color=(.25,1,0.25)) 

rc = page.insertTextbox(rect, text,
                        fontsize=fontsize_to_use,
                        fontname=fontname_to_use,
                        align=1)

备选方案 2,较小的字体大小:

text = "absolutely not"
fontname_to_use = "Times-Roman"

rect_x1 = 50
rect_y1 = 100
rect_x2 = 200
rect_y2 = 200

rect_width = rect_x2 - rect_x1
rect_height = rect_y2 - rect_y1

rect = (rect_x1, rect_y1, rect_x2, rect_y2)

fontsize_to_use = rect_width/len(text)*2  # *2 just because 1pt is too small for a char. It mantains a good ratio for rect's width with larger text, but behaviour is not assured.

## Uncomment if you wish to display rect
# page.drawRect(rect,color=(.25,1,0.25))

rc = page.insertTextbox(rect, text,
                        fontsize=fontsize_to_use,
                        fontname=fontname_to_use,
                        align=1)

注意:rc是未使用的矩形高度,它也可以是负数,在你的情况下它是-5.59,这意味着文本超过了矩形的高度。

于 2020-11-11T16:58:37.867 回答
-2

你是否同时安装了 pymupdf 和 fitz?如果没有尝试在命令提示符下运行这些。

pip install pymupdf
pip install fitz

于 2020-08-16T06:20:48.267 回答