转自:https://www.davidfischer.name/2015/08/generating-pdfs-with-and-without-python/
1 from reportlab.platypus import SimpleDocTemplate, Paragraph 2 from reportlab.lib.styles import getSampleStyleSheet 3 from reportlab.lib.units import inch 4 from reportlab.lib.pagesizes import letter 5 import io 6 7 def write_pdf_file(path, sentlist): 8 buf = io.BytesIO() 9 10 # Setup the document with paper size and margins 11 doc = SimpleDocTemplate( 12 buf, 13 rightMargin=inch / 2, 14 leftMargin=inch / 2, 15 topMargin=inch / 2, 16 bottomMargin=inch / 2, 17 pagesize=letter, 18 ) 19 20 # Styling paragraphs 21 styles = getSampleStyleSheet() 22 # Write things on the document 23 paragraphs = [] 24 for sent in sentlist: 25 if sent.strip() == '': 26 sent = '_' 27 paragraphs.append(Paragraph(sent, styles['Normal'])) 28 doc.build(paragraphs) 29 # Write the PDF to a file 30 with open(path, 'w') as fd: 31 fd.write(buf.getvalue()) 32 33 if __name__ == '__main__': 34 text=['a','b','c'] 35 path='test.pdf' 36 write_pdf_file(path,text)