Created
March 13, 2018 10:43
-
-
Save quietcricket/6e4a61fcf1a8b38b6ea74c80a5f37854 to your computer and use it in GitHub Desktop.
Generate PDF from plain text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from reportlab.lib.pagesizes import * | |
from reportlab.lib.styles import getSampleStyleSheet | |
from reportlab.lib.units import inch | |
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, PageBreak | |
from reportlab.lib.enums import * | |
from reportlab.pdfbase import pdfmetrics | |
from reportlab.pdfbase.ttfonts import TTFont | |
if len(sys.argv) < 3: | |
print "Usage: <script> textfile pdffile" | |
sys.exit() | |
else: | |
w,h=B5 | |
pdf = SimpleDocTemplate(sys.argv[2], pagesize = (w-50,h)) | |
story = [] | |
styles = getSampleStyleSheet() | |
style = styles['Normal'] | |
font_path = r"/Library/Fonts/Athelas.ttc" | |
pdfmetrics.registerFont(TTFont("Athelas", font_path)) | |
style.fontName="Athelas" | |
style.firstLineIndent=20 | |
style.alignment=TA_JUSTIFY | |
text = file(sys.argv[1]).read() | |
paragraphs = text.split("\n") | |
firstline=True | |
for para in paragraphs: | |
if para[:7]=="Chapter": | |
if not firstline: | |
story.append(PageBreak()) | |
else: | |
firstline=False | |
style.alignment=TA_CENTER | |
style.fontSize=20 | |
else: | |
style.alignment=TA_JUSTIFY | |
style.fontSize=10 | |
story.append(Paragraph(para, style)) | |
if style.fontSize==20: | |
story.append(Spacer(0, inch * style.fontSize/50.0)) | |
pdf.build(story) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment