-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtxt2pdf.py
executable file
·88 lines (72 loc) · 2.24 KB
/
txt2pdf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# -*- coding: utf-8 -*-
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm
PAGE_SIZE = A4
LEFT = 2*cm
RIGHT = 2*cm
TOP = 2*cm
BOTTOM = 2*cm
AUTHOR = None
TITLE = None
FONT_SIZE = 10
LEADING = None
KERNING = 0
FONT = 'Courier'
def readfile(infile, nChars):
with open(infile, 'r') as f:
nbr = 0
for l0 in f:
l = l0.decode("utf-8")
nbr += 1
l = l[:-1] # remove trailing newspace \n character
if len(l) > nChars:
while len(l) > nChars:
yield l[:nChars]
l = l[nChars:]
yield l
def newpage(c, font, fontsize, top, mleft, leading0, kerning):
textobject = c.beginText()
textobject.setFont(font, fontsize, leading=leading0)
textobject.setTextOrigin(mleft, top)
textobject.setCharSpace( kerning )
return textobject
def pdf_create(c, data, outfile, font, fontsize, top, mleft, lpp, leading, kerning):
p,l = 1, 0
t = newpage(c, font, fontsize, top, mleft, leading, kerning)
for line in data:
t.textLine(line)
l += 1
if l == lpp:
c.drawText(t)
c.drawRightString(10*cm, 1*cm, str(p))
c.showPage()
l = 0
p += 1
t = newpage(c, font, fontsize, top, mleft, leading, kerning)
if l > 0:
c.drawText(t)
c.drawRightString(10*cm, 1*cm, str(p))
else:
p -= 1
c.save()
def get_outfile(infile):
if '.' in infile:
return infile[:infile.rfind('.')] + '.pdf'
return infile + '.pdf'
def convert(infile):
outfile = get_outfile(infile)
c = canvas.Canvas(outfile, pagesize=PAGE_SIZE)
if AUTHOR:
c.setAuthor(AUTHOR)
if TITLE:
c.setTitle(TITLE)
width = PAGE_SIZE[0] - LEFT - RIGHT
w = c.stringWidth(".", fontName=FONT, fontSize=FONT_SIZE)
nChars = int((width + KERNING) / (w + KERNING))
top = PAGE_SIZE[1] - TOP - FONT_SIZE
leading = LEADING or 1.2*FONT_SIZE
nLines = int((leading + PAGE_SIZE[1] - TOP - BOTTOM - FONT_SIZE) / (leading))
data = readfile(infile, nChars)
pdf_create(c, data, outfile, FONT, FONT_SIZE, top, LEFT, nLines, leading, KERNING)
return outfile