Python 3.x 如何将文本写入pdf文件
我正在使用Python3,我有一个很长的文本文件,我想创建一个新的pdf,并在其中写入文本 我尝试使用reportlab,但它只写一行Python 3.x 如何将文本写入pdf文件,python-3.x,pdf,Python 3.x,Pdf,我正在使用Python3,我有一个很长的文本文件,我想创建一个新的pdf,并在其中写入文本 我尝试使用reportlab,但它只写一行 from reportlab.pdfgen pdfgen import canvas c = canvas.Canvas("hello.pdf") c.drawString(100,750, text) c.save() 我知道我可以告诉它在哪一行写什么。但有没有一个图书馆,我可以只给文本和页边空白,它会写在pdf文件 谢谢 编辑: 或者,我还可以使用一个库
from reportlab.pdfgen pdfgen import canvas
c = canvas.Canvas("hello.pdf")
c.drawString(100,750, text)
c.save()
我知道我可以告诉它在哪一行写什么。但有没有一个图书馆,我可以只给文本和页边空白,它会写在pdf文件
谢谢
编辑:
或者,我还可以使用一个库来轻松地将txt文件转换为pdf文件?在画布上简单地绘制字符串是不行的。
如果它只是原始文本,您不需要对文本进行任何修改,如标题和其他类型的内容,那么您可以简单地将文本放入
可流动内容中,即段落,您的可流动内容可以附加到您的故事[]
您可以根据自己的用途调整边距
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter
styles = getSampleStyleSheet()
styleN = styles['Normal']
styleH = styles['Heading1']
story = []
pdf_name = 'your_pdf_file.pdf'
doc = SimpleDocTemplate(
pdf_name,
pagesize=letter,
bottomMargin=.4 * inch,
topMargin=.6 * inch,
rightMargin=.8 * inch,
leftMargin=.8 * inch)
with open("your_text_file.txt", "r") as txt_file:
text_content = txt_file.read()
P = Paragraph(text_content, styleN)
story.append(P)
doc.build(
story,
)
有关流动性的更多信息,请阅读