This recipe shows how to convert all text files matching a filename wildcard to PDF, using the xtopdf PDF creation toolkit. For example, if you specify report.txt as the wildcard, all files in the current directory that match report.txt, will be converted to PDF, each in a separate PDF file. The original text files are not changed.
Here is a guide to installing and using xtopdf:
http://jugad2.blogspot.in/2012/07/guide-to-installing-and-using-xtopdf.html
More details on running the program, and sample output, are available here:
http://jugad2.blogspot.in/2016/12/xtopdf-wildcard-text-files-to-pdf-with.html
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 | from __future__ import print_function
# WildcardTextToPDF.py
# Convert the text files specified by a filename wildcard,
# like '*.txt' or 'foo*bar*baz.txt', to PDF files.
# Each text file's content goes to a separate PDF file, with the
# PDF file name being the full text file name (including the
# '.txt' part), with '.pdf' appended.
# Requires:
# - xtopdf: https://bitbucket.org/vasudevram/xtopdf
# - ReportLab: https://www.reportlab.com/ftp/reportlab-1.21.1.tar.gz
# Author: Vasudev Ram
# Copyright 2016 Vasudev Ram
# Product store: https://gumroad.com/vasudevram
# Web site: https://vasudevram.github.io
# Blog: http://jugad2.blogspot.com
import sys
import glob
from PDFWriter import PDFWriter
def usage(argv):
sys.stderr.write("Usage: python {} txt_filename_pattern\n".format(argv[0]))
sys.stderr.write("E.g. python {} foo*.txt\n".format(argv[0]))
def text_to_pdf(txt_filename):
pw = PDFWriter(txt_filename + '.pdf')
pw.setFont('Courier', 12)
pw.setHeader('{} converted to PDF'.format(txt_filename))
pw.setFooter('PDF conversion by xtopdf: https://google.com/search?q=xtopdf')
with open(txt_filename) as txt_fil:
for line in txt_fil:
pw.writeLine(line.strip('\n'))
pw.savePage()
def main():
if len(sys.argv) != 2:
usage(sys.argv)
sys.exit(0)
try:
for filename in glob.glob(sys.argv[1]):
print("Converting {} to {}".format(filename, filename + '.pdf'))
text_to_pdf(filename)
except Exception as e:
print("Caught Exception: type: {}, message: {}".format(\
e.__class__, str(e)))
if __name__ == '__main__':
main()
|
Here is a guide to installing and using xtopdf:
http://jugad2.blogspot.in/2012/07/guide-to-installing-and-using-xtopdf.html
Use ReportLab 1.21 since that is the one that xtopdf is tested with. Any Python version in the range 2.2 to 2.7 should work, xtopdf is tested on most or all of them, but the latest 2.x version is preferred, obviously.
More details on running the program, and sample output, are available here:
http://jugad2.blogspot.in/2016/12/xtopdf-wildcard-text-files-to-pdf-with.html