我想用条形码创建pdf格式的发票, 首先使用reportlab创建条形码的mybarcode.py文件
#mybarcode.py文件创建裸码
from reportlab.lib.units import mm
from reportlab.graphics.barcode import createBarcodeDrawing
from reportlab.graphics.shapes import Drawing, String
from reportlab.graphics.charts.barcharts import HorizontalBarChart
class MyBarcodeDrawing(Drawing):
def __init__(self, text_value, *args, **kw):
barcode = createBarcodeDrawing('Code128', value=text_value, barHeight=19*mm, humanReadable=True)
Drawing.__init__(self,barcode.width,barcode.height,*args,**kw)
self.add(barcode, name='barcode')
views函数生成带条形码的pdf。
#views.py
from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus.tables import Table
cm = 2.54
def print_pdf(request):
import mybarcode
product = Product.objects.get(id = id)
d = mybarcode.MyBarcodeDrawing(product.code)
binaryStuff = d.asString('jpg')
response = HttpResponse(content_type='application/pdf')
filename=somefilename.pdf'
elements = []
doc = SimpleDocTemplate(response, rightMargin=0, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0)
data=[("barcode", binaryStuff),("name", "some_name")]
table = Table(data)
elements.append(table)
doc.build(elements)
return response
并收到此错误:'utf8'编解码器无法解码位置0中的字节0xff:无效的起始字节
答案 0 :(得分:0)
这可能会解决您的问题:
import codecs
f = codecs.open(dir+location, 'r', encoding='utf-8')
txt = f.read()
从那时起txt采用unicode格式,您可以在代码中的任何地方使用它。
如果您想在处理后生成UTF-8文件:
f.write(txt.encode('utf-8'))