Report Lab is not producing/saving a pdf file - python

Report lab is not producing a pdf in a very simple example/try:
from arcpy import *
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from pyPdf import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, cm
from reportlab.platypus import Paragraph
from reportlab.lib import colors
from reportlab.pdfgen import canvas
filename = "HelloWorld.pdf"
c = canvas.Canvas(filename)
c.drawString(100,750,"Welcome to Reportlab!")
c.save()
These two lines work fine:
c.drawString(100,750,"Welcome to Reportlab!")
c.save()
But is this one that throw the errors. I've tried to change the path, the filename, try the 'r' before the string of text for the path+filename, nothing works.
I've got this error trace:
Traceback (most recent call last):
File "C:\Users\Edmundo\GIS_SEG\EGtemp\PdfReports\PyScripts\TestRepLab.py", line 15, in <module>
c.save()
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfgen\canvas.py", line 1237, in save
self._doc.SaveToFile(self._filename, self)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 221, in SaveToFile
data = self.GetPDFData(canvas)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 246, in GetPDFData
return self.format()
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 423, in format
IOf = IO.format(self)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 871, in format
fcontent = format(self.content, document, toplevel=1) # yes this is at top level
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 80, in format
f = element.format(document)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 1561, in format
return PD.format(document)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 679, in format
L = [(format(PDFName(k),document)+b" "+format(dict[k],document)) for k in keys]
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 80, in format
f = element.format(document)
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\pdfdoc.py", line 610, in format
s.decode('pdfdoc')
File "C:\Python27\ArcGIS10.4\lib\site-packages\reportlab\pdfbase\rl_codecs.py", line 1047, in _rl_codecs
if name.startswith(e): return RL_Codecs.__rl_codecs(e)
AttributeError: 'NoneType' object has no attribute '_RL_Codecs__rl_codecs'

You need to call showPage():
from reportlab.pdfgen import canvas
filename = "HelloWorld.pdf"
c = canvas.Canvas(filename)
c.drawString(100,750,"Welcome to Reportlab!")
c.showPage()
c.save()

Related

Geopandas not working after importing a file from a different directory

I am trying to make a map in python using shapefiles I have downloaded from bbike.org. Here is my code:
import geopandas as gpd
import os
import sys
import matplotlib.pyplot as plt
bos_files_list = ['buildings.shx', 'landuse.shx', 'natural.shx', 'places.shx', 'points.shx', 'railways.shx', 'roads.shx']
cur_path = os.path.dirname(__file__)
def maps_of_bos(files):
for x in range(len(files)):
os.chdir(f'location/of/file')
f = open(f'{files[x]}', 'r')
gpd.read_file(f)
z = maps_of_bos(bos_files_list)
z.plot()
plt.show()
However, my error output is as follows:
Traceback (most recent call last):
File "test.py", line 16, in <module>
z = maps_of_bos(bos_files_list)
File "test.py", line 13, in maps_of_bos
gpd.read_file(f)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/geopandas/io/f
ile.py", line 76, in read_file
with reader(path_or_bytes, **kwargs) as features:
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 113, in
__enter__
return next(self.gen)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/fiona/__init__
.py", line 206, in fp_reader
dataset = memfile.open()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/fiona/io.py",
line 63, in open
return Collection(vsi_path, 'w', crs=crs, driver=driver,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/fiona/collecti
on.py", line 126, in __init__
raise DriverError("no driver")
fiona.errors.DriverError: no driver
I am relatively new to python, and don't really understand my error. can someone please help me?
According to the docs read_file should take the path to the file not an object.
gpd.read_file(f'{files[x]}')
you dont need
f = open(f'{files[x]}', 'r')

python error on barcode generation

I am using python 2.7 and pyBarcode 0.7 in Windows and I am trying to generate barcode as png image by using following sample code (available in pyBarcode webpage)
>>> import barcode
>>> barcode.PROVIDED_BARCODES
[u'code39', u'ean', u'ean13', u'ean8', u'gs1', u'gtin', u'isbn', u'isbn10',
u'isbn13', u'issn', u'jan', u'pzn', u'upc', u'upca']
>>> EAN = barcode.get_barcode_class('ean13')
>>> EAN
<class 'barcode.ean.EuropeanArticleNumber13'>
>>> ean = EAN(u'5901234123457')
>>> ean
<barcode.ean.EuropeanArticleNumber13 object at 0x00BE98F0>
# Example with PNG
>>> from barcode.writer import ImageWriter
>>> ean = EAN(u'5901234123457', writer=ImageWriter())
>>> fullname = ean.save('ean13_barcode')
Last line generates following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python27\lib\site-packages\barcode\base.py", line 68, in save
output = self.render(options)
File "c:\python27\lib\site-packages\barcode\ean.py", line 106, in render
return Barcode.render(self, options)
File "c:\python27\lib\site-packages\barcode\base.py", line 103, in render
raw = Barcode.raw = self.writer.render(code)
File "c:\python27\lib\site-packages\barcode\writer.py", line 188, in render
self._callbacks['paint_text'](xpos, ypos)
File "c:\python27\lib\site-packages\barcode\writer.py", line 280, in _paint_te
xt
font = ImageFont.truetype(FONT, self.font_size * 2)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 218, in truetype
return FreeTypeFont(filename, size, index, encoding)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 134, in __init__
self.font = core.getfont(file, size, index, encoding)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 34, in __getattr__
raise ImportError("The _imagingft C module is not installed")
ImportError: The _imagingft C module is not installed
I retried by installing Pillow (but before that I removed PIL); I downloaded "Pillow-4.2.1-win32-py2_7.exe"
and I did also "pip install Pillow".
Now when I try to run
import barcode
I got:
File "barcode\codex.py", line 12, in <module>
from barcode.base import Barcode
File "barcode\base.py", line 9, in <module>
from barcode.writer import SVGWriter
File "barcode\writer.py", line 12, in <module>
import Image, ImageDraw, ImageFont
File "c:\python27\lib\site-packages\PIL\Image.py", line 27, in <module>
from . import VERSION, PILLOW_VERSION, _plugins
ValueError: Attempted relative import in non-package
What should I do ?
thanks

How do I use reportlab's drawImage with an image url?

When I try the following:
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
import urllib
import StringIO
import PIL.Image
image_file = urllib.urlopen('https://www.google.com/images/srpr/logo11w.png')
image_string = StringIO.StringIO(image_file.read())
logo = PIL.Image.open(image_string)
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10)
canvas.showPage()
canvas.save()
I get this error:
Traceback (most recent call last):
File "imagefromurl.py", line 12, in <module>
canvas.drawImage(logo, 10, 10)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfgen/canvas.py", line 857, in drawImage
imgObj = pdfdoc.PDFImageXObject(name, image, mask=mask)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfbase/pdfdoc.py", line 2090, in __init__
ext = string.lower(os.path.splitext(source)[1])
File "/usr/lib/python2.7/posixpath.py", line 96, in splitext
return genericpath._splitext(p, sep, altsep, extsep)
File "/usr/lib/python2.7/genericpath.py", line 91, in _splitext
sepIndex = p.rfind(sep)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 515, in __getattr__
raise AttributeError(name)
Reportlab is version 2.5.
I was doing it the hard way. This works (also added the necessary mask to avoid transparent becoming black):
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.utils import ImageReader
logo = ImageReader('https://www.google.com/images/srpr/logo11w.png')
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10, mask='auto')
canvas.showPage()
canvas.save()
Though the hard way would have allowed me to detect a failure to fetch the image url and handle it (e.g. substituting a local image), and this doesn't.

Text to XML in python

I'm trying to convert text into xml format. And I'm using LXML Library. But I'm getting error message. Please help me. Thank you
import re
from lxml import etree
import urllib,urllib2
def get_movie_info(movie_id):
URL = "http://www.raaga.com/a/rss.asp?%s"%(movie_id)
f = urllib.urlopen(URL)
movie_info = f.read()
rss = "".join([ line.strip() for line in movie_info ])
mi_tree = etree.fromstring(rss)
#mi_title = self._parse_movie_title(mi_tree.xpath("/rss/channel/title/text()")[0])
#mi_tracks = mi_tree.xpath("/rss/channel/item")
return mi_tree
get_movie_info('A0000102')
Here is my traceback
Traceback (most recent call last):
File "py1.py", line 14, in <module>
get_movie_info('A0000102')
File "py1.py", line 9, in get_movie_info
mi_tree = etree.fromstring(rss)
File "lxml.etree.pyx", line 2743, in lxml.etree.fromstring (src/lxml\lxml.etre
e.c:52665)
File "parser.pxi", line 1573, in lxml.etree._parseMemoryDocument (src/lxml\lxm
l.etree.c:79932)
File "parser.pxi", line 1452, in lxml.etree._parseDoc (src/lxml\lxml.etree.c:7
8774)
File "parser.pxi", line 960, in lxml.etree._BaseParser._parseDoc (src/lxml\lxm
l.etree.c:75389)
File "parser.pxi", line 564, in lxml.etree._ParserContext._handleParseResultDo
c (src/lxml\lxml.etree.c:71739)
File "parser.pxi", line 645, in lxml.etree._handleParseResult (src/lxml\lxml.e
tree.c:72614)
File "parser.pxi", line 585, in lxml.etree._raiseParseError (src/lxml\lxml.etr
ee.c:71955)
lxml.etree.XMLSyntaxError: xmlParsePITarget: invalid name prefix 'xml', line 1,
column 13
It works fine for me without this string:
rss = "".join([ line.strip() for line in movie_info ])
Something like this:
mi_tree = etree.fromstring(movie_info)

How to fix such ClientForm bug?

from mechanize import Browser
br = Browser()
page = br.open('http://wow.interzet.ru/news.php?readmore=23')
br.form = br.forms().next()
print br.form
gives me the following error:
Traceback (most recent call last):
File "C:\Users\roddik\Desktop\mech.py", line 6, in <module>
br.form = br.forms().next()
File "build\bdist.win32\egg\mechanize\_mechanize.py", line 426, in forms
File "D:\py26\lib\site-package\mechanize-0.1.11-py2.6.egg\mechanize\_html.py", line 559, in forms
File "D:\py26\lib\site-packages\mechanize-0.1.11-py2.6.egg\mechanize\_html.py", line 225, in forms
File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 967, in ParseResponseEx
File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 1100, in _ParseFileEx
File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 870, in feed
File "D:\py26\lib\sgmllib.py", line 104, in feed
self.goahead(0)
File "D:\py26\lib\sgmllib.py", line 138, in goahead
k = self.parse_starttag(i)
File "D:\py26\lib\sgmllib.py", line 290, in parse_starttag
self._convert_ref, attrvalue)
File "D:\py26\lib\sgmllib.py", line 302, in _convert_ref
return self.convert_charref(match.group(2)) or \
File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 850, in convert_charref
File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 244, in unescape_charref
ValueError: invalid literal for int() with base 10: 'e'
How can I fix it?
Edit:
I've fixed it this way. Is it ok? If not, how instead?
import ClientForm
from mechanize import Browser
def myunescape_charref(data, encoding):
if not str(data).isdigit(): return 0
name, base = data, 10
if name.startswith("x"):
name, base= name[1:], 16
uc = unichr(int(name, base))
if encoding is None:
return uc
else:
try:
repl = uc.encode(encoding)
except UnicodeError:
repl = "&#%s;" % data
return repl
ClientForm.unescape_charref = myunescape_charref
The problem is caused by urls like this
http://wow.zet/forum/index.php?showtopic=1197&pid=30419&st=0&#entry30419
ClientForm is looking for an integer after the &#
It is ok to have the # in the url, but it should be escaped in the html
as &# means a character encoding

Categories