def test_send_with_files(self): file1 = BytesIO(get_binay('blablabla\blabla.')) file2 = open(join(dirname(__file__), 'static', 'lucterios.mailing', 'images', 'config_mail.png'), mode='rb') try: configSMTP('localhost', 1025) self.assertEqual(0, self.server.count()) self.assertEqual(True, will_mail_send()) send_email('*****@*****.**', 'send with files', '2 files sent!', [('filename1.txt', file1), ('filename2.png', file2)]) self.assertEqual(1, self.server.count()) self.assertEqual('*****@*****.**', self.server.get(0)[1]) self.assertEqual(['*****@*****.**'], self.server.get(0)[2]) msg, msg_f1, msg_f2 = self.server.check_first_message( 'send with files', 3) self.assertEqual('text/plain', msg.get_content_type()) self.assertEqual('base64', msg.get('Content-Transfer-Encoding', '')) self.assertEqual('2 files sent!', decode_b64(msg.get_payload())) self.assertEqual(None, self.server.smtp.auth_params) self.assertTrue('filename1.txt' in msg_f1.get('Content-Type', ''), msg_f1.get('Content-Type', '')) self.assertEqual('blablabla\blabla.', decode_b64(msg_f1.get_payload())) self.assertTrue('filename2.png' in msg_f2.get('Content-Type', ''), msg_f2.get('Content-Type', '')) file2.seek(0, SEEK_END) self.assertEqual(file2.tell(), len(b64decode(msg_f2.get_payload()))) finally: file1.close() file2.close()
def __readNdxFile(self, file, dic): fileName = file.filename sizeFile = file.file_size fileData = self.__zipFile.read(fileName, 'rU') bt = BytesIO(fileData) bt.seek(0) lenBytes = bt.read(2) # lenSum = self.BytesToInt(lenBytes) # print "lenSum = ", lenSum while bt.tell() < sizeFile: lenBytes12 = bt.read(12) # NULL bytes bytesNull = lenBytes12[0:2] bytesNullInt = self.BytesToInt(bytesNull) # FILETIME bytes bytesFileTime = lenBytes12[2:10] bytesFileTimeInt = self.BytesToInt(bytesFileTime) # offset in PDT bytes bytesOffsetPdt = lenBytes12[10:12] bytesOffsetPdtInt = self.BytesToInt(bytesOffsetPdt) startTimeInt = self.FiletimeToUnixtimestamp(bytesFileTimeInt) if bytesOffsetPdtInt not in dic.keys(): dic[bytesOffsetPdtInt] = [None, None] dic[bytesOffsetPdtInt][1] = startTimeInt bt.close()
def parse_data(src): # HTML解析 et = html.fromstring(src) # 整理数据 product_items_list = et.xpath( "//div[@class='list-product']//div[@class='plp-slide']") final_list = [] for i in product_items_list: data = {} data["img_box_src"] = i.xpath(".//div[@class='img-box']//img/@lazysrc") data["img_box_src"] = data["img_box_src"][0] if data[ "img_box_src"] else "" data["goods_tit"] = i.xpath(".//p[@class='goods-tit']/a/text()") data["goods_tit"] = data["goods_tit"][0] if data["goods_tit"] else "" data["goods_introudce"] = i.xpath( ".//p[@class='goods-introudce']/a/text()") data["goods_introudce"] = data["goods_introudce"][0] if data[ "goods_introudce"] else "" goods_classify = i.xpath(".//div[@class='goods-classify']//span") gc_list = data["goods_classify"] = [] for gc in goods_classify: dgc = {} dgc["title"] = gc.xpath("./img/@title") dgc["title"] = dgc["title"][0] if dgc["title"] else "" dgc["title"] = dgc["title"].replace('\xa0', ' ') dgc["code"] = gc.xpath("./@data-code") dgc["code"] = dgc["code"][0] if dgc["code"] else "" dgc["saleprice"] = gc.xpath("./@data-saleprice") dgc["saleprice"] = dgc["saleprice"][0] if dgc["saleprice"] else "" dgc["img_src"] = gc.xpath("./img/@src") dgc["img_src"] = dgc["img_src"][0] if dgc["img_src"] else "" # 解析SKU颜色值 if dgc["img_src"]: req_img = requests.get(dgc["img_src"], verify=False) img_data = req_img.content bio = BytesIO() bio.write(img_data) bio.seek(0) pimg = Image.open(bio) # 读入PIL图像 pimg.thumbnail((1, 1)) # 转换为1x1像素的图片 r, g, b = pimg.getcolors( pimg.size[0] * pimg.size[1])[0][1] # 形式:[(1, (223, 218, 212))] dgc["img_color"] = '#%02x%02x%02x' % (r, g, b) pimg.close() bio.close() else: dgc["img_color"] = "" gc_list.append(dgc) final_list.append(data) return final_list
def create_thumbnail(image_model_instance): image_path = image_model_instance.original.name image_name = image_path.split('/').pop() pil_image = open_image(MEDIA_ROOT + image_path) pil_image.thumbnail(thumbnail_size, Image.ANTIALIAS) f = BytesIO() try: pil_image.save(f, format=u'JPEG') s = f.getvalue() image_model_instance.thumbnail.save("thumb_%s" % image_name, ContentFile(s)) finally: f.close()
def pdf_response(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="test.pdf"' buff = BytesIO() p = canvas.Canvas(buff) p.drawString(100, 100, "hello world.") p.showPage() p.save() pdf = buff.getvalue() buff.close() response.write(pdf) return response
def __readPdtFile(self, file, dic): fileName = file.filename sizeFile = file.file_size fileData = self.__zipFile.read(fileName, 'rU') bt = BytesIO(fileData) bt.seek(int('0x01A', 0)) while bt.tell() < sizeFile: pos = bt.tell() lenBytes = bt.read(2) lenBytesHex = "0x" + ''.join( [ "%02X" % ord( x ) for x in reversed(lenBytes) ] ) lenSum = int(lenBytesHex, 0) bytesProName = unicode(bt.read(lenSum), self.__jtvEncodeProgrammName) if pos not in dic.keys(): dic[pos] = [None, None] dic[pos][0] = bytesProName bt.close()
def get(self, request, *args, **kwargs): #Indicamos el tipo de contenido a devolver, en este caso un pdf response = HttpResponse(content_type='application/pdf') #La clase io.BytesIO permite tratar un array de bytes como un fichero binario, se utiliza como almacenamiento temporal buffer = BytesIO() #Canvas nos permite hacer el reporte con coordenadas X y Y pdf = canvas.Canvas(buffer) #Llamo al método cabecera donde están definidos los datos que aparecen en la cabecera del reporte. self.cabecera(pdf) self.tabla(pdf) self.razas(pdf) #Con show page hacemos un corte de página para pasar a la siguiente pdf.showPage() pdf.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
async def run_wsgi_feeder(self, scope: Scope, receive: Receive, fut: Awaitable[None], input_io: BytesIO): while not fut.done(): event = await receive() if event["type"] == "http.disconnect": input_io.close() break # Use exponential back-off until each attempt is 30 seconds apart. b = 0 while len(input_io.getbuffer()) > 1024 * 1024: await asyncio.sleep(0.1 * (1.1**b)) if b < 60: b += 1 input_io.write(event.get("body", b"")) if not event.get("more_body", False): input_io.close() break
def update_item_pic(self, args): job_item = args[0] file_name = job_item.file_name item_obj = job_item.item_obj # ----此处二次处理图片为缩略图,避免内存溢出,并使用高斯模糊滤镜---- # PIL打开图片 img = Image.open(file_name) # 锁定长宽比缩小图片 w, h = img.size ratio = self.PIC_SIZE / (h if h >= w else w) img = img.resize((int(w * ratio), int(h * ratio)), Image.ANTIALIAS) w, h = img.size # 顺便重新获取大小,供后面计算使用 # 高斯模糊 img = img.filter(ImageFilter.GaussianBlur(radius=2)) # 暂存于内存中,使用BytesIO bio = BytesIO() img.save(bio, 'jpeg') # 关闭PIL图像句柄 img.close() # 利用QPainter将图片在QImage内居中显示 qimg = QImage.fromData(bio.getvalue()) new_qimg = QImage(self.PIC_SIZE, self.PIC_SIZE, QImage.Format_ARGB32) new_qimg.fill(Qt.white) # 填充白色作为背景,否则显示效果会有些诡异 pnt = QPainter() pnt.begin( new_qimg ) # 经测试,在slot里面一定要用QPainter.begin()、QPainter.end(),否则会报错“QPaintDevice: Cannot destroy paint device that is being painted” pnt.drawImage(max((self.PIC_SIZE - w) / 2, 0), max((self.PIC_SIZE - h) / 2, 0), qimg) # 居中画图 pnt.end() # 将QImage显示在QListWidgetItem上 icon = QIcon(QPixmap.fromImage(new_qimg)) item_obj.setIcon(icon) # 将QListWidgetItem对象添加到界面上的QListWidget中 with self.data_lock: self.lwPicsList.addItem(item_obj) self.update_label_text(self.LABEL_FMT.format(len(self.data_list))) # 关闭BytesIO句柄 bio.close()
def writepkg(self, pkg_filename, include_media): "Code copied from gramps/plugins/export/exportpkg.py" try: archive = tarfile.open(pkg_filename, 'w:gz') except EnvironmentError as msg: log.warning(str(msg)) self.user.notify_error( _('Failure writing %s') % pkg_filename, str(msg)) return 0 # Write media files first, since the database may be modified # during the process (i.e. when removing object) if include_media: for m_id in self.db.get_media_handles(sort_handles=True): mobject = self.db.get_media_from_handle(m_id) filename = media_path_full(self.db, mobject.get_path()) archname = str(mobject.get_path()) if os.path.isfile(filename) and os.access(filename, os.R_OK): archive.add(filename, archname, filter=fix_mtime) # Write XML now g = BytesIO() gfile = XmlWriter(self.db, self.user, 2, compress=1, material_type=self.material_type, description=self.description) gfile.write_handle(g) tarinfo = tarfile.TarInfo('data.gramps') tarinfo.size = len(g.getvalue()) tarinfo.mtime = time.time() if not win(): tarinfo.uid = os.getuid() tarinfo.gid = os.getgid() g.seek(0) archive.addfile(tarinfo, g) archive.close() g.close() return True
def handle_form(): # file = request.files['file'] # filename = secure_filename(file.filename) # file_path = os.path.join(path, filename) # file.save(file_path) # doc = docx.Document(file_path) filename = 'quote.docx' file_path = os.path.join(path, filename) content = request.data # create_folder('./Document1/') folder_path = str(os.getcwd()) id = uuid.uuid1() os.makedirs('./' + id.hex) # session_id = request.headers['Session-Id'] session_id = '00DN0000000Xus2MAC!AR0AQB7ICQROcGsf6X_a1zamtLOJ1MLO9Ut1a1ndex3NfUbRQV.HePM9mTGyP.YNv_eNewYtp_rlIBBukTXOykCdhkCh57i1' instance_url = request.headers['baseUrl'] record_id = request.headers['recordId'] print("headers-->{}".format(request.data)) bytes = b64decode(content) # f = open(file_path,'wb') source_stream = BytesIO(content) doc = Document(source_stream) source_stream.close() # f.write(bytes) # f.close # doc = docx.Document(documentx) full_text = [] field_list = [] child_obj_metadata = [] for para in doc.paragraphs: full_text.append(para.text) document_data = '\n'.join(full_text) field_list = re.findall("\\$\\{(.*?)\\}", document_data) child_obj_metadata = re.findall("\\$tbl\\{(.*?)\\}", document_data) head_child_obj = '' for table in doc.tables: for row in table.rows: for cell in row.cells: full_text.append(cell.text) fields_in_cell = re.findall("\\$\\{(.*?)\\}", cell.text) child_obj_values = re.findall("\\$tbl\\{(.*?)\\}", cell.text) child_obj_str = [] if len(child_obj_values) > 0: child_obj_str = re.findall("\\$tbl{START:(.*):", cell.text) if len(child_obj_str) > 0: head_child_obj = child_obj_str[0] if len(fields_in_cell) > 0 and fields_in_cell[0].split( '.')[1] == head_child_obj.strip(): for field in fields_in_cell: child_obj_metadata.append(field) elif len(fields_in_cell) > 0: for field in fields_in_cell: field_list.append(field) field_list = list(dict.fromkeys(field_list)) #This block will do json formation of fields and parent objects which will be returned to salesforce for retrieving data if len(field_list) > 0: obj_wrapper = obj_wrap(field_list[0].split('.')[0], False, [], [], []) field_wrapper = [] parent_wrapper = [] parent_field_wrapper = [] grand_parent_field_wrapper = [] grand_wrapper = [] for field in field_list: format_type = re.findall("(#[A-Z]*)", field) if len(format_type) > 0: corrected_field = field.replace(format_type[0], '') else: corrected_field = field parent_obj = corrected_field.split('.') if len(parent_obj) == 2: field_wrap = field_wrap_obj(parent_obj[-1], False) if field_wrap not in field_wrapper: field_wrapper.append(field_wrap) else: field_wrap = field_wrap_obj(parent_obj[1], False) if field_wrap.__dict__ not in field_wrapper: field_wrapper.append(field_wrap.__dict__) filtered_obj = parent_obj[1:len(parent_obj)] if len(filtered_obj) == 3: parent_field_wrap = field_wrap_obj(filtered_obj[1], False) if parent_field_wrap not in parent_field_wrapper: parent_field_wrapper.append(parent_field_wrap) grand_parent_field_wrap = field_wrap_obj( filtered_obj[2], False) if grand_parent_field_wrap not in grand_parent_field_wrapper: grand_parent_field_wrapper.append( grand_parent_field_wrap) grand_wrap = grand_wrap_obj(filtered_obj[1], False, grand_parent_field_wrapper) if len(grand_wrapper) > 0: check_grobj_list = list() for obj in grand_wrapper: check_grobj_list.append(obj.objName) if grand_wrap.objName not in check_grobj_list: grand_wrapper.append(grand_wrap) elif { 'fieldName': filtered_obj[2] } not in grand_wrapper[check_grobj_list.index( grand_wrap.objName)].fieldWrapperList: grand_wrapper[check_grobj_list.index( grand_wrap.objName)].fieldWrapperList.append( field_wrap_obj(filtered_obj[2], False)) else: grand_wrapper.append(grand_wrap) parent_wrap = parent_wrap_obj(filtered_obj[0], False, parent_field_wrapper, [], [], grand_wrapper) if len(parent_wrapper) > 0: check_obj_list = list() for obj in parent_wrapper: check_obj_list.append(obj.objName) if parent_wrap.objName not in check_obj_list: parent_wrapper.append(parent_wrap) else: if field_wrap_obj( filtered_obj[1], False ) not in parent_wrapper[check_obj_list.index( parent_wrap.objName)].fieldWrapperList: parent_wrapper[check_obj_list.index( parent_wrap.objName )].fieldWrapperList.append( field_wrap_obj(filtered_obj[1], False)) if 'grandObjWrapperList' in parent_wrapper[ check_obj_list.index( parent_wrap.objName)]: parent_wrapper[check_obj_list.index( parent_wrap. objName)].grandObjWrapperList.append( grand_wrap_obj( filtered_obj[1], False, [ field_wrap_obj( filtered_obj[2], False) ])) else: parent_wrapper[check_obj_list.index( parent_wrap. objName)].grandObjWrapperList = [ grand_wrap_obj( filtered_obj[1], False, [ field_wrap_obj( filtered_obj[2], False) ]) ] else: check_grandobj_list = list() if 'grandObjWrapperList' in parent_wrapper[ check_obj_list.index( parent_wrap.objName)]: for obj in parent_wrapper[ check_obj_list.index( parent_wrap.objName )].grandObjWrapperList: check_grandobj_list.append(obj.objName) else: check_grandobj_list = [] if grand_wrap.objName not in check_grandobj_list: grand_wrapper.append(grand_wrap) else: if field_wrap_obj( filtered_obj[2], False) not in parent_wrapper[ check_obj_list.index( parent_wrap.objName )].grandObjWrapperList[ check_grandobj_list.index( grand_wrap.objName )].fieldWrapperList: parent_wrapper[check_obj_list.index( parent_wrap.objName )].grandObjWrapperList[ check_grandobj_list.index( grand_wrap.objName )].fieldWrapperList.append( field_wrap_obj( filtered_obj[2], False)) else: parent_wrapper.append(parent_wrap) grand_wrap = {} grand_parent_field_wrap = {} parent_field_wrap = {} parent_wrap = {} parent_field_wrapper = [] grand_parent_field_wrapper = [] grand_wrapper = [] elif len(filtered_obj) == 2: parent_field_wrap = field_wrap_obj(filtered_obj[-1], False) check_parent_obj_list = list() for obj in parent_wrapper: check_parent_obj_list.append(obj.objName) if ({ 'objName': filtered_obj[0] } in check_parent_obj_list ) and parent_field_wrap not in parent_wrapper[ check_parent_obj_list.index( filtered_obj[0])]['fieldWrapperList']: parent_field_wrapper.append(parent_field_wrap) parent_wrap = parent_wrap_obj(filtered_obj[0], False, parent_field_wrapper, [], [], []) if len(parent_wrapper) > 0: check_obj_list = list() for obj in parent_wrapper: check_obj_list.append(obj.objName) if parent_wrap.objName not in check_obj_list: parent_wrap.fieldWrapperList = [ field_wrap_obj(filtered_obj[-1], False) ] parent_wrapper.append(parent_wrap) parent_field_wrapper = [] elif { 'fieldName': filtered_obj[-1], 'isExists': False } not in parent_wrapper[check_obj_list.index( parent_wrap.objName)].fieldWrapperList: parent_wrapper[check_obj_list.index( parent_wrap.objName)].fieldWrapperList.append( field_wrap_obj(filtered_obj[-1], False)) parent_field_wrapper = [] else: parent_wrap.fieldWrapperList.append( field_wrap_obj(filtered_obj[-1], False)) parent_wrapper.append(parent_wrap) parent_field_wrapper = [] parent_field_wrapper = [] obj_wrapper.fieldWrapperList = field_wrapper obj_wrapper.parentObjWrapperList = parent_wrapper parent_wrapper = [] parent_field_wrapper = [] parent_field_wrap = {} parent_wrap = {} old_child_obj_meta = [] #Method to return index of the obj def check_obj_present(current_obj, child_wrapper): obj_list = list() for record in child_wrapper.parentObjWrapperList: obj_list.append(record.objName) if len(obj_list) > 0: try: return obj_list.index(current_obj) except ValueError: return -1 else: return -1 #Method to return index of the parent obj def check_grand_obj_present(current_obj, child_wrapper, parent_index): obj_list = list() for record in child_wrapper.parentObjWrapperList[ parent_index].grandObjWrapperList: obj_list.append(record.objName) if len(obj_list) > 0: try: return obj_list.index(current_obj) except ValueError: return -1 else: return -1 #Method to generate childWrapper def generate_child_obj(child_obj, child_wrapper): child1_field_wrap = field_wrap_obj(child_obj[2], False) if child1_field_wrap not in child_wrapper.fieldWrapperList: child_wrapper.fieldWrapperList.append(child1_field_wrap) if len(child_obj) == 4: index_value = check_obj_present(child_obj[2], child_wrapper) if index_value == -1: child_wrapper.parentObjWrapperList.append( parent_wrap_obj(child_obj[2], False, field_wrap_obj(child_obj[3], False), [], [])) else: if field_wrap_obj( child_obj[3], False) not in child_wrapper.parentObjWrapperList[ check_obj_present(child_obj[2], child_wrapper)].fieldWrapperList: child_wrapper.parentObjWrapperList[check_obj_present( child_obj[2], child_wrapper)].fieldWrapperList.append( field_wrap_obj(child_obj[3], False)) if len(child_obj) == 5: index_value = check_obj_present(child_obj[2], child_wrapper) if index_value == -1: child_wrapper.parentObjWrapperList.append( parent_wrap_obj( child_obj[2], False, [field_wrap_obj(child_obj[3], False)], [ grand_wrap_obj( child_obj[3], False, [field_wrap_obj(child_obj[4], False)]) ])) else: if field_wrap_obj( child_obj[3], False) not in child_wrapper.parentObjWrapperList[ index_value].fieldWrapperList: child_wrapper.parentObjWrapperList[ index_value].fieldWrapperList.append( field_wrap_obj(child_obj[3], False)) grand_index_value = check_grand_obj_present( child_obj[3], child_wrapper, index_value) if grand_index_value == -1: child_wrapper.parentObjWrapperList[ index_value].grandObjWrapperList.append( grand_wrap_obj( child_obj[3], False, [field_wrap_obj(child_obj[4], False)])) else: child_wrapper.parentObjWrapperList[ index_value].grandObjWrapperList[ grand_index_value].fieldWrapperList.append( field_wrap_obj(child_obj[4], False)) return child_wrapper if len(child_obj_metadata) > 0: child_wrapper = child_wrap_obj('', False, [], [], '') child_obj_list = [] child_wrapper_list = [] for field in child_obj_metadata: child_obj = field.split('.') if child_obj not in old_child_obj_meta: if child_obj[1] not in child_obj_list: head_obj = re.findall("\\$tbl{START:[A-Za-z]\\:(.*)", document_data) child_obj_check = child_wrap_obj(child_obj[1], False, [], [], '') child_wrapper = generate_child_obj(child_obj, child_obj_check) child_obj_list.append(child_obj[1]) child_wrapper_list.append(child_wrapper) else: child_wrapper = generate_child_obj( child_obj, child_wrapper_list[child_obj_list.index(child_obj[1])]) child_wrapper_list[child_obj_list.index( child_obj[1])] = child_wrapper old_child_obj_meta.append(child_obj) obj_wrapper.childObjWrapperList = child_wrapper_list obj_wrapper = json.dumps(obj_wrapper, default=lambda o: o.__dict__) r = requests.post(instance_url + "/services/apexrest/data_retrieve/" + record_id, data=obj_wrapper, headers={ "Authorization": 'OAuth ' + session_id, 'Content-Type': 'application/json', 'recordId': record_id }) print("response-->{}".format(r)) data_dict = json.loads(r.json()) # r = get_data_sf() # data_dict = json.loads(r.text) bind_values_doc(data_dict, doc) docx_stream = io.BytesIO() doc.save(docx_stream) docx_bytes = docx_stream.getvalue() encoded = base64.b64encode(docx_bytes) data = { "Name": "demoAttachment.pdf", "Body": str(encoded)[2:-1], "parentId": record_id } # salesforce_response = requests.post(instance_url+"/services/data/v47.0/sobjects/Attachment",data=data,headers = {"Authorization":'OAuth '+'00D0p0000000V5HEAU!AQgAQEWkzrkC5T1NKhmV2C43BfSYR.2NbZ2VxatnomppLnH9V6hnFl1SCwIun9Cm2FI9Xbdpt_Lp6ie.pUyXXuFKfFisMEiJ','Content-Type': 'application/json'}) # print("salesforce_response-->{}".format(salesforce_response)) return json.dumps(data) else: obj_wrapper = json.dumps(obj_wrapper, default=lambda o: o.__dict__) print("ObjMetaDataInfo-->{}".format(obj_wrapper)) r = requests.post(instance_url + "/services/apexrest/data_retrieve/" + record_id, data=obj_wrapper, headers={ "Authorization": 'OAuth ' + session_id, 'Content-Type': 'application/json', 'recordId': record_id }) data_dict = json.loads(r.json()) print("session_id-->{}".format(data_dict)) bind_values_doc(data_dict, doc) docx_stream = io.BytesIO() doc.save(docx_stream) docx_bytes = docx_stream.getvalue() encoded = base64.b64encode(docx_bytes) data = { "Name": "demoAttachment.pdf", "Body": str(encoded)[2:-1], "parentId": record_id } # r = get_data_sf() # data_dict = json.loads(r.text) # bind_values_doc(data_dict,file_path) return json.dumps(data)
def export_bangdiem(baithi): ''' export bang diem ra pdf ''' rows_len = len(baithi) table_data=[] table_data.append([u'BỘ QUỐC PHÒNG', u'CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM']) table_data.append([u'HỌC VIỆN HẬU CẦN', u'Độc lập - Tự do - Hạnh phúc']) table_data.append([u'', u'Hà Nội, ngày ' + str(timezone.now().day) + u' tháng ' + str(timezone.now().month) + u' năm ' + str(timezone.now().year)]) buf = BytesIO() # file_name = 'dethi.pdf' doc = SimpleDocTemplate(buf) pars = [Spacer(1, 0.1*inch)] # pars = [] title_table = Table(table_data, colWidths=[250, PAGE_WIDTH-250]) title_table.setStyle(TableStyle([('FONT', (0,0), (1,1), 'TimesBd', 13), ('FONT', (0,2), (-1,-1), 'Times', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ])) pars.append(title_table) pars.append(Spacer(1, 0.5*inch)) bd_title_table_data = [[u'BÁO CÁO KẾT QUẢ THI']] bd_title_table_data.append([u'môn: ' + baithi[0].khthi.mon_thi.ten_mon_thi + u' đvht: ' + str(baithi[0].khthi.mon_thi.so_dvht)]) ngay_thi = '%d - %d - %d' %(baithi[0].khthi.ngay_thi.day, baithi[0].khthi.ngay_thi.month, baithi[0].khthi.ngay_thi.year) bd_title_table_data.append([u'lớp: ' + baithi[0].thi_sinh.lop.ten_lop + u' ngày thi: ' + ngay_thi]) bd_title_table = Table(bd_title_table_data, colWidths=[PAGE_WIDTH]) bd_title_table.setStyle(TableStyle([('FONT', (0,0), (0,0), 'TimesBd', 14), ('FONT', (0,1), (-1,-1), 'Times', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), #('BOX', (1,0), (-1,-1), 1.25, colors.black), ])) pars.append(bd_title_table) pars.append(Spacer(1, 0.5*inch)) bd_table_data = [[u'STT', u'Họ tên', u'Điểm', u'Ghi chú']] n = 1 for bt in baithi: row = [str(n), bt.thi_sinh.get_ho_ten, str(bt.diem), ""] bd_table_data.append(row) n = n + 1 bd_table = Table(bd_table_data, colWidths=[50, 250, 50, 100]) bd_table.setStyle(TableStyle([('FONT', (0,0), (3,0), 'TimesBd', 13), ('FONT', (0,1), (-1,-1), 'Times', 13), ('ALIGN', (0,0), (-1,0), 'CENTER'), #header ('ALIGN', (0,0), (0,-1), 'CENTER'), #STT ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.5, colors.black), ])) pars.append(bd_table) pars.append(Spacer(1, 0.5*inch)) # ký sig_table_data = [[u'-------HẾT--------', u'']] sig_table_data.append([u'' ,u'TRƯỞNG KHOA']) sig_table_data.append([u'' ,u'(Ký, họ tên)']) sig_table = Table(sig_table_data, colWidths=[PAGE_WIDTH-300, 200]) sig_table.setStyle(TableStyle([('FONT', (0,0), (1,0), 'Times', 13), ('FONT', (0,1), (1,1), 'TimesBd', 13), ('FONT', (0,2), (1,2), 'TimesIt', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('SPAN',(0,0),(1,0)), ])) pars.append(sig_table) doc.build(pars, onFirstPage=myFirstPage, onLaterPages=myLaterPages) # Get the value of the BytesIO buffer and write it to the response. pdf = buf.getvalue() buf.close() return pdf
def export_baithi_dapan_pdf(de_thi, dapan, baithi): ''' export de thi trac nghiem ra pdf ''' socau = len(dapan) table_data=[] table_data.append([u'HỌC VIỆN HẬU CẦN', u'ĐÁP ÁN MÔN THI']) table_data.append([u'%s' %de_thi.logSinhDe.monHoc.khoa.ten_dv, u'MÔN: ' + de_thi.logSinhDe.monHoc.ten_mon_thi]) table_data.append([u'', u'Đối tượng: ' + de_thi.logSinhDe.doiTuong.ten_dt]) table_data.append([u'', u'Thời gian: ']) table_data.append([u'', u'Đề gồm: ' + str(socau) + u' câu']) buf = BytesIO() # file_name = 'dethi.pdf' doc = SimpleDocTemplate(buf) pars = [Spacer(1, 0.1*inch)] # pars = [] title_table = Table(table_data, colWidths=[(PAGE_WIDTH-100)/2.0]*2) title_table.setStyle(TableStyle([('FONT', (0,0), (1,1), 'TimesBd', 13), ('FONT', (0,2), (-1,-1), 'Times', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ])) pars.append(title_table) pars.append(Spacer(1, 0.5*inch)) sv_info_table_data = [[u'Mã môn học: '+ de_thi.logSinhDe.monHoc.ma_mon_thi + u' - Số tín chỉ (hoặc đvht): ' , u'Mã đề thi']] sv_info_table_data.append([u'Lớp: ' ,de_thi.maDeThi + baithi.thi_sinh.ma_sv.split('-')[1]]) sv_info_table_data.append([u'Mã học viên, sinh viên: ','']) sv_info_table_data.append([u'Họ tên học viên, sinh viên: ','']) sv_info_table = Table(sv_info_table_data, colWidths=[PAGE_WIDTH-200, 100]) sv_info_table.setStyle(TableStyle([('FONT', (1,0), (-1,-1), 'TimesBd', 13), ('FONT', (0,0), (0,-1), 'Times', 13), ('ALIGN', (1,0), (-1,-1), 'CENTER'), ('BOX', (1,0), (-1,-1), 1.25, colors.black), ])) pars.append(sv_info_table) pars.append(Spacer(1, 0.5*inch)) for i in xrange(1, len(dapan)+1): cau_hoi = str(i) dap_an = dapan[cau_hoi] # question p = Paragraph(u'Câu ' + cau_hoi + ": " + dap_an, answer_stype) pars.append(p) pars.append(Spacer(1, 0.05*inch)) # ký sig_table_data = [[u'-------HẾT--------', u'']] sig_table_data.append([u'' ,u'TRƯỞNG KHOA']) sig_table_data.append([u'' ,u'(Ký, họ tên)']) sig_table = Table(sig_table_data, colWidths=[PAGE_WIDTH-300, 200]) sig_table.setStyle(TableStyle([('FONT', (0,0), (1,0), 'Times', 13), ('FONT', (0,1), (1,1), 'TimesBd', 13), ('FONT', (0,2), (1,2), 'TimesIt', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('SPAN',(0,0),(1,0)), ])) pars.append(sig_table) doc.build(pars, onFirstPage=myFirstPage, onLaterPages=myLaterPages) # Get the value of the BytesIO buffer and write it to the response. pdf = buf.getvalue() buf.close() return pdf
def export_pdf(de_thi, dapan): ''' export de thi trac nghiem ra pdf ''' socau = len(dapan) table_data=[] table_data.append([u'HỌC VIỆN HẬU CẦN', u'ĐỀ THI KẾT THÚC MÔN']) table_data.append([u'%s' %de_thi.logSinhDe.monHoc.khoa.ten_dv, u'MÔN: ' + de_thi.logSinhDe.monHoc.ten_mon_thi]) table_data.append([u'', u'Đối tượng: ' + de_thi.logSinhDe.doiTuong.ten_dt]) table_data.append([u'', u'Thời gian: ']) table_data.append([u'', u'Đề gồm: ' + str(socau) + u' câu']) buf = BytesIO() # file_name = 'dethi.pdf' doc = SimpleDocTemplate(buf) pars = [Spacer(1, 0.1*inch)] # pars = [] title_table = Table(table_data, colWidths=[(PAGE_WIDTH-100)/2.0]*2) title_table.setStyle(TableStyle([('FONT', (0,0), (1,1), 'TimesBd', 13), ('FONT', (0,2), (-1,-1), 'Times', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ])) pars.append(title_table) pars.append(Spacer(1, 0.5*inch)) sv_info_table_data = [[u'Mã môn học: '+ de_thi.logSinhDe.monHoc.ma_mon_thi + u' - Số tín chỉ (hoặc đvht): ' , u'Mã đề thi']] sv_info_table_data.append([u'Lớp: ' ,de_thi.maDeThi]) sv_info_table_data.append([u'Mã học viên, sinh viên: ','']) sv_info_table_data.append([u'Họ tên học viên, sinh viên: ','']) sv_info_table = Table(sv_info_table_data, colWidths=[PAGE_WIDTH-200, 100]) sv_info_table.setStyle(TableStyle([('FONT', (1,0), (-1,-1), 'TimesBd', 13), ('FONT', (0,0), (0,-1), 'Times', 13), ('ALIGN', (1,0), (-1,-1), 'CENTER'), ('BOX', (1,0), (-1,-1), 1.25, colors.black), ])) pars.append(sv_info_table) pars.append(Spacer(1, 0.5*inch)) n = 1 for question, answers in dapan: # question p = Paragraph(u'Câu ' + str(n) + ": " + question.noiDung, question_style) n += 1 pars.append(p) # answers ls = ['A. ', 'B. ', 'C. ', 'D. '] for l, answer in zip(ls, answers): pars.append(Spacer(1, 0.03*inch)) p = Paragraph(l + answer.dapAn, answer_stype) pars.append(p) pars.append(Spacer(1, 0.03*inch)) pars.append(Spacer(1, 0.05*inch)) # ký sig_table_data = [[u'-------HẾT--------', u'']] sig_table_data.append([u'' ,u'TRƯỞNG KHOA']) sig_table_data.append([u'' ,u'(Ký, họ tên)']) sig_table = Table(sig_table_data, colWidths=[PAGE_WIDTH-300, 200]) sig_table.setStyle(TableStyle([('FONT', (0,0), (1,0), 'Times', 13), ('FONT', (0,1), (1,1), 'TimesBd', 13), ('FONT', (0,2), (1,2), 'TimesIt', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('SPAN',(0,0),(1,0)), ])) pars.append(sig_table) doc.build(pars, onFirstPage=myFirstPage, onLaterPages=myLaterPages) # Get the value of the BytesIO buffer and write it to the response. pdf = buf.getvalue() buf.close() return pdf
''' @author: xilh @since: 20200128 ''' from _io import BytesIO from demo.tools.tool import pline # 创建对象 f = BytesIO() f.write('hello'.encode(encoding='utf_8')) f.write(' '.encode(encoding='utf_8')) f.write('world'.encode(encoding='utf_8')) f.write(' '.encode(encoding='utf_8')) f.write('张三'.encode(encoding='utf_8')) # 获取值 ret = f.getvalue() print(ret) pline() f = BytesIO('张三是程序员'.encode('utf-8')) print(f.readline()) # 关闭 f.close()