您的位置:首页 > 编程语言 > Python开发

【python】用python生成pdf文件

2017-04-21 17:27 274 查看
转自:https://www.davidfischer.name/2015/08/generating-pdfs-with-and-without-python/

from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter
import io

def write_pdf_file(path, sentlist):
buf = io.BytesIO()

# Setup the document with paper size and margins
doc = SimpleDocTemplate(
buf,
rightMargin=inch / 2,
leftMargin=inch / 2,
topMargin=inch / 2,
bottomMargin=inch / 2,
pagesize=letter,
)

# Styling paragraphs
styles = getSampleStyleSheet()
# Write things on the document
paragraphs = []
for sent in sentlist:
if sent.strip() == '':
sent = '_'
paragraphs.append(Paragraph(sent, styles['Normal']))
doc.build(paragraphs)
# Write the PDF to a file
with open(path, 'w') as fd:
fd.write(buf.getvalue())

if __name__ == '__main__':
text=['a','b','c']
path='test.pdf'
write_pdf_file(path,text)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: