Exemplo n.º 1
0
def main():

	'''
	Program to create a PDF book from chapters contained in text files,
	one chapter per file.
	Command line args are:
	1. The name of the PDF file to create.
	2. The name of a text file containing info about chapters.
	   Format of this file:
	   Each line consists of two fields, separated by a colon.
	   Field 1 is the name of the text file containing a chapter.
	   Field 2 is the chapter title, to be used as the header/footer.
	'''
	
	# check for proper args
	if len(sys.argv) != 3:
		usage()
		sys.exit(1)

	# get the PDF file name and create the PDFWriter from it
	book_fn = sys.argv[1]
	pw = PDFWriter(book_fn)

	# set the font name and size for the PDF file
	pw.setFont("Courier", 10)

	# get the chapter list file name and open it, checking for I/O errors
	try:
		chap_list_fn = sys.argv[2]
		chap_list_fil = file(chap_list_fn)
	except IOError:
		sys.stderr.write(sys.argv[0] + ": IOError: while opening file " + \
		chap_list_fn + ". Exiting.\n")
		sys.exit(1)

	i = 0

	# loop over all the lines in the chapter list file
	for lin in chap_list_fil:
			i = i + 1
			if lin[-1] == "\n":
				lin = lin[:-1] # remove the trailing newline
			# split line into two fields, chapter file name and chapter title
			i = string.find(lin, ":")
			if (i == -1):
				sys.stderr.write(sys.argv[0] + \
				": Chapter list file format error: Line #" + \
				str(i) + " has no colon delimiter. Exiting.\n")
				chap_list_fil.close()
				sys.exit(0)
			chap_fn = lin[:i]
			chap_title = lin[i + 1:]
			# write the chapter to the PDF file
			write_chapter(pw, chap_fn, chap_title)

	pw.close()
Exemplo n.º 2
0
def dsv_to_pdf(dsv_fil, delim_char, pdf_filename):
    with PDFWriter(pdf_filename) as pw:
        pw.setFont("Courier", 12)
        pw.setHeader(pdf_filename[:-4] + " => " + pdf_filename)
        pw.setFooter("Generated by xtopdf: https://google.com/search?q=xtopdf")
        for idx, lin in enumerate(dsv_fil):
            fields = lin.split(delim_char)
            assert len(fields) > 0
            # Knock off the newline at the end of the last field,
            # since it is the line terminator, not part of the field.
            if fields[-1][-1] == '\n':
                fields[-1] = fields[-1][:-1]
            # Treat a blank line as a line with one field,
            # an empty string (that is what split returns).
            pw.writeLine(' - '.join(fields))
Exemplo n.º 3
0
def main():
    '''
	Program to create a PDF book from chapters contained in text files,
	one chapter per file.
	Command line args are:
	1. The name of the PDF file to create.
	2. The name of a text file containing info about chapters.
	   Format of this file:
	   Each line consists of two fields, separated by a colon.
	   Field 1 is the name of the text file containing a chapter.
	   Field 2 is the chapter title, to be used as the header/footer.
	'''

    # check for proper args
    if len(sys.argv) != 3:
        usage()
        sys.exit(1)

    # get the PDF file name and create the PDFWriter from it
    book_fn = sys.argv[1]
    pw = PDFWriter(book_fn)

    # set the font name and size for the PDF file
    pw.setFont("Courier", 10)

    # get the chapter list file name and open it, checking for I/O errors
    try:
        chap_list_fn = sys.argv[2]
        chap_list_fil = file(chap_list_fn)
    except IOError:
        sys.stderr.write(sys.argv[0] + ": IOError: while opening file " + \
        chap_list_fn + ". Exiting.\n")
        sys.exit(1)

    i = 0

    # loop over all the lines in the chapter list file
    for lin in chap_list_fil:
        i = i + 1
        if lin[-1] == "\n":
            lin = lin[:-1]  # remove the trailing newline
        # split line into two fields, chapter file name and chapter title
        i = string.find(lin, ":")
        if (i == -1):
            sys.stderr.write(sys.argv[0] + \
            ": Chapter list file format error: Line #" + \
            str(i) + " has no colon delimiter. Exiting.\n")
            chap_list_fil.close()
            sys.exit(0)
        chap_fn = lin[:i]
        chap_title = lin[i + 1:]
        # write the chapter to the PDF file
        write_chapter(pw, chap_fn, chap_title)

    pw.close()
Exemplo n.º 4
0
def InvoiceToPDF(pdf_filename, data):
    try:
        # Get the invoice data from the dict.
        font_name = data['font_name']
        font_size = data['font_size']
        header = data['header']
        footer = data['footer']
        invoice_number = data['invoice_number']
        invoice_customer = data['invoice_customer']
        invoice_date_time = data['invoice_date_time']
        invoice_line_items = data['invoice_line_items']
    except KeyError as ke:
        error_exit("KeyError: {}".format(ke))
    try:
        with PDFWriter(pdf_filename) as pw:
            # Generate the PDF invoice from the data.
            pw.setFont(font_name, font_size)
            pw.setHeader(header)
            pw.setFooter(footer)
            pw.writeLine('-' * 60)
            pw.writeLine('Invoice Number: ' + str(invoice_number))
            pw.writeLine('Invoice Customer: ' + invoice_customer)
            pw.writeLine('Invoice Date & Time: ' + invoice_date_time)
            pw.writeLine('-' * 60)
            pw.writeLine('Invoice line items:')
            pw.writeLine('S. No.'.zfill(5) + ' ' + 'Description'.ljust(10) + \
            ' ' + 'Unit price'.ljust(10) + ' ' + 'Quantity'.ljust(10) + ' ' + \
            str('Ext. Price').rjust(8))
            pw.writeLine('-' * 60)
            sum_ext_price = 0
            for line_item in invoice_line_items:
                id, desc, price, quantity = line_item
                pw.writeLine(str(id).zfill(5) + ' ' + desc.ljust(10) + \
                ' ' + str(price).rjust(10) + ' ' + str(quantity).rjust(10) + \
                str(price * quantity).rjust(10))
                sum_ext_price += price * quantity
            pw.writeLine('-' * 60)
            pw.writeLine('Total:'.rjust(38) + str(sum_ext_price).rjust(10))
            pw.writeLine('-' * 60)
    except IOError as ioe:
        error_exit("IOError: {}".format(ioe))
    except Exception as e:
        error_exit("Exception: {}".format(e))
Exemplo n.º 5
0
def JSONtoPDF(json_data):
    # Get the data values from the JSON string json_data.
    try:
        data = json.loads(json_data)
        pdf_filename = data['pdf_filename']
        font_name = data['font_name']
        font_size = data['font_size']
        header = data['header']
        footer = data['footer']
        lines = data['lines']
    except Exception as e:
        error_exit("Invalid JSON data: {}".format(e.message))
    # Generate the PDF using the data values.
    try:
        with PDFWriter(pdf_filename) as pw:
            pw.setFont(font_name, font_size)
            pw.setHeader(header)
            pw.setFooter(footer)
            for line in lines:
                pw.writeLine(line)
    except IOError as ioe:
        error_exit("IOError while generating PDF file: {}".format(ioe.message))
    except Exception as e:
        error_exit("Error while generating PDF file: {}".format(e.message))
Exemplo n.º 6
0
def main():

    # Create some HTML for testing conversion of its text to PDF.
    html_doc = """
    <html>
        <head>
            <title>
            Test file for HTMLTextToPDF
            </title>
        </head>
        <body>
        This is text within the body element but outside any paragraph.
        <p>
        This is a paragraph of text. Hey there, how do you do?
        The quick red fox jumped over the slow blue cow.
        </p>
        <p>
        This is another paragraph of text.
        Don't mind what it contains.
        What is mind? Not matter.
        What is matter? Never mind.
        </p>
        This is also text within the body element but not within any paragraph.
        </body>
    </html>
    """

    pw = PDFWriter("HTMLTextTo.pdf")
    pw.setFont("Courier", 10)
    pw.setHeader("Conversion of HTML text to PDF")
    pw.setFooter("Generated by xtopdf: http://slid.es/vasudevram/xtopdf")

    # Use method chaining this time.
    for line in BeautifulSoup(html_doc).get_text().split("\n"):
        pw.writeLine(line)
    pw.savePage()
    pw.close()
Exemplo n.º 7
0
by the PrettyTable library, to PDF, using the xtopdf toolkit 
for PDF creation from other formats.
Author: Vasudev Ram - http://www.dancingbison.com
xtopdf is at: http://slides.com/vasudevram/xtopdf

Copyright 2015 Vasudev Ram
"""

from prettytable import PrettyTable
from PDFWriter import PDFWriter

pt = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
pt.align["City name"] = "l"  # Left align city names
pt.padding_width = 1  # One space between column edges and contents (default)
pt.add_row(["Adelaide", 1295, 1158259, 600.5])
pt.add_row(["Brisbane", 5905, 1857594, 1146.4])
pt.add_row(["Darwin", 112, 120900, 1714.7])
pt.add_row(["Hobart", 1357, 205556, 619.5])
pt.add_row(["Sydney", 2058, 4336374, 1214.8])
pt.add_row(["Melbourne", 1566, 3806092, 646.9])
pt.add_row(["Perth", 5386, 1554769, 869.4])
lines = pt.get_string()

pw = PDFWriter('Australia-Rainfall.pdf')
pw.setFont('Courier', 12)
pw.setHeader('Demo of PrettyTable to PDF')
pw.setFooter('Demo of PrettyTable to PDF')
for line in lines.split('\n'):
    pw.writeLine(line)
pw.close()
Exemplo n.º 8
0
    name = 'Student-' + id
    # Let's grade them on the curve [1].
    # This examiner doesn't give anyone 100 marks :)
    marks = random.randint(40, 99)
    # Compute grade from marks.
    grade = grade_letters[(marks - 40) / 10]
    result = results[grade]
    columns = [id, name, marks, grade, result]

    # str.center returns a centered string of the given width. The default padding character is the space,
    # but it can be set by the user
    row = [ str(col).center(widths[idx]) for idx, col in enumerate(columns) ]
    data.append(row)

# Set up the PDFWriter.
pw = PDFWriter('student_grades.pdf')
pw.setFont('Courier', 10)
pw.setHeader('Student Grades Report - generated by xtopdf')
pw.setFooter('xtopdf: http://slides.com/vasudevram/xtopdf')

# Generate header and data rows as strings; output them to screen and PDF.

separator = '-' * sum(widths)
print_and_write(pw, separator)

# Output headers
header_strs = [ header.center(widths[idx]) for idx, header in enumerate(data.headers) ]
print_and_write(pw, ''.join(header_strs))
print_and_write(pw, separator)

# Output data
Exemplo n.º 9
0
# FirebirdToPDF.py
# Author: Vasudev Ram - http://jugad2.blogspot.com
# Demo program to show how to convert Firebird RDBMS data to PDF.
# Uses xtopdf, Reportlab, Firebird RDBMS and fdb Python driver for Firebird.

import fdb
from PDFWriter import PDFWriter

con = fdb.connect(dsn='localhost:/temp/firebird/test.fdb',
                  user='******',
                  password='******')

cur = con.cursor()
select_stmt = 'select * from contacts order by name desc'
cur.execute(select_stmt)
pw = PDFWriter("contacts.pdf")
pw.setFont("Courier", 12)
pw.setHeader("Firebird RDBMS data (contacts.fdb) to PDF")
pw.setFooter("Generated by xtopdf using fdb Firebird driver for Python")
for (id, name, address) in cur:
    print id, name, address
    pw.writeLine(str(id) + " " + name + " " + address)
pw.close()

# EOF
Exemplo n.º 10
0
"""
CalendarToPDF.py
Author: Vasudev Ram - www.dancingbison.com
Copyright 2014 Vasudev Ram
This is a demo program to generate PDF calendars.
"""

import sys
import traceback
from debug1 import debug1
import calendar
from PDFWriter import PDFWriter

try:
    cal = calendar.TextCalendar(calendar.SUNDAY)
    cal_str = cal.formatmonth(2014, 02, 4, 2)
    cal_lines = cal_str.split("\n")
    pw = PDFWriter("Calendar-February-2014.pdf")
    pw.setFont("Courier", 10)
    pw.setHeader("Calendar for February 2014")
    pw.setFooter("Generated by xtopdf: http://bit.ly/xtopdf")
    for line in cal_lines:
        if line != "":
            pw.writeLine(line)
    pw.close()
    print "Calendar generated."
except Exception as e:
    traceback.print_exc()
    sys.exit(1)
Exemplo n.º 11
0
from PDFWriter import PDFWriter

try:
    # Flag 'c' opens the DB read/write and doesn't delete it if it exists.
    fruits_db = bsddb.btopen('fruits.db', 'c')
    fruits = [('apple', 'The apple is a red fruit.'),
              ('banana', 'The banana is a yellow fruit.'),
              ('cherry', 'The cherry is a red fruit.'),
              ('durian', 'The durian is a yellow fruit.')]
    # Add the key/value fruit records to the DB.
    for fruit in fruits:
        fruits_db[fruit[0]] = fruit[1]
    fruits_db.close()

    # Read the key/value fruit records from the DB and write them to PDF.
    with PDFWriter("fruits.pdf") as pw:
        pw.setFont("Courier", 12)
        pw.setHeader("BSDDBToPDF demo: fruits.db to fruits.pdf")
        pw.setFooter("Generated by xtopdf")
        fruits_db = bsddb.btopen('fruits.db', 'c')
        print("FRUITS")
        print()
        pw.writeLine("FRUITS")
        pw.writeLine(" ")
        for key in list(fruits_db.keys()):
            print(key)
            print(fruits_db[key])
            print()
            pw.writeLine(key)
            pw.writeLine(fruits_db[key])
            pw.writeLine(" ")
Exemplo n.º 12
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()
Exemplo n.º 13
0
                        unit_price=item[3])

# define the query
query = db.furniture
# the above line shows an interesting property of PyDAL; it seems to
# have some flexibility in how queries can be defined; in this case,
# just saying db.table_name tells it to fetch all the rows
# from table_name; there are other variations possible; I have not
# checked out all the options, but the ones I have seem somewhat
# intuitive.

# run the query
rows = db(query).select()

# setup the PDFWriter
pw = PDFWriter('furniture.pdf')
pw.setFont('Courier', 10)
pw.setHeader(
    '     House Depot Stock Report - Furniture Division     '.center(60))
pw.setFooter('Generated by xtopdf: http://google.com/search?q=xtopdf')

pw.writeLine('=' * SEP)

field_widths = (5, 10, 10, 12, 10)

# print the header row
pw.writeLine(''.join(
    header_field.center(field_widths[idx])
    for idx, header_field in enumerate(('#', 'Name', 'Quantity', 'Unit price',
                                        'Price'))))
Exemplo n.º 14
0
def docx_to_pdf(infilename, outfilename):

    # Extract the text from the DOCX file object infile and write it to 
    # a PDF file.

    try:
        infil = opendocx(infilename)
    except:
        print("Error opening infilename")
        #print "Exception: " + repr(e) + "\n"
        sys.exit(1)

    paragraphs = getdocumenttext(infil)

    pw = PDFWriter(outfilename)
    pw.setFont("Courier", 12)
    pw.setHeader("DOCXtoPDF - convert text in DOCX file to PDF")
    pw.setFooter("Generated by xtopdf and python-docx")
    wrapper = TextWrapper(width=70, drop_whitespace=False)

    # For Unicode handling.
    new_paragraphs = []
    for paragraph in paragraphs:
        new_paragraphs.append(paragraph.encode("utf-8"))

    for paragraph in new_paragraphs:
        lines = wrapper.wrap(paragraph)
        for line in lines:
            pw.writeLine(line)
        pw.writeLine("")

    pw.savePage()
    pw.close()
Exemplo n.º 15
0
for i in range(20):
    id = str(i).zfill(2)
    name = 'Student-' + id
    # Let's grade them on the curve [1].
    # This examiner doesn't give anyone 100 marks :)
    marks = random.randint(40, 99)
    # Compute grade from marks.
    grade = grade_letters[(marks - 40) / 10]
    result = results[grade]
    columns = [id, name, marks, grade, result]
    row = [str(col).center(widths[idx]) for idx, col in enumerate(columns)]
    data.append(row)

# Set up the PDFWriter.
pw = PDFWriter('student_grades.pdf')
pw.setFont('Courier', 10)
pw.setHeader('Student Grades Report - generated by xtopdf')
pw.setFooter('xtopdf: http://slides.com/vasudevram/xtopdf')

# Generate header and data rows as strings; output them to screen and PDF.

separator = '-' * sum(widths)
print_and_write(pw, separator)

# Output headers
header_strs = [
    header.center(widths[idx]) for idx, header in enumerate(data.headers)
]
print_and_write(pw, ''.join(header_strs))
print_and_write(pw, separator)
Exemplo n.º 16
0
def pdf_book():
    if request.method == 'GET':
        # Display the PDF book creation form.
        return '''
            <form action="/pdf_book" method="post">
                PDF file name: <input type="text" name="pdf_file_name" />

                Header: <input type="text" name="header" />
                Footer: <input type="text" name="footer" />

                Content:
                <textarea name="content" rows="15" cols="50"></textarea>

                <input type="submit" value="Submit" />

            </form>
            '''
    else:
        # Create the PDF book from the posted form content.
        try:
            # Get the needed fields from the form.
            pdf_file_name = request.form['pdf_file_name']
            header = request.form['header']
            footer = request.form['footer']
            content = request.form['content']

            # Create a PDFWriter instance and set some of its fields.
            pw = PDFWriter(pdf_file_name)
            pw.setFont("Courier", 12)
            pw.setHeader(header)
            pw.setFooter(footer)

            # Get the content field.
            # Split it into paragraphs delimited by newlines.
            # Convert each paragraph into a list of lines of
            # maximum width 70 characters.
            # Print each line to the PDF file.
            paragraphs = content.split('\n')
            wrapper = TextWrapper(width=70, drop_whitespace=False)
            for paragraph in paragraphs:
                lines = wrapper.wrap(paragraph)
                for line in lines:
                    pw.writeLine(line)

            pw.savePage()
            pw.close()
            return "OK. PDF book created in file " + pdf_file_name + ".\n"
        except Exception, e:
            traceback.print_stack()
            return "Error: PDF book not created.\n" + repr(e) + ".\n"
Exemplo n.º 17
0
    curs.execute(
        "INSERT INTO stocks VALUES ('2006-01-05', 'BUY', 'RHAT', 100, 25.1)")
    curs.execute(
        "INSERT INTO stocks VALUES ('2007-02-06', 'SELL', 'ORCL', 200, 35.2)")
    curs.execute(
        "INSERT INTO stocks VALUES ('2008-03-07', 'HOLD', 'IBM', 300, 45.3)")
    conn.commit()

    # Create a namedtuple to represent stock rows.
    StockRecord = namedtuple('StockRecord', 'date, trans, symbol, qty, price')

    # Run the query to get the stocks data.
    curs.execute("SELECT date, trans, symbol, qty, price FROM stocks")

    # Create a PDFWriter and set some of its fields.
    pw = PDFWriter("stocks.pdf")
    pw.setFont("Courier", 12)
    pw.setHeader("SQLite data to PDF with named tuples")
    pw.setFooter(
        "Generated by xtopdf - https://bitbucket.org/vasudevram/xtopdf")

    # Write header info.
    hdr_flds = [
        str(hdr_fld).rjust(10) + " " for hdr_fld in StockRecord._fields
    ]
    hdr_fld_str = ''.join(hdr_flds)
    print_and_write(pw, '=' * len(hdr_fld_str))
    print_and_write(pw, hdr_fld_str)
    print_and_write(pw, '-' * len(hdr_fld_str))

    # Now loop over the fetched data and write it to PDF.
Exemplo n.º 18
0
def main():
    try:
        # Create and set up a PDFWriter instance.
        pw = PDFWriter("PopenTo.pdf")
        pw.setFont("Courier", 12)
        pw.setHeader("Use subprocess.Popen to read pipe and write to PDF.")
        pw.setFooter(
            "Done using selpg, xtopdf, Python and ReportLab, on Linux.")

        # Set up a pipeline with nl and selpg such that we can read from its stdout.
        # nl numbers the lines of the input.
        # selpg extracts pages 3 to 5 from the input.
        pipe = subprocess.Popen("nl -ba 1000-lines.txt | selpg -s3 -e5", \
            shell=True, bufsize=-1, stdout=subprocess.PIPE,
            stderr=sys.stderr).stdout

        # Read from the pipeline and write the data to PDF, using the PDFWriter instance.
        for idx, line in enumerate(pipe):
            pw.writeLine(str(idx).zfill(8) + ": " + line)
    except IOError as ioe:
        error_exit("Caught IOError: {}".format(str(ioe)))
    except Exception as e:
        error_exit("Caught Exception: {}".format(str(e)))
    finally:
        pw.close()
Exemplo n.º 19
0
def docx_to_pdf(infilename, outfilename):

    # Extract the text from the DOCX file object infile and write it to 
    # a PDF file.

    try:
        infil = opendocx(infilename)
    except Exception, e:
        print "Error opening infilename"
        print "Exception: " + repr(e) + "\n"
        sys.exit(1)

    paragraphs = getdocumenttext(infil)

    pw = PDFWriter(outfilename)
    pw.setFont("Courier", 12)
    pw.setHeader("DOCXtoPDF - convert text in DOCX file to PDF")
    pw.setFooter("Generated by xtopdf and python-docx")
    wrapper = TextWrapper(width=70, drop_whitespace=False)

    # For Unicode handling.
    new_paragraphs = []
    for paragraph in paragraphs:
        new_paragraphs.append(paragraph.encode("utf-8"))

    for paragraph in new_paragraphs:
        lines = wrapper.wrap(paragraph)
        for line in lines:
            pw.writeLine(line)
        pw.writeLine("")
Exemplo n.º 20
0
# xlsxtopdf.py
# program to conver xlsx file to pdf

from openpyxl import load_workbook
from PDFWriter import PDFWriter

workbook = load_workbook('test.xlsx', guess_types=True, data_only=True)
worksheet = workbook.active

pw = PDFWriter('test.pdf')
pw.setFont('Courier', 12)
pw.setHeader('xlsxtopdf.py - convert xlsx file to pdf')
pw.setFooter('generated using openpyxl and xtopdf')

ws_range = worksheet.iter_rows('A1:H13')
for row in ws_range:
    s = ''
    for cell in row:
        if cell.value is None:
            s += ' ' * 11
        else:
            s += str(cell.value).rjust(10) + ' '
        pw.writeLine(s)

pw.savePage()
pw.close()
Exemplo n.º 21
0
def app(environ, start_response):
    path = environ['PATH_INFO']
    method = environ['REQUEST_METHOD']
    print("path:", path)
    print("method:", method)

    #response = 'This is the page for "{}"'.format(path)

    lines = [
        "Jack and Jill went up the hill", "Humpty Dumpty sat on a wall,",
        "'You are old, Father William,' the young man said,",
        "Master of all masters"
    ]

    pdf_filename = "Nursery-rhymes-and-stories.pdf"
    pw = PDFWriter(pdf_filename)
    pw.setFont("Courier", 12)
    pw.setHeader("Excerpts from nursery rhymes and stories")
    pw.setFooter("Generated by xtopdf and basic_wsgi_pdf_server")

    for line in lines:
        pw.writeLine(line)
        pw.writeLine(" ")
    pw.close()

    with open(pdf_filename, "rb") as fil:
        response = fil.read()

    #start_response('200 OK', [('Content-type', 'text/html')])
    start_response('200 OK', [('Content-type', 'application/pdf')])
    return [response]
Exemplo n.º 22
0
# FirebirdToPDF.py
# Author: Vasudev Ram - http://jugad2.blogspot.com
# Demo program to show how to convert Firebird RDBMS data to PDF.
# Uses xtopdf, Reportlab, Firebird RDBMS and fdb Python driver for Firebird.

import fdb
from PDFWriter import PDFWriter

con = fdb.connect(dsn='localhost:/temp/firebird/test.fdb', 
    user='******',  password='******')

cur = con.cursor()
select_stmt = 'select * from contacts order by name desc'
cur.execute(select_stmt)
pw = PDFWriter("contacts.pdf")
pw.setFont("Courier", 12)
pw.setHeader("Firebird RDBMS data (contacts.fdb) to PDF")
pw.setFooter("Generated by xtopdf using fdb Firebird driver for Python")
for (id, name, address) in cur:
    print id, name, address
    pw.writeLine(str(id) + " " + name + " " + address)
pw.close()

# EOF
Exemplo n.º 23
0
20    024    14    00010100    DC4             Device Control 4
21    025    15    00010101    NAK             Negative Acknowledgement
22    026    16    00010110    SYN             Synchronous Idle
23    027    17    00010111    ETB             End of Transmit Block
24    030    18    00011000    CAN             Cancel
25    031    19    00011001    EM             End of Medium
26    032    1A    00011010    SUB             Substitute
27    033    1B    00011011    ESC             Escape
28    034    1C    00011100    FS             File Separator
29    035    1D    00011101    GS             Group Separator
30    036    1E    00011110    RS             Record Separator
31    037    1F    00011111    US             Unit Separator
"""

# Create and set some of the fields of a PDFWriter instance.
pw = PDFWriter("ASCII-Table.pdf")
pw.setFont("Courier", 12)
pw.setHeader("ASCII Control Characters - 0 to 31")
pw.setFooter("Generated by xtopdf: http://slid.es/vasudevram/xtopdf")

# Write the column headings to the output.
column_headings = [ str(val).ljust(column_widths[idx]) \
    for idx, val in enumerate(column_names) ]
pw.writeLine(' '.join(column_headings))

# Split the string into lines, omitting the first and last empty lines.
for line in ascii_control_characters.split('\n')[1:-1]:

    # Split the line into space-delimited fields.
    lis = line.split()
Exemplo n.º 24
0
23    027    17    00010111    ETB             End of Transmit Block
24    030    18    00011000    CAN             Cancel
25    031    19    00011001    EM             End of Medium
26    032    1A    00011010    SUB             Substitute
27    033    1B    00011011    ESC             Escape
28    034    1C    00011100    FS    
         File Separator
29    035    1D    00011101    GS    
         Group Separator
30    036    1E    00011110    RS    
         Record Separator
31    037    1F    00011111    US             Unit Separator
"""

# Create and set some of the fiels of a PDF witer
p = PDFWriter("ASCII-Table.pdf")
p.setFont("Courier", 12)
p.setHeader("ASCII Characters - 0 to 31")
p.setFooter("Generated by xtopdf: http://slid.es/vasudevram/xtopdf")

#write the column headings to output
column_headings = [str(val).ljust(column_sizes[idx])\
 for idx, val in enumerate(column_names)]
p.writeLine(' '.join(column_headings))

#Split the string into lines
for line in ascii_chars.split('\n')[1:-1]:

    #space-delimited fields
    l = line.split()
    l2 = l[0:5] + [' '.join(l[6:])]
Exemplo n.º 25
0
def get_pdf():
    pw = PDFWriter('hello-from-netius.pdf')
    pw.setFont('Courier', 10)
    pw.setHeader('PDF generated by xtopdf, a PDF library for Python')
    pw.setFooter('Using netius Python network library, at {}'.format(time.ctime()))
    pw.writeLine('Hello world! This is a test PDF served by Netius, ')
    pw.writeLine('a Python networking library; PDF created with the help ')
    pw.writeLine('of xtopdf, a Python library for PDF creation.')
    pw.close()
    pdf_fil = open('hello-from-netius.pdf', 'rb')
    pdf_str = pdf_fil.read()
    pdf_len = len(pdf_str)
    pdf_fil.close()
    return pdf_len, pdf_str
Exemplo n.º 26
0
# Define some contact rows.
contacts = (('Albert Einstein', 22, 'Science',
             'Physicist'), ('Benjamin Franklin', 32, 'Many', 'Polymath'),
            ('Samuel Johnson', 42, 'Writing', 'Writer'))

# Save the contact rows to the contacts table.
for contact in contacts:
    c = Contact(name=contact[0], age=contact[1], \
    skills=contact[2], title=contact[3])
    c.save()

sep = '-' * (20 + 5 + 10 + 15)

# Publish the contact rows to PDF.
with PDFWriter('contacts.pdf') as pw:
    pw.setFont('Courier', 12)
    pw.setHeader('Demo of publishing Peewee ORM data to PDF')
    pw.setFooter('Generated by xtopdf: slides.com/vasudevram/xtopdf')
    print_and_write(pw, sep)
    print_and_write(
        pw, "Name".ljust(20) + "Age".center(5) + "Skills".ljust(10) +
        "Title".ljust(15))
    print_and_write(pw, sep)

    # Loop over all rows queried from the contacts table.
    for contact in Contact.select():
        print_and_write(
            pw,
            contact.name.ljust(20) + str(contact.age).center(5) +
            contact.skills.ljust(10) + contact.title.ljust(15))
Exemplo n.º 27
0
data = \
[
    ['North', 'Desktop #1', 1000],
    ['South', 'Desktop #3', 1100],
    ['North', 'Laptop #7', 1200],
    ['South', 'Keyboard #4', 200],
    ['North', 'Mouse #2', 50],
    ['East', 'Tablet #5', 200],
    ['West', 'Hard disk #8', 500],
    ['West', 'CD-ROM #6', 150],
    ['South', 'DVD Drive', 150],
    ['East', 'Offline UPS', 250],
]

pw = PDFWriter('SalesReport.pdf')
pw.setFont('Courier', 12)
pw.setHeader('Sales by Region')
pw.setFooter('Using itertools.groupby and xtopdf')

# Convenience function to both print to screen and write to PDF.
def print_and_write(s, pw):
    print(s)
    pw.writeLine(s)

# Set column headers.
headers = ['Region', 'Item', 'Sale Value']
# Set column widths.
widths = [ 10, 15, 10 ]
# Build header string for report.
header_str = ''.join([hdr.center(widths[ind]) \
Exemplo n.º 28
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()
Exemplo n.º 29
0
import sys
from xlwings import Workbook, Sheet, Range, Chart
from PDFWriter import PDFWriter

# Create a connection with a new workbook.
wb = Workbook()

# Create the Excel data.
# Column 1.
Range('A1').value = 'Foo 1'
Range('A2').value = 'Foo 2'
Range('A3').value = 'Foo 3'
# Column 2.
Range('B1').value = 'Bar 1'
Range('B2').value = 'Bar 2'
Range('B3').value = 'Bar 3'

pw = PDFWriter("xlwingsTo.pdf")
pw.setFont("Courier", 10)
pw.setHeader("Testing Excel conversion to PDF with xlwings and xtopdf")
pw.setFooter(
    "xlwings: http://xlwings.org --- xtopdf: http://slid.es/vasudevram/xtopdf")

for row in Range('A1..B3').value:
    s = ''
    for col in row:
        s += col + ' | '
    pw.writeLine(s)

pw.close()
Exemplo n.º 30
0
def main():
    '''Main program to test DBFReader class.
	'''

    # check for right num. of args
    if (len(sys.argv) != 3):
        usage()
        sys.exit(1)

    # extract dbf and pdf filenames from args
    dbf_fn = sys.argv[1]
    pdf_fn = sys.argv[2]

    # create and open the DBFReader instance
    dr = DBFReader(dbf_fn)
    dr.open()

    # create the PDFWriter instance
    pw = PDFWriter(pdf_fn)

    # and set some of its fields

    # set the font
    pw.setFont("Courier", 10)

    # set the page header
    gen_datetime = time.asctime()
    pw.setHeader("Generated by DBFtoPDF: Input: " + dbf_fn + \
    " At: " + gen_datetime)

    # set the page footer
    pw.setFooter("Generated by DBFtoPDF: Input: " + dbf_fn + \
    " At: " + gen_datetime)

    # create the separator for logical grouping of output
    sep = "=" * 60

    # get the DBF file header
    file_header = dr.read_dbf_file_header()

    # print a separator line
    pw.writeLine(sep)

    # print title for the overall output
    pw.writeLine("Information for DBF file: %s" % (dbf_fn))

    # print a separator line
    pw.writeLine(sep)

    # print the file header section title
    pw.writeLine("")
    pw.writeLine("File Header Information:")

    # print a separator line
    pw.writeLine(sep)

    # setup labels for file header output
    lbl_dbf_ver = \
    "DBF version (signature)       : "
    lbl_last_update = \
    "Date of last update (YY/MM/DD): "
    lbl_num_recs = \
    "Number of data records        : "
    lbl_hdr_len = \
    "DBF header length in bytes    : "
    lbl_rec_len = \
    "DBF record length in bytes    : "
    lbl_num_flds = \
    "Number of fields in DBF file  : "

    # print the file header metadata with labels
    pw.writeLine(lbl_dbf_ver + str(file_header['ver']))
    pw.writeLine(lbl_last_update + file_header['last_update'])
    pw.writeLine(lbl_num_recs + str(file_header['num_recs']))
    pw.writeLine(lbl_hdr_len + str(file_header['hdr_len']))
    pw.writeLine(lbl_rec_len + str(file_header['rec_len']))
    pw.writeLine(lbl_num_flds + str(file_header['num_flds']))

    # print a separator line
    pw.writeLine(sep)

    # save current page
    pw.savePage()

    # print the field headers section title
    pw.writeLine("Field Header Information:")

    # print a separator line
    pw.writeLine(sep)

    # print labels for field headers output
    pw.writeLine("%3s%13s%7s%8s%10s" % \
       ("#", "Field name", "Type", "Length", "Decimals"))

    # print a separator line
    pw.writeLine(sep)

    # get num. of fields from file header
    num_flds = file_header["num_flds"]

    # get the field headers
    field_headers = dr.read_dbf_field_headers()

    # extract individual lists from the field headers list of lists
    fld_nam, fld_typ, fld_len, fld_dec = (field_headers[0], field_headers[1],
                                          field_headers[2], field_headers[3])

    fld_num = 0

    # print the field headers metadata
    while (fld_num < num_flds):
        s1 = "%3s" % (fld_num + 1)
        s2 = "%13s" % (fld_nam[fld_num])
        #s3 =  "%4s" % (string.replace(fld_typ[fld_num], '\0', ' ')) ,
        s3 = "%4s" % (fld_typ[fld_num])
        s4 = "%5s" % (fld_len[fld_num])
        s5 = "%7s" % (fld_dec[fld_num])

        s = s1 + " " + s2 + " " + s3 + " " + s4 + " " + s5
        pw.writeLine(s)
        fld_num = fld_num + 1

    # print a separator line
    pw.writeLine(sep)

    # save current page
    pw.savePage()

    # position the DBFReader instance to start reading data records
    dr.reset()

    # print the data records section title
    pw.writeLine("DBF Data Records:")

    # print a separator line
    pw.writeLine(sep)

    # print the data records
    rec_num = 0
    while (dr.has_next_record()):
        rec_num = rec_num + 1
        # get next data record from the DBFReader
        r = dr.next_record()
        # convert it from a list to a human-friendly string
        fr = dbf_record_to_string(r)
        # the serial num. of the record
        s1 = "%7d:" % (rec_num)
        # the record itself
        s2 = "%s" % (fr)
        # serial num. + record
        s = s1 + " " + s2
        # print the record
        pw.writeLine(s)

    # print a separator line
    pw.writeLine(sep)

    # save current page
    pw.savePage()

    # close the DBFReader
    dr.close()

    # close the PDFWriter
    pw.close()
Exemplo n.º 31
0
def main():

    if len(sys.argv) < 3:
        usage(sys.argv[0])
        sys.exit(0)

    try:
        pw = PDFWriter(sys.argv[1])
        pw.setFont('Courier', 12)
        pw.setFooter('xtopdf: https://google.com/search?q=xtopdf')

        for line in fileinput.input(sys.argv[2:]):
            if fileinput.filelineno() == 1:
                pw.setHeader(fileinput.filename())
                if fileinput.lineno() != 1:
                    pw.savePage()
            pw.writeLine(line.strip('\n'))

        pw.savePage()
        pw.close()
    except Exception as e:
        print("Caught Exception: type: {}, message: {}".format(\
            e.__class__, str(e)))
Exemplo n.º 32
0
                 (date text, trans text, symbol text, qty real, price real)''')

    # Insert a few rows of data into the stocks table.
    curs.execute("INSERT INTO stocks VALUES ('2006-01-05', 'BUY', 'RHAT', 100, 25.1)")
    curs.execute("INSERT INTO stocks VALUES ('2007-02-06', 'SELL', 'ORCL', 200, 35.2)")
    curs.execute("INSERT INTO stocks VALUES ('2008-03-07', 'HOLD', 'IBM', 300, 45.3)")
    conn.commit()

    # Create a namedtuple to represent stock rows.
    StockRecord = namedtuple('StockRecord', 'date, trans, symbol, qty, price')

    # Run the query to get the stocks data.
    curs.execute("SELECT date, trans, symbol, qty, price FROM stocks")

    # Create a PDFWriter and set some of its fields.
    pw = PDFWriter("stocks.pdf")
    pw.setFont("Courier", 12)
    pw.setHeader("SQLite data to PDF with named tuples")
    pw.setFooter("Generated by xtopdf - https://bitbucket.org/vasudevram/xtopdf")

    # Write header info.
    hdr_flds = [ str(hdr_fld).rjust(10) + " " for hdr_fld in StockRecord._fields ]
    hdr_fld_str = ''.join(hdr_flds)
    print_and_write(pw, '=' * len(hdr_fld_str))
    print_and_write(pw, hdr_fld_str)
    print_and_write(pw, '-' * len(hdr_fld_str))

    # Now loop over the fetched data and write it to PDF.
    # Map the StockRecord namedtuple's _make class method
    # (that creates a new instance) to all the rows fetched.
    for stock in map(StockRecord._make, curs.fetchall()):
Exemplo n.º 33
0
Blog: http://jugad2.blogspot.com
Product store on Gumroad: https://gumroad.com/vasudevram
'''


def print_and_write(s, pw):
    print(s)
    pw.writeLine(s)


sa, lsa = sys.argv, len(sys.argv)
if lsa == 1:
    sys.stderr.write("Usage: {} out_filename.pdf\n".format(sa[0]))
    sys.exit(1)

with PDFWriter(sa[1]) as pw:

    pw.setFont('Courier', 12)
    pw.setHeader('*** Number table: 0 to 255 in bases 2, 8, 10, 16 ***')
    pw.setFooter('*** By xtopdf: https://google.com/search?q=xtopdf ***')
    b = "Bin"
    o = "Oct"
    d = "Dec"
    h = "Hex"
    header = "{b:>10}{o:>10}{d:>10}{h:>10}".format(b=b, o=o, d=d, h=h)

    for i in range(256):
        if i % 16 == 0:
            print_and_write(header, pw)
        print_and_write("{b:>10}{o:>10}{d:>10}{h:>10}".format( \
            b=bin(i), o=oct(i), d=str(i), h=hex(i)), pw)
Exemplo n.º 34
0
def XMLtoPDFBook():

    debug("Entered XMLtoPDFBook()")

    global sysargv

    # Get command-line arguments.
    xml_filename = get_xml_filename(sysargv)
    debug("xml_filename: " + xml_filename)
    pdf_filename = get_pdf_filename(sysargv)
    debug("pdf_filename: " + pdf_filename)

    # Parse the XML file.
    try:
        tree = ET.ElementTree(file=xml_filename)
        debug("tree = " + repr(tree))
    except Exception:
        sys.stderr.write("Error: caught exception in ET.ElementTree(file)")
        sys.exit(1)

    # Get the tree root.
    root = tree.getroot()
    debug("root.tag = " + root.tag)
    if root.tag != "book":
        debug("Error: Root tag is not 'book'")
        sys.exit(1)

    # Initialize the table of contents list.
    toc = []
    # Initialize the chapters list.
    chapters = []

    # Traverse the tree, extracting needed data into variables.
    debug("-" * 60)
    for root_child in root:
        if root_child.tag != "chapter":
            debug("Error: root_child tag is not 'chapter'")
            sys.exit(1)
        chapter = root_child
        #debug(chapter.text)
        chapters.append(chapter.text)
        try:
            chapter_name = chapter.attrib['name']
        except KeyError:
            chapter_name = ""
        toc.append(chapter_name)
        debug("-" * 60)

    # Create and set some fields of a PDFWriter.
    pw = PDFWriter(pdf_filename)
    pw.setFont("Courier", 12)
    pw.setFooter("Generated by XMLtoPDFBook. Copyright 2013 Vasudev Ram")

    # Write the TOC.
    pw.setHeader("Table of Contents")
    chapter_num = 0
    debug("Chapter names")
    for chapter_name in toc:
        debug(chapter_name)
        chapter_num += 1
        pw.writeLine(str(chapter_num) + ": " + chapter_name)
    pw.savePage()

    # Write the chapters.
    chapter_num = 0
    for chapter in chapters:
        chapter_num += 1
        pw.setHeader("Chapter " + str(chapter_num) + ": " +
                     toc[chapter_num - 1])
        lines = chapter.split("\n")
        for line in lines:
            pw.writeLine(line)
        pw.savePage()

    pw.close()

    debug("Exiting XMLtoPDFBook()")
Exemplo n.º 35
0
def app(environ, start_response):
    path = environ['PATH_INFO']
    method = environ['REQUEST_METHOD']
    print "path:", path
    print "method:", method

    #response = 'This is the page for "{}"'.format(path)

    lines = [
            "Jack and Jill went up the hill",
            "Humpty Dumpty sat on a wall,",
            "'You are old, Father William,' the young man said,",
            "Master of all masters"
            ]

    pdf_filename = "Nursery-rhymes-and-stories.pdf"
    pw = PDFWriter(pdf_filename)
    pw.setFont("Courier", 12)
    pw.setHeader("Excerpts from nursery rhymes and stories")
    pw.setFooter("Generated by xtopdf and basic_wsgi_pdf_server")

    for line in lines:
        pw.writeLine(line)
        pw.writeLine(" ")
    pw.close()

    with open(pdf_filename, "rb") as fil:
        response = fil.read()

    #start_response('200 OK', [('Content-type', 'text/html')])
    start_response('200 OK', [('Content-type', 'application/pdf')])
    return [response]
Exemplo n.º 36
0
def main():

    # Create some HTML for testing conversion of its text to PDF.
    html_doc = """
    <html>
        <head>
            <title>
            Test file for HTMLTextToPDF
            </title>
        </head>
        <body>
        This is text within the body element but outside any paragraph.
        <p>
        This is a paragraph of text. Hey there, how do you do?
        The quick red fox jumped over the slow blue cow.
        </p>
        <p>
        This is another paragraph of text.
        Don't mind what it contains.
        What is mind? Not matter.
        What is matter? Never mind.
        </p>
        This is also text within the body element but not within any paragraph.
        </body>
    </html>
    """

    pw = PDFWriter("HTMLTextTo.pdf")
    pw.setFont("Courier", 10)
    pw.setHeader("Conversion of HTML text to PDF")
    pw.setFooter("Generated by xtopdf: http://slid.es/vasudevram/xtopdf")
 
    # Use method chaining this time.
    for line in BeautifulSoup(html_doc).get_text().split("\n"):
        pw.writeLine(line)
    pw.savePage()
    pw.close()
Exemplo n.º 37
0
# XLSXtoPDF.py

# Program to convert the data from an XLSX file to PDF.
# Uses the openpyxl library and xtopdf.

# Author: Vasudev Ram - http://jugad2.blogspot.com
# Copyright 2015 Vasudev Ram.

from openpyxl import load_workbook
from PDFWriter import PDFWriter

workbook = load_workbook('fruits2.xlsx', guess_types=True, data_only=True)
worksheet = workbook.active

pw = PDFWriter('fruits2.pdf')
pw.setFont('Courier', 12)
pw.setHeader('XLSXtoPDF.py - convert XLSX data to PDF')
pw.setFooter('Generated using openpyxl and xtopdf')

ws_range = worksheet.iter_rows('A1:H13')
for row in ws_range:
    s = ''
    for cell in row:
        if cell.value is None:
            s += ' ' * 11
        else:
            s += str(cell.value).rjust(10) + ' '
    pw.writeLine(s)
pw.savePage()
pw.close()
Exemplo n.º 38
0
by the PrettyTable library, to PDF, using the xtopdf toolkit 
for PDF creation from other formats.
Author: Vasudev Ram - http://www.dancingbison.com
xtopdf is at: http://slides.com/vasudevram/xtopdf

Copyright 2015 Vasudev Ram
"""

from prettytable import PrettyTable
from PDFWriter import PDFWriter

pt = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
pt.align["City name"] = "l" # Left align city names
pt.padding_width = 1 # One space between column edges and contents (default)
pt.add_row(["Adelaide",1295, 1158259, 600.5])
pt.add_row(["Brisbane",5905, 1857594, 1146.4])
pt.add_row(["Darwin", 112, 120900, 1714.7])
pt.add_row(["Hobart", 1357, 205556, 619.5])
pt.add_row(["Sydney", 2058, 4336374, 1214.8])
pt.add_row(["Melbourne", 1566, 3806092, 646.9])
pt.add_row(["Perth", 5386, 1554769, 869.4])
lines = pt.get_string()

pw = PDFWriter('Australia-Rainfall.pdf')
pw.setFont('Courier', 12)
pw.setHeader('Demo of PrettyTable to PDF')
pw.setFooter('Demo of PrettyTable to PDF')
for line in lines.split('\n'):
    pw.writeLine(line)
pw.close()
Exemplo n.º 39
0
# test_pdfwriter.py

from PDFWriter import PDFWriter

with PDFWriter("test_pdfwriter.pdf") as pw:

    pw.setFont("Courier", 12)
    pw.setHeader("Input: test_pdfwriter.py Output: test_pdfwriter.pdf")
    pw.setFooter("Generated by xtopdf: http://bit.ly/xtopdf")

    with open("test_pdfwriter.py") as in_fil:
        for lin in in_fil:
            pw.writeLine(lin)
Exemplo n.º 40
0
def main():

	'''Main program to test DBFReader class.
	'''

	# check for right num. of args
	if (len(sys.argv) != 3):
		usage()
		sys.exit(1)

	# extract dbf and pdf filenames from args
	dbf_fn = sys.argv[1]
	pdf_fn = sys.argv[2]

	# create and open the DBFReader instance
	dr = DBFReader(dbf_fn)
	dr.open()

	# create the PDFWriter instance
	pw = PDFWriter(pdf_fn)

	# and set some of its fields

	# set the font
	pw.setFont("Courier", 10)

	# set the page header
	gen_datetime = time.asctime()
	pw.setHeader("Generated by DBFtoPDF: Input: " + dbf_fn + \
	" At: " + gen_datetime)

	# set the page footer
	pw.setFooter("Generated by DBFtoPDF: Input: " + dbf_fn + \
	" At: " + gen_datetime)

	# create the separator for logical grouping of output
	sep = "=" * 60

	# get the DBF file header
	file_header = dr.read_dbf_file_header()

	# print a separator line
	pw.writeLine(sep)

	# print title for the overall output
	pw.writeLine("Information for DBF file: %s" % (dbf_fn))

	# print a separator line
	pw.writeLine(sep)

	# print the file header section title
	pw.writeLine("")
	pw.writeLine("File Header Information:")

	# print a separator line
	pw.writeLine(sep)

	# setup labels for file header output
	lbl_dbf_ver = \
	"DBF version (signature)       : "
	lbl_last_update = \
	"Date of last update (YY/MM/DD): "
	lbl_num_recs = \
	"Number of data records        : "
	lbl_hdr_len = \
	"DBF header length in bytes    : "
	lbl_rec_len = \
	"DBF record length in bytes    : "
	lbl_num_flds = \
	"Number of fields in DBF file  : "

	# print the file header metadata with labels
	pw.writeLine(lbl_dbf_ver + str(file_header['ver']))
	pw.writeLine(lbl_last_update + file_header['last_update'])
	pw.writeLine(lbl_num_recs + str(file_header['num_recs']))
	pw.writeLine(lbl_hdr_len + str(file_header['hdr_len']))
	pw.writeLine(lbl_rec_len + str(file_header['rec_len']))
	pw.writeLine(lbl_num_flds + str(file_header['num_flds']))

	# print a separator line
	pw.writeLine(sep)

	# save current page
	pw.savePage()

	# print the field headers section title
	pw.writeLine("Field Header Information:")

	# print a separator line
	pw.writeLine(sep)

	# print labels for field headers output
	pw.writeLine("%3s%13s%7s%8s%10s" % \
		  ("#", "Field name", "Type", "Length", "Decimals"))

	# print a separator line
	pw.writeLine(sep)

	# get num. of fields from file header
	num_flds = file_header["num_flds"]

	# get the field headers
	field_headers = dr.read_dbf_field_headers()

	# extract individual lists from the field headers list of lists
	fld_nam, fld_typ, fld_len, fld_dec = (
		field_headers[0], 
		field_headers[1], 
		field_headers[2], 
		field_headers[3] )

	fld_num = 0

	# print the field headers metadata
	while (fld_num < num_flds):
		s1 =  "%3s" % (fld_num + 1) 
		s2 =  "%13s" % (fld_nam[fld_num])
		#s3 =  "%4s" % (string.replace(fld_typ[fld_num], '\0', ' ')) ,
		s3 =  "%4s" % (fld_typ[fld_num])
		s4 =  "%5s" % (fld_len[fld_num])
		s5 =  "%7s" % (fld_dec[fld_num])

		s = s1 + " " + s2 + " " + s3 + " " + s4 + " " + s5
		pw.writeLine(s)
		fld_num = fld_num + 1
		
	# print a separator line
	pw.writeLine(sep)

	# save current page
	pw.savePage()

	# position the DBFReader instance to start reading data records
	dr.reset()

	# print the data records section title
	pw.writeLine("DBF Data Records:")

	# print a separator line
	pw.writeLine(sep)
	
	# print the data records
	rec_num = 0
	while (dr.has_next_record()):
		rec_num = rec_num + 1
		# get next data record from the DBFReader
		r = dr.next_record()
		# convert it from a list to a human-friendly string
		fr = dbf_record_to_string(r)
		# the serial num. of the record
		s1 = "%7d:" % (rec_num)
		# the record itself
		s2 = "%s" % (fr)
		# serial num. + record
		s = s1 + " " + s2
		# print the record
		pw.writeLine(s)

	# print a separator line
	pw.writeLine(sep)

	# save current page
	pw.savePage()

	# close the DBFReader
	dr.close()

	# close the PDFWriter
	pw.close()
Exemplo n.º 41
0
def pdf_book():
    if request.method == 'GET':
        # Display the PDF book creation form.
        return '''
            <form action="/pdf_book" method="post">
                PDF file name: <input type="text" name="pdf_file_name" />

                Header: <input type="text" name="header" />
                Footer: <input type="text" name="footer" />

                Content:
                <textarea name="content" rows="15" cols="50"></textarea>

                <input type="submit" value="Submit" />

            </form>
            '''
    else:
        # Create the PDF book from the posted form content.
        try:
            # Get the needed fields from the form.
            pdf_file_name = request.form['pdf_file_name']
            header = request.form['header']
            footer = request.form['footer']
            content = request.form['content']

            # Create a PDFWriter instance and set some of its fields.
            pw = PDFWriter(pdf_file_name)
            pw.setFont("Courier", 12)
            pw.setHeader(header)
            pw.setFooter(footer)

            # Get the content field.
            # Split it into paragraphs delimited by newlines.
            # Convert each paragraph into a list of lines of
            # maximum width 70 characters.
            # Print each line to the PDF file.
            paragraphs = content.split('\n')
            wrapper = TextWrapper(width=70, drop_whitespace=False)
            for paragraph in paragraphs:
                lines = wrapper.wrap(paragraph)
                for line in lines:
                    pw.writeLine(line)

            pw.savePage()
            pw.close()
            return "OK. PDF book created in file " + pdf_file_name + ".\n"
        except Exception, e:
            traceback.print_stack()
            return "Error: PDF book not created.\n" + repr(e) + ".\n" 
