为什么 PyPDF2 和 reportlab 在插入文本时删除空格?

Why is PyPDF2 and reportlab removing spaces when inserting text?

我正在尝试将格式化文本插入到我的 PDF 的最后一页。我正在使用 PyPDF2 和 reportlab 库来执行此操作。我正在使用 Python 2.7.

出于某种原因,插入的文本没有空格,并且每个字符都换行(不是每个 CRLF)。我哪里做错了或者有更好的方法吗?

谢谢。

PYTHON 代码:

# Libs
from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger;
from reportlab.pdfgen import canvas; # PDF Editor 1
from reportlab.lib.pagesizes import letter; # PDF Editor 2
from reportlab.lib.units import inch; # PDF Editor 3

uniOCRText = 'This is a test string.';

# Create a new PDF with Reportlab
packet = io.BytesIO();
can = canvas.Canvas(packet, pagesize=letter);

textobject = can.beginText();
textobject.setTextOrigin(inch, 2.5*inch);
textobject.setFont("Times-Roman", 10);
i = 0;
for line in uniOCRText:
    i = i + 1;
    print("i = " + str(i) + " - line = " + str(line));
    textobject.textLine(line); # Error here deletes spaces!!!
textobject.setFillGray(0.4);
can.drawText(textobject);
can.save();

# Move to the beginning of the StringIO buffer
packet.seek(0);
new_pdf = PdfFileReader(packet);

# Add watermark
output = PdfFileWriter();

page = new_pdf.getPage(0);
output.addPage(page);

tempFolder = "Temp/TempPDF.pdf";
outputStream = open(tempFolder, "wb");
output.write(outputStream);
outputStream.close();

# Create a Merger PDF
merger = PdfFileMerger();
merger.append(PdfFileReader(open(pdfFileFromLoc, 'rb')));
merger.append(PdfFileReader(open(tempFolder, 'rb')));
merger.write(pdfFileDestLoc);
>>> for line in 'hello':
...     print(line)
... 
h
e
l
l
o

您正在迭代字符。调用变量 line 不会使解释器遍历行。您必须 splitlines() 并迭代结果列表:

>>> for line in 'hello\nbye'.splitlines():
...     print(line)
... 
hello
bye