我正在尝试将文本文件(.txt)转换为加密的PDF文件,但出现错误:
TypeError: a bytes-like object is required, not 'str'
文本文件(.txt)内是中文文本,我使用的代码如下:
import PyPDF2
from fpdf import FPDF
with open('Chinese.txt') as f:
QQ = f.read()
QQ = QQ.encode('utf-8')
pdf = FPDF()
pdf.add_page()
pdf.set_xy(0, 0)
pdf.set_font('arial', 'B', 13.0)
pdf.cell(40,10,QQ)
pdf.output('Before.pdf', 'F')
pdffile = open(r"Before.pdf", "rb")
pdfReader = PyPDF2.PdfFileReader(pdffile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfWriter.encrypt('123')
resultPDF = open(r"After.pdf", "wb")
pdfWriter.write(resultPDF)
resultPDF.close()
pdffile.close()
答案 0 :(得分:0)
在您的代码中,您不需要对utf-8进行编码,因为FPDF可以为您编码。请应用以下更改。它对我有用。
with open(b'hello.txt','r') as f:
QQ = f.read()
#QQ = QQ.encode('utf-8')
pdf = FPDF()
pdf.add_page()
pdf.set_xy(0, 0)
pdf.set_font('arial', 'B', 13.0)
pdf.cell(40,10,QQ)
pdf.output('Before.pdf', 'F')
pdffile = open(r"Before.pdf", "rb")
pdfReader = PyPDF2.PdfFileReader(pdffile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfWriter.encrypt('123')
resultPDF = open(r"After.pdf", "wb")
pdfWriter.write(resultPDF)
resultPDF.close()
pdffile.close()
答案 1 :(得分:0)
最后我找到了答案 我的Chinese.txt文件中有中文字体,这就是为什么无法成功转换为PDF的原因, 因此需要下载fireflysung.ttf以支持PDF中文显示。
import PyPDF2
from fpdf import FPDF
with open'Chinese.txt') as f:
QQ = f.read()
pdf = FPDF()
pdf.add_page()
pdf.add_font('fireflysung', '', 'fireflysung.ttf', uni=True)
pdf.set_font('fireflysung', '', 12)
pdf.set_xy(0, 0)
pdf.multi_cell(0,5,QQ)
pdf.output('Before.pdf', 'F')
with open("Before.pdf", "rb") as pdffile:
pdfReader = PyPDF2.PdfFileReader(pdffile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfWriter.encrypt(a)
with open("After.pdf", "wb") as resultPDF:
pdfWriter.write(resultPDF)