Exemplo n.º 42
0
    db.furniture.insert(id=item[0], name=item[1], quantity=item[2], unit_price=item[3])

# define the query
query = db.furniture
# the above line shows an interesting property of PyDAL; it seems to 
# have some flexibility in how queries can be defined; in this case,
# just saying db.table_name tells it to fetch all the rows 
# from table_name; there are other variations possible; I have not 
# checked out all the options, but the ones I have seem somewhat 
# intuitive.

# run the query
rows = db(query).select()

# setup the PDFWriter
pw = PDFWriter('furniture.pdf')
pw.setFont('Courier', 10)
pw.setHeader('     House Depot Stock Report - Furniture Division     '.center(60))
pw.setFooter('Generated by xtopdf: http://google.com/search?q=xtopdf')

pw.writeLine('=' * SEP)

field_widths = (5, 10, 10, 12, 10)

# print the header row
pw.writeLine(''.join(header_field.center(field_widths[idx]) for idx, header_field in enumerate(('#', 'Name', 'Quantity', 'Unit price', 'Price'))))

pw.writeLine('-' * SEP)

# print the data rows
for row in rows:
Exemplo n.º 43
0
# StdinToPDF.py

# Read the contents of stdin (standard input) and write it to a PDF file
# whose name is specified as a command line argument.
# Author: Vasudev Ram - http://www.dancingbison.com
# This program is part of the xtopdf toolkit:
#     https://bitbucket.org/vasudevram/xtopdf

import sys
from PDFWriter import PDFWriter

try:
    with PDFWriter(sys.argv[1]) as pw:
        pw.setFont("Courier", 12)
        for lin in sys.stdin:
            pw.writeLine(lin)
except Exception as e:
    print("ERROR: Caught exception: " + repr(e))
    sys.exit(1)
Exemplo n.º 44
0
def main():
    try:
        # Create and set up a PDFWriter instance.
        pw = PDFWriter("PopenTo.pdf")
        pw.setFont("Courier", 12)
        pw.setHeader("Use subprocess.Popen to read pipe and write to PDF.")
        pw.setFooter("Done using selpg, xtopdf, Python and ReportLab, on Linux.")

        # Set up a pipeline with nl and selpg such that we can read from its stdout.
        # nl numbers the lines of the input.
        # selpg extracts pages 3 to 5 from the input.
        pipe = subprocess.Popen("nl -ba 1000-lines.txt | selpg -s3 -e5", \
            shell=True, bufsize=-1, stdout=subprocess.PIPE, 
            stderr=sys.stderr).stdout

        # Read from the pipeline and write the data to PDF, using the PDFWriter instance.
        for idx, line in enumerate(pipe):
            pw.writeLine(str(idx).zfill(8) + ": " + line)
    except IOError as ioe:
        error_exit("Caught IOError: {}".format(str(ioe)))
    except Exception as e:
        error_exit("Caught Exception: {}".format(str(e)))
    finally:
        pw.close()