def testStringWidth(self): "Test TTFont.stringWidth" font = TTFont("Vera", "Vera.ttf") self.assert_(font.stringWidth("test", 10) > 0) width = font.stringWidth(utf8(0x2260) * 2, 1000) expected = font.face.getCharWidth(0x2260) * 2 self.assertNear(width,expected)
def testStringWidth(self): "Test TTFont.stringWidth" font = TTFont("TestFont", "luxiserif.ttf") self.assert_(font.stringWidth("test", 10) > 0) width = font.stringWidth(utf8(0x2260) * 2, 1000) expected = font.face.getCharWidth(0x2260) * 2 self.assert_(abs(width - expected) < 0.01, "%g != %g" % (width, expected))
def testSplitStringSpaces(self): # In order for justification (word spacing) to work, the space # glyph must have a code 32, and no other character should have # that code in any subset, or word spacing will be applied to it. doc = PDFDocument() font = TTFont("Vera", "Vera.ttf") text = b"".join(utf8(i) for i in range(512, -1, -1)) chunks = font.splitString(text, doc) state = font.state[doc] self.assertEquals(state.assignments[32], 32) self.assertEquals(state.subsets[0][32], 32) self.assertEquals(state.subsets[1][32], 32)
def testSubsetInternalName(self): "Tests TTFont.getSubsetInternalName" doc = PDFDocument() font = TTFont("Vera", "Vera.ttf") # Actually generate some subsets text = b"".join(utf8(i) for i in range(513)) font.splitString(text, doc) self.assertRaises(IndexError, font.getSubsetInternalName, -1, doc) self.assertRaises(IndexError, font.getSubsetInternalName, 3, doc) self.assertEquals(font.getSubsetInternalName(0, doc), "/F1+0") self.assertEquals(font.getSubsetInternalName(1, doc), "/F1+1") self.assertEquals(font.getSubsetInternalName(2, doc), "/F1+2") self.assertEquals(doc.delayedFonts, [font])
def testSubsetInternalName(self): "Tests TTFont.getSubsetInternalName" doc = PDFDocument() font = TTFont("TestFont", "luxiserif.ttf") # Actually generate some subsets text = string.join(map(utf8, range(0, 513)), "") font.splitString(text, doc) self.assertRaises(IndexError, font.getSubsetInternalName, -1, doc) self.assertRaises(IndexError, font.getSubsetInternalName, 3, doc) self.assertEquals(font.getSubsetInternalName(0, doc), "/F1+0") self.assertEquals(font.getSubsetInternalName(1, doc), "/F1+1") self.assertEquals(font.getSubsetInternalName(2, doc), "/F1+2") self.assertEquals(doc.delayedFonts, [font])
def testSplitString(self): "Tests TTFont.splitString" doc = PDFDocument() font = TTFont("TestFont", "luxiserif.ttf") text = string.join(map(utf8, range(0, 512)), "") allchars = string.join(map(chr, range(0, 256)), "") chunks = [(0, allchars), (1, allchars)] self.assertEquals(font.splitString(text, doc), chunks) # Do it twice self.assertEquals(font.splitString(text, doc), chunks) text = string.join(map(utf8, range(511, -1, -1)), "") allchars = string.join(map(chr, range(255, -1, -1)), "") chunks = [(1, allchars), (0, allchars)] self.assertEquals(font.splitString(text, doc), chunks)
def testParallelConstruction(self): "Test that TTFont can be used for different documents at the same time" doc1 = PDFDocument() doc2 = PDFDocument() font = TTFont("TestFont", "luxiserif.ttf") self.assertEquals(font.splitString(u'hello ', doc1), [(0, 'hello ')]) self.assertEquals(font.splitString(u'hello ', doc2), [(0, 'hello ')]) self.assertEquals(font.splitString(u'\u0410\u0411'.encode('UTF-8'), doc1), [(0, '\x80\x81')]) self.assertEquals(font.splitString(u'\u0412'.encode('UTF-8'), doc2), [(0, '\x80')]) font.addObjects(doc1) self.assertEquals(font.splitString(u'\u0413'.encode('UTF-8'), doc2), [(0, '\x81')]) font.addObjects(doc2)
def testSplitString(self): "Tests TTFont.splitString" doc = PDFDocument() font = TTFont("Vera", "Vera.ttf") text = string.join(map(utf8, xrange(0, 511)), "") allchars = string.join(map(chr, xrange(0, 256)), "") nospace = allchars[:32] + allchars[33:] chunks = [(0, allchars), (1, nospace)] self.assertEquals(font.splitString(text, doc), chunks) # Do it twice self.assertEquals(font.splitString(text, doc), chunks) text = string.join(map(utf8, range(510, -1, -1)), "") allchars = string.join(map(chr, range(255, -1, -1)), "") nospace = allchars[:223] + allchars[224:] chunks = [(1, nospace), (0, allchars)] self.assertEquals(font.splitString(text, doc), chunks)
def testSplitString(self): "Tests TTFont.splitString" doc = PDFDocument() font = TTFont("Vera", "Vera.ttf") text = b"".join(utf8(i) for i in range(511)) allchars = b"".join(int2Byte(i) for i in range(256)) nospace = allchars[:32] + allchars[33:] chunks = [(0, allchars), (1, nospace)] self.assertEquals(font.splitString(text, doc), chunks) # Do it twice self.assertEquals(font.splitString(text, doc), chunks) text = b"".join(utf8(i) for i in range(510, -1, -1)) allchars = b"".join(int2Byte(i) for i in range(255, -1, -1)) nospace = allchars[:223] + allchars[224:] chunks = [(1, nospace), (0, allchars)] self.assertEquals(font.splitString(text, doc), chunks)
def testParallelConstruction(self): "Test that TTFont can be used for different documents at the same time" doc1 = PDFDocument() doc2 = PDFDocument() font = TTFont("TestFont", "luxiserif.ttf") self.assertEquals(font.splitString("ab", doc1), [(0, "\0\1")]) self.assertEquals(font.splitString("b", doc2), [(0, "\0")]) font.addObjects(doc1) self.assertEquals(font.splitString("c", doc2), [(0, "\1")]) font.addObjects(doc2)
def testParallelConstruction(self): "Test that TTFont can be used for different documents at the same time" ttfAsciiReadable = rl_config.ttfAsciiReadable try: rl_config.ttfAsciiReadable = 1 doc1 = PDFDocument() doc2 = PDFDocument() font = TTFont("Vera", "Vera.ttf") self.assertEquals(font.splitString('hello ', doc1), [(0, b'hello ')]) self.assertEquals(font.splitString('hello ', doc2), [(0, b'hello ')]) self.assertEquals(font.splitString(u'\u0410\u0411'.encode('UTF-8'), doc1), [(0, b'\x80\x81')]) self.assertEquals(font.splitString(u'\u0412'.encode('UTF-8'), doc2), [(0, b'\x80')]) font.addObjects(doc1) self.assertEquals(font.splitString(u'\u0413'.encode('UTF-8'), doc2), [(0, b'\x81')]) font.addObjects(doc2) finally: rl_config.ttfAsciiReadable = ttfAsciiReadable
def no_longer_testAddObjectsResets(self): "Test that TTFont.addObjects resets the font" # Actually generate some subsets doc = PDFDocument() font = TTFont("Vera", "Vera.ttf") font.splitString('a', doc) # create some subset doc = PDFDocument() font.addObjects(doc) self.assertEquals(font.frozen, 0) self.assertEquals(font.nextCode, 0) self.assertEquals(font.subsets, []) self.assertEquals(font.assignments, {}) font.splitString('ba', doc) # should work
def testAddObjects(self): "Test TTFont.addObjects" # Actually generate some subsets doc = PDFDocument() font = TTFont("TestFont", "luxiserif.ttf") font.splitString('a', doc) # create some subset internalName = font.getSubsetInternalName(0, doc)[1:] font.addObjects(doc) pdfFont = doc.idToObject[internalName] self.assertEquals(doc.idToObject['BasicFonts'].dict[internalName], pdfFont) self.assertEquals(pdfFont.Name, internalName) self.assertEquals(pdfFont.BaseFont, "AAAAAA+LuxiSerif") self.assertEquals(pdfFont.FirstChar, 0) self.assertEquals(pdfFont.LastChar, 127) self.assertEquals(len(pdfFont.Widths.sequence), 128) toUnicode = doc.idToObject[pdfFont.ToUnicode.name] self.assert_(toUnicode.content != "") fontDescriptor = doc.idToObject[pdfFont.FontDescriptor.name] self.assertEquals(fontDescriptor.dict['Type'], '/FontDescriptor')
def testAddObjects(self): "Test TTFont.addObjects" # Actually generate some subsets ttfAsciiReadable = rl_config.ttfAsciiReadable try: rl_config.ttfAsciiReadable = 1 doc = PDFDocument() font = TTFont("Vera", "Vera.ttf") font.splitString('a', doc) # create some subset internalName = font.getSubsetInternalName(0, doc)[1:] font.addObjects(doc) pdfFont = doc.idToObject[internalName] self.assertEquals(doc.idToObject['BasicFonts'].dict[internalName], pdfFont) self.assertEquals(pdfFont.Name, internalName) self.assertEquals(pdfFont.BaseFont, "AAAAAA+BitstreamVeraSans-Roman") self.assertEquals(pdfFont.FirstChar, 0) self.assertEquals(pdfFont.LastChar, 127) self.assertEquals(len(pdfFont.Widths.sequence), 128) toUnicode = doc.idToObject[pdfFont.ToUnicode.name] self.assert_(toUnicode.content != "") fontDescriptor = doc.idToObject[pdfFont.FontDescriptor.name] self.assertEquals(fontDescriptor.dict['Type'], '/FontDescriptor') finally: rl_config.ttfAsciiReadable = ttfAsciiReadable
def testAddObjectsEmpty(self): "TTFont.addObjects should not fail when no characters were used" font = TTFont("Vera", "Vera.ttf") doc = PDFDocument() font.addObjects(doc)
import datetime import os import textwrap from PyPDF2 import PdfFileWriter, PdfFileReader import io from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from slugify import slugify pdfmetrics.registerFont( TTFont('Balthazar', os.path.join(settings.SCHEDE_DIR, 'Balthazar.ttf'))) from reportlab.rl_config import defaultPageSize PAGE_HEIGHT = defaultPageSize[1] PAGE_WIDTH = defaultPageSize[0] def print_scheda(modeladmin, request, queryset): response = HttpResponse(content_type='application/pdf') if len(queryset) == 1: title = slugify(queryset[0].name) else: title = "%s-%s" % ('SchedeOiR', datetime.date.today())
# encoding = utf-8 import PIL from reportlab.lib.pagesizes import letter from reportlab.lib.utils import ImageReader from reportlab.pdfgen import canvas from DataSource.Code2Name import code2name from Function.SeaSelect.Sub.reportlab_sub import print_k_to_pdf, add_front, add_tail_page from Function.SeaSelect.gen_pic import stk_code from Global_Value.file_dir import sea_select_pic_dir from SDK.MyTimeOPT import get_current_date_str from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics pdfmetrics.registerFont(TTFont('song', 'SURSONG.TTF')) pdfmetrics.registerFont(TTFont('hei', 'SIMHEI.TTF')) from reportlab.lib import fonts fonts.addMapping('song', 0, 0, 'song') fonts.addMapping('song', 0, 1, 'song') fonts.addMapping('song', 1, 0, 'hei') fonts.addMapping('song', 1, 1, 'hei') date = '2019-12-28' if __name__ == '__main__': c = canvas.Canvas(U"魔灯海选" + get_current_date_str() + ".pdf", pagesize=letter) c = add_front(c, '魔灯每日股票海选结果' + get_current_date_str(), '本文档由免费开源的量化投资软件“魔灯”自动生成 末尾公众号内有软件介绍', pagesize=letter) c = print_k_to_pdf(c, stk_code, date) c = add_tail_page(c) c.save()
'''<para> {date} - <a href="{url}">{url}</a> - wger Workout Manager {version} </para>'''.format(date=date, url=url, version=get_version()), styleSheet["Normal"]) return p # register new truetype fonts for reportlab pdfmetrics.registerFont( TTFont( 'OpenSans', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-Light.ttf'))) pdfmetrics.registerFont( TTFont( 'OpenSans-Bold', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-Bold.ttf'))) pdfmetrics.registerFont( TTFont( 'OpenSans-Regular', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-Regular.ttf'))) styleSheet = StyleSheet1() styleSheet.add( ParagraphStyle( name='Normal',
# # from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.units import inch, mm, cm #pdfmetrics.registerFont(UnicodeCIDFont('HeiseiMin-W3')) GEN_SHIN_GOTHIC = "./fonts/GenShinGothic-P-Light.ttf" c = canvas.Canvas('card.pdf', pagesize=(100 * mm, 148 * mm)) pdfmetrics.registerFont(TTFont('GenShinGothic', GEN_SHIN_GOTHIC)) c.setFont('GenShinGothic', 20) c.drawString(45 * mm, 125 * mm, '9999999') c.setFont('GenShinGothic', 12) c.drawString(30 * mm, 100 * mm, '東京都目黒区洗足1-29-2') c.drawString(30 * mm, 90 * mm, '高野由紀夫') c.showPage() c.save()
def form_02(request_data): """ Форма 025/у - титульный лист амбулаторной карты Приказ Минздрава России от 15.12.2014 N 834н (ред. от 09.01.2018) http://docs.cntd.ru/document/436733768) Об утверждении критериев оценки качества медицинской помощи ПРИКАЗ Минздрава России от 10 мая 2017 года N 203н https://minjust.consultant.ru/documents/35361 """ ind_card = Card.objects.get(pk=request_data["card_pk"]) patient_data = ind_card.get_data_individual() hospital: Hospitals = request_data["hospital"] hospital_name = hospital.safe_short_title hospital_address = hospital.safe_address hospital_kod_ogrn = hospital.safe_ogrn if sys.platform == 'win32': locale.setlocale(locale.LC_ALL, 'rus_rus') else: locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') pdfmetrics.registerFont( TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=25 * mm, rightMargin=5 * mm, topMargin=6 * mm, bottomMargin=6 * mm, allowSplitting=1, title="Форма {}".format("025/у")) width, height = portrait(A4) styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 10 style.leading = 12 style.spaceAfter = 0.5 * mm styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" styleCenter = deepcopy(style) styleCenter.alignment = TA_CENTER styleCenter.fontSize = 12 styleCenter.leading = 15 styleCenter.spaceAfter = 1 * mm styleCenterBold = deepcopy(styleBold) styleCenterBold.alignment = TA_CENTER styleCenterBold.fontSize = 12 styleCenterBold.leading = 15 styleCenterBold.face = 'PTAstraSerifBold' styleCenterBold.borderColor = black styleJustified = deepcopy(style) styleJustified.alignment = TA_JUSTIFY styleJustified.spaceAfter = 4.5 * mm styleJustified.fontSize = 12 styleJustified.leading = 4.5 * mm objs = [] styleT = deepcopy(style) styleT.alignment = TA_LEFT styleT.fontSize = 10 styleT.leading = 4.5 * mm styleT.face = 'PTAstraSerifReg' print_district = '' if SettingManager.get("district", default='True', default_type='b'): if ind_card.district is not None: print_district = 'Уч: {}'.format(ind_card.district.title) opinion = [ [ Paragraph( '<font size=11>{}<br/>Адрес: {}<br/>ОГРН: {} <br/><u>{}</u> </font>' .format(hospital_name, hospital_address, hospital_kod_ogrn, print_district), styleT), Paragraph( '<font size=9 >Код формы по ОКУД:<br/>Код организации по ОКПО: 31348613<br/>' 'Медицинская документация<br/>Учетная форма № 025/у</font>', styleT), ], ] tbl = Table(opinion, 2 * [90 * mm]) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.white), ('LEFTPADDING', (1, 0), (-1, -1), 80), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) space_symbol = ' ' if patient_data['age'] < SettingManager.get( "child_age_before", default='15', default_type='i'): patient_data['serial'] = patient_data['bc_serial'] patient_data['num'] = patient_data['bc_num'] else: patient_data['serial'] = patient_data['passport_serial'] patient_data['num'] = patient_data['passport_num'] p_phone = '' if patient_data['phone']: p_phone = 'тел. ' + ", ".join(patient_data['phone']) card_num_obj = patient_data['card_num'].split(' ') p_card_num = card_num_obj[0] if len(card_num_obj) == 2: p_card_type = '(' + str(card_num_obj[1]) + ')' else: p_card_type = '' content_title = [ Indenter(left=0 * mm), Spacer(1, 1 * mm), Paragraph( 'МЕДИЦИНСКАЯ КАРТА ПАЦИЕНТА, <br/> ПОЛУЧАЮЩЕГО МЕДИЦИНСКУЮ ПОМОЩЬ В АМБУЛАТОРНЫХ УСЛОВИЯХ', styleCenter), Paragraph( '{}<font size=14>№</font><font fontname="PTAstraSerifBold" size=17> <u>{}</u></font><font size=14> {}</font>' .format(3 * space_symbol, p_card_num, p_card_type), styleCenter), Spacer(1, 2 * mm), Paragraph( '1.Дата заполнения медицинской карты: {}'.format( pytils.dt.ru_strftime(u"%d %B %Y", inflected=True, date=datetime.datetime.now())), style), Paragraph( "2. Фамилия, имя, отчество: <font size=11.7 fontname ='PTAstraSerifBold'> {} </font> " .format(patient_data['fio']), style), Paragraph( '3. Пол: {} {} 4. Дата рождения: {}'.format( patient_data['sex'], 3 * space_symbol, patient_data['born']), style), Paragraph( '5. Место регистрации: {}'.format(patient_data['main_address']), style), Paragraph('{}'.format(p_phone), style), Paragraph('6. Местность: городская — 1, сельская — 2', style), Paragraph( '7. Полис ОМС: серия {} №: {} {}' '8. СНИЛС: {}'.format(patient_data['oms']['polis_serial'], patient_data['oms']['polis_num'], 13 * space_symbol, patient_data['snils']), style), Paragraph( '9. Наименование страховой медицинской организации: {}'.format( patient_data['oms']['polis_issued']), style), Paragraph( '10. Код категории льготы: {} {} 11. Документ: {} серия: {} №: {}' .format(8 * space_symbol, 25 * space_symbol, patient_data['type_doc'], patient_data['serial'], patient_data['num']), style, ), ] objs.extend(content_title) if SettingManager.get("dispensary", default='True', default_type='b'): objs.append( Paragraph( '12. Заболевания, по поводу которых осуществляется диспансерное наблюдение:', style)) objs.append(Spacer(1, 2 * mm)) styleTCenter = deepcopy(styleT) styleTCenter.alignment = TA_CENTER styleTCenter.leading = 3.5 * mm opinion = [ [ Paragraph( '<font size=9>Дата начала диспансерного наблюдения </font>', styleTCenter), Paragraph( '<font size=9 >Дата прекращения диспансерного наблюдения</font>', styleTCenter), Paragraph('<font size=9 >Диагноз</font>', styleTCenter), Paragraph('<font size=9 >Код по МКБ-10</font>', styleTCenter), Paragraph('<font size=9 >Врач</font>', styleTCenter), ], ] for i in range(0, 5): para = ['', '', '', '', ''] opinion.append(para) row_height = [] for i in opinion: row_height.append(6 * mm) row_height[0] = None tbl = Table(opinion, colWidths=(27 * mm, 30 * mm, 75 * mm, 20 * mm, 27 * mm), rowHeights=row_height) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'), ])) objs.append(tbl) def first_pages(canvas, document): canvas.saveState() canvas.restoreState() def later_pages(canvas, document): canvas.saveState() canvas.restoreState() doc.build(objs, onFirstPage=first_pages, onLaterPages=later_pages) pdf = buffer.getvalue() buffer.close() return pdf
def slotcarivade(self): firma = "%" + self.lineEdit.text() + "%" print("firma ", firma) myddb1 = Myddb() self.kontrol = 1 print("cari vade listesi") self.tableWidget.clearContents() self.tableWidget.setColumnWidth(0, 60) self.tableWidget.setColumnWidth(1, 400) self.tableWidget.setColumnWidth(2, 100) self.tableWidget.setColumnWidth(3, 100) self.tableWidget.setColumnWidth(4, 25) deger1 = self.dateEdit.date().toPyDate() deger2 = self.dateEdit_2.date().toPyDate() tar1 = deger1.strftime('%d%m%Y') tar2 = deger2.strftime('%d%m%Y') self.wb = xlwt.Workbook(encoding="utf-8") self.dest_filename = "EKSTRE" + tar1 + tar2 + ".xls" date_format = xlwt.XFStyle() date_format.num_format_str = u'#,##0.00₺' date_xf = xlwt.easyxf(num_format_str='DD-MM-YYYY') self.ws1 = self.wb.add_sheet("ekstre") self.style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;') c = canvas.Canvas("EKSTRE" + tar1 + tar2 + ".pdf") pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf')) c.setFont("Verdana", 8) item = "KOD FİRMA ADI " \ "VADESİ GELEN TOPLAM " c.drawString(10, 810, item) tar1 = deger1.strftime('%Y-%m-%d') tar2 = deger2.strftime('%Y-%m-%d') myddb1.cur.execute("drop table if exists table3 ") myddb1.cur.execute("drop table if exists table4 ") myddb1.cur.execute( """CREATE TABLE table3 AS (select `cariid` AS `cariid`,sum(`tutar`) AS `tutar` from cari_har where ( (tarih > '2016-12-31')) and (fistipi=10 or fistipi=11) group by cariid )""") myddb1.cur.execute( """CREATE TABLE table4 AS (select cariid,sum(tutar) as tutar from cari_har where vade < %s and (tarih > '2016-12-31') group by cariid )""", (tar2,)) sql = """select a.cariid,a.cariad , ifnull( b.tutar,0) as giriş ,ifnull(c.tutar,0) as çıkış, (ifnull( b.tutar,0)-ifnull(c.tutar,0)) as fark from cari a left join table3 b on a.cariid=b.cariid left join table4 c on a.cariid=c.cariid where b.tutar>0 and a.cariad like %s order by çıkış desc """ bul2 = myddb1.cur.execute(sql, (firma,)) print(bul2, tar1, tar2) bul = myddb1.cur.fetchall() i = bul2 j = 5 self.tableWidget.setRowCount(i) aa = 0 bb = 0 dep = 0 toplam = 0.0 toplam1 = 0.0 toplam2 = 0.0000 for row1 in bul: item = str(row1[0]) self.ws1.write(aa, 0, item) self.tableWidget.setItem(aa, 0, QtWidgets.QTableWidgetItem(item)) c.drawString(45, 800 - (15 * (bb + 1)), item) item = (row1[1]) self.ws1.write(aa, 1, item) c.drawString(80, 800 - (15 * (bb + 1)), item) self.tableWidget.setItem(aa, 1, QtWidgets.QTableWidgetItem(item)) if row1[3] > 0: item = str(row1[3]) self.ws1.write(aa, 2, item) self.tableWidget.setItem(aa, 2, QtWidgets.QTableWidgetItem(item)) c.drawRightString(400, 800 - (15 * (bb + 1)), item) item = str(row1[2]) self.ws1.write(aa, 3, float(row1[4])) c.drawRightString(470, 800 - (15 * (bb + 1)), item) toplam = toplam + float(row1[3]) toplam2 = Decimal(toplam2) + (row1[2]) self.tableWidget.setItem(aa, 3, QtWidgets.QTableWidgetItem(item)) if row1[3] <= 0: item = "0" self.ws1.write(aa, 2, item) self.tableWidget.setItem(aa, 2, QtWidgets.QTableWidgetItem(item)) c.drawRightString(400, 800 - (15 * (bb + 1)), item) item = str(row1[2]) self.ws1.write(aa, 3, float(row1[4])) c.drawRightString(470, 800 - (15 * (bb + 1)), item) toplam2 = Decimal(toplam2) + (row1[2]) self.tableWidget.setItem(aa, 3, QtWidgets.QTableWidgetItem(item)) aa = aa + 1 bb = bb + 1 if (15 * (bb + 1)) >= 760: c.setFont("Verdana", 10) c.drawString(210, 800 - (15 * (bb + 1)), str(toplam)) c.drawString(270, 800 - (15 * (bb + 1)), str(toplam1)) c.drawString(350, 800 - (15 * (bb + 1)), str(toplam2)) c.showPage() c.setFont("Verdana", 8) bb = 0 self.tableWidget.setRowCount(aa + 2) font = QtGui.QFont("Courier New", 11) self.tableWidget.setItem(aa + 1, 2, QtWidgets.QTableWidgetItem("{:10.2f}".format((toplam)))) self.tableWidget.item(aa + 1, 2).setBackground(QtGui.QColor(255, 128, 128)) self.tableWidget.item(aa + 1, 2).setFont(font) c.setFont("Verdana", 10) self.ws1.write(aa + 1, 3, toplam) self.ws1.write(aa + 1, 4, toplam1) self.ws1.write(aa + 1, 5, toplam2) c.drawString(350, 800 - (15 * (bb + 1)), "{:10.2f}".format((toplam))) c.drawString(420, 800 - (15 * (bb + 1)), "{:10.2f}".format((toplam2))) # c.drawString(430, 800 - (15 * (bb + 1)), str(toplam2)) # todo genel toplam yazılacak c.setFont("Courier", 60) # This next setting with make the text of our # watermark gray, nice touch for a watermark. c.setFillGray(0.3, 0.3) # Set up our watermark document. Our watermark # will be rotated 45 degrees from the direction # of our underlying document. c.saveState() c.translate(500, 100) c.rotate(45) c.drawCentredString(0, 0, "BISHOP NEN ©") c.drawCentredString(0, 300, "BISHOP NEN ©") c.drawCentredString(0, 600, "BISHOP NEN ©") c.restoreState() c.save() self.wb.save(self.dest_filename) self.kontrol = 0
import PyPDF2 from io import StringIO, BytesIO from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase.pdfmetrics import stringWidth pdfmetrics.registerFont(TTFont('MetaBookCapsLFC', 'MetaBookCapsLFC.ttf')) def TupleSum(x, y): z = [] for i in range(len(x)): z.append(x[i] + y[i]) return tuple(z) class PdfString(): def __init__(self, text, begin_point): self.begin_point = begin_point self.text = text class Text(): def __init__(self, font_size, line_spacing, list_size): self.strings = [] self.font_size = font_size self.line_spacing = line_spacing self.list_size = list_size def add_string(self, text):
def imprimir_Ticket(self): pdfmetrics.registerFont( TTFont('Liberation-Sans', 'LiberationSans-Regular.ttf')) pdfmetrics.registerFont( TTFont('LiberationSans-I', 'LiberationSans-Italic.ttf')) pdfmetrics.registerFont( TTFont('LiberationSans-BI', 'LiberationSans-BoldItalic.ttf')) pdfmetrics.registerFont( TTFont('LiberationSans-Bold', 'LiberationSans-Bold.ttf')) if not self.busco: if self.validacion_ticket_alumno(): self.id_atei = self.usuario self.estado = "Alta de Ticket" self.today = date.today() self.fecha = (self.today.strftime("%d"), self.today.strftime("%m"), self.today.strftime("%Y")) self.datos = (self.uid.Edit_CUIT.text(), self.uid.Edit_AyN.text(), self.uid.Edit_Dom.text(), self.uid.Edit_Tel.text(), self.uid.Edit_Mail.text(), self.uid.Edit_N_S.text(), self.uid.Edit_Marca.text(), self.uid.Edit_Modelo.text()) self.datos_ticket = (self.uid.Edit_Ticket.text(), self.uid.Edit_N_S.text(), self.id_atei, self.uid.comboBox.currentText(), self.estado, (self.fecha[0] + '/' + self.fecha[1] + '/' + self.fecha[2]), self.uid.Fecha_Conig.text(), self.uid.Edit_Comentarios.text()) self.cursor.execute( "INSERT INTO ALU_MAQ (CUIL,A_N,DOMICILIO,TEL,MAIL,N_S,MARCA,MODELO) VALUES (?,?,?,?,?,?,?,?)", self.datos) self.con.commit() self.cursor.execute( "INSERT INTO ST (N_TICKET,N_S_FK,ID_ATEI_FK,MOTIVO,ESTADO,FECHA_CARGA,FECHA_CONIG,COMENTARIOS) VALUES (?,?,?,?,?,?,?,?)", self.datos_ticket) self.con.commit() self.cursor.execute('SELECT CUE,CIUDAD,COLEGIO FROM DIRECTIVO') datos = self.cursor.fetchone() self.datos_colegio = { 'colegio': datos[2], 'cue': datos[0], 'ciudad': datos[1] } c = canvas.Canvas("Tickets\Ticket " + self.uid.Edit_Ticket.text() + " - " + self.uid.Edit_AyN.text() + ".pdf", pagesize=legal) c.alignment = "TA_JUSTIFY" width, height = legal Modulos.ST.Escribir.escribir_Texto( c, self.uid.Edit_Ticket.text(), self.uid.Edit_CUIT.text(), self.uid.Edit_AyN.text(), self.uid.Edit_Dom.text(), self.uid.Edit_Tel.text(), self.uid.Edit_N_S.text(), self.uid.Edit_Marca.text(), self.uid.Edit_Modelo.text(), self.uid.Fecha_Conig.text(), self.uid.comboBox.currentText(), self.uid.Edit_Comentarios.text(), self.uid.Edit_Mail.text(), self.datos_colegio) Modulos.ST.Cargar_Movimientos.cargar_Movimiento( self.uid.Edit_Ticket.text(), self.usuario, 'Alta de Ticket ' + self.uid.Edit_Ticket.text()) c.save() self.close() QtGui.QMessageBox.about( self, "Registro guardado", "Registro Guardado satisfactoriamente") else: if self.validacion_alu_edit(): self.id_atei = self.usuario self.cursor.execute("SELECT * FROM ST WHERE N_S_FK = '" + self.uid.Edit_N_S.text() + "' AND ESTADO != 'Caso Cerrado'") self.estado = "Alta de Ticket" self.today = date.today() self.fecha = (self.today.strftime("%d"), self.today.strftime("%m"), self.today.strftime("%Y")) self.datos_ticket = (self.uid.Edit_Ticket.text(), self.uid.Edit_N_S.text(), self.id_atei, self.uid.comboBox.currentText(), self.estado, (self.fecha[0] + '/' + self.fecha[1] + '/' + self.fecha[2]), self.uid.Fecha_Conig.text(), self.uid.Edit_Comentarios.text()) if self.editar: self.cursor.execute( 'UPDATE ALU_MAQ SET CUIL = "' + str(self.uid.Edit_CUIT.text()) + '", A_N = "' + str(self.uid.Edit_AyN.text()) + '", DOMICILIO = "' + str(self.uid.Edit_Dom.text()) + '", TEL = "' + str(self.uid.Edit_Tel.text()) + '", MAIL = "' + str(self.uid.Edit_Mail.text()) + '", N_S = "' + str(self.uid.Edit_N_S.text()) + '",MARCA = "' + str(self.uid.Edit_Marca.text()) + '",MODELO = "' + str(self.uid.Edit_Modelo.text()) + '" WHERE CUIL = ' + str(self.cuil_viejo) + ' ') self.con.commit() self.cursor.execute( "INSERT INTO ST (N_TICKET,N_S_FK,ID_ATEI_FK,MOTIVO,ESTADO,FECHA_CARGA,FECHA_CONIG,COMENTARIOS) VALUES (?,?,?,?,?,?,?,?)", self.datos_ticket) self.con.commit() self.cursor.execute('SELECT CUE,CIUDAD,COLEGIO FROM DIRECTIVO') datos = self.cursor.fetchone() self.datos_colegio = { 'colegio': datos[2], 'cue': datos[0], 'ciudad': datos[1] } c = canvas.Canvas("Tickets\Ticket " + self.uid.Edit_Ticket.text() + " - " + self.uid.Edit_AyN.text() + ".pdf", pagesize=legal) c.alignment = "TA_JUSTIFY" width, height = legal Modulos.ST.Escribir.escribir_Texto( c, self.uid.Edit_Ticket.text(), self.uid.Edit_CUIT.text(), self.uid.Edit_AyN.text(), self.uid.Edit_Dom.text(), self.uid.Edit_Tel.text(), self.uid.Edit_N_S.text(), self.uid.Edit_Marca.text(), self.uid.Edit_Modelo.text(), self.uid.Fecha_Conig.text(), self.uid.comboBox.currentText(), self.uid.Edit_Comentarios.text(), self.uid.Edit_Mail.text(), self.datos_colegio) Modulos.ST.Cargar_Movimientos.cargar_Movimiento( self.uid.Edit_Ticket.text(), self.usuario, 'Alta de Ticket ' + self.uid.Edit_Ticket.text()) c.save() self.close() QtGui.QMessageBox.about( self, "Registro guardado", "Registro Guardado satisfactoriamente")
def loadFont(self, names, src, encoding="WinAnsiEncoding", bold=0, italic=0): # XXX Just works for local filenames! if names and src: # and src.local: file = src src = file.uri log.debug("Load font %r", src) if type(names) is types.ListType: fontAlias = names else: fontAlias = [x.lower().strip() for x in names.split(",") if x] # XXX Problems with unicode here fontAlias = [str(x) for x in fontAlias] fontName = fontAlias[0] parts = src.split(".") baseName, suffix = ".".join(parts[: - 1]), parts[ - 1] suffix = suffix.lower() if suffix in ["ttc", "ttf"]: # determine full font name according to weight and style fullFontName = "%s_%d%d" % (fontName, bold, italic) # check if font has already been registered if fullFontName in self.fontList: log.warn(self.warning("Repeated font embed for %s, skip new embed ", fullFontName)) else: # Register TTF font and special name filename = file.getNamedFile() pdfmetrics.registerFont(TTFont(fullFontName, filename)) # Add or replace missing styles for bold in (0, 1): for italic in (0, 1): if ("%s_%d%d" % (fontName, bold, italic)) not in self.fontList: addMapping(fontName, bold, italic, fullFontName) # Register "normal" name and the place holder for style self.registerFont(fontName, fontAlias + [fullFontName]) elif suffix in ("afm", "pfb"): if suffix == "afm": afm = file.getNamedFile() tfile = pisaFileObject(baseName + ".pfb") pfb = tfile.getNamedFile() else: pfb = file.getNamedFile() tfile = pisaFileObject(baseName + ".afm") afm = tfile.getNamedFile() #afm = baseName + ".afm" #pfb = baseName + ".pfb" # determine full font name according to weight and style fullFontName = "%s_%d%d" % (fontName, bold, italic) #fontNameOriginal = "" #for line in open(afm).readlines()[:-1]: # if line[:16] == 'StartCharMetrics': # self.error("Font name not found") # if line[:8] == 'FontName': # fontNameOriginal = line[9:].strip() # break # check if font has already been registered if fullFontName in self.fontList: log.warn(self.warning("Repeated font embed for %s, skip new embed", fontName)) else: # Include font face = pdfmetrics.EmbeddedType1Face(afm, pfb) fontNameOriginal = face.name pdfmetrics.registerTypeFace(face) # print fontName, fontNameOriginal, fullFontName justFont = pdfmetrics.Font(fullFontName, fontNameOriginal, encoding) pdfmetrics.registerFont(justFont) # Add or replace missing styles for bold in (0, 1): for italic in (0, 1): if ("%s_%d%d" % (fontName, bold, italic)) not in self.fontList: addMapping(fontName, bold, italic, fontNameOriginal) # Register "normal" name and the place holder for style self.registerFont(fontName, fontAlias + [fullFontName, fontNameOriginal]) #import pprint #pprint.pprint(self.fontList) else: log.warning(self.warning("wrong attributes for <pdf:font>"))
def imprimir_Ticket_Parque(self): if not self.busco_parque: if self.validacion_ticket_parque(): pdfmetrics.registerFont( TTFont('Liberation-Sans', 'LiberationSans-Regular.ttf')) pdfmetrics.registerFont( TTFont('LiberationSans-I', 'LiberationSans-Italic.ttf')) pdfmetrics.registerFont( TTFont('LiberationSans-BI', 'LiberationSans-BoldItalic.ttf')) pdfmetrics.registerFont( TTFont('LiberationSans-Bold', 'LiberationSans-Bold.ttf')) self.id_atei = self.usuario self.estado = "Alta de Ticket" self.today = date.today() self.fecha = (self.today.strftime("%d"), self.today.strftime("%m"), self.today.strftime("%Y")) if (not self.uid.Edit_Ticket_2.text().isdigit()): QtGui.QMessageBox.about(self, "Dato texto en campo Ticket", "Numero de Ticket Mal Ingresado") self.uid.Edit_Ticket_2.setFocus() return self.datos = (self.uid.Edit_N_S_2.text(), self.uid.Edit_Marca_2.text(), self.uid.Edit_Modelo_2.text(), self.uid.cmb_condicion.currentText(), 1) self.datos_ticket = (self.uid.Edit_Ticket_2.text(), self.uid.Edit_N_S_2.text(), self.id_atei, self.uid.comboBox_2.currentText(), self.estado, (self.fecha[0] + '/' + self.fecha[1] + '/' + self.fecha[2]), self.uid.Fecha_Conig_2.text(), self.uid.Edit_Comentarios_2.text()) self.cursor.execute( "INSERT INTO PARQUE_ESCOLAR (N_S,MARCA,MODELO,CONDICION,ID_DIRECTIVO_FK) VALUES (?,?,?,?,?)", self.datos) self.con.commit() self.cursor.execute( "INSERT INTO ST (N_TICKET,N_S_FK,ID_ATEI_FK,MOTIVO,ESTADO,FECHA_CARGA,FECHA_CONIG,COMENTARIOS) VALUES (?,?,?,?,?,?,?,?)", self.datos_ticket) self.con.commit() self.cursor.execute('SELECT CUE,CIUDAD,COLEGIO FROM DIRECTIVO') datos = self.cursor.fetchone() self.datos_colegio = { 'colegio': datos[2], 'cue': datos[0], 'ciudad': datos[1] } c = canvas.Canvas("Tickets\Ticket " + self.uid.Edit_Ticket_2.text() + " - " + self.uid.Edit_AyN_2.text() + ".pdf", pagesize=legal) c.alignment = "TA_JUSTIFY" width, height = legal Modulos.ST.Escribir_Parque.escribir_Texto( c, self.uid.Edit_Ticket_2.text(), self.uid.Edit_CUIT_2.text(), self.uid.Edit_AyN_2.text(), self.uid.Edit_Dom_2.text(), self.uid.Edit_Tel_2.text(), self.uid.Edit_N_S_2.text(), self.uid.Edit_Marca_2.text(), self.uid.Edit_Modelo_2.text(), self.uid.Fecha_Conig_2.text(), self.uid.comboBox_2.currentText(), self.uid.Edit_Comentarios_2.text(), self.uid.Edit_Mail_2.text(), self.datos_colegio) Modulos.ST.Cargar_Movimientos.cargar_Movimiento( self.uid.Edit_Ticket_2.text(), self.usuario, 'Alta de Ticket ' + self.uid.Edit_Ticket_2.text()) c.save() self.close() QtGui.QMessageBox.about( self, "Registro guardado", "Registro Guardado satisfactoriamente") else: if self.validacion_parque_edit(): pdfmetrics.registerFont( TTFont('Liberation-Sans', 'LiberationSans-Regular.ttf')) pdfmetrics.registerFont( TTFont('LiberationSans-I', 'LiberationSans-Italic.ttf')) pdfmetrics.registerFont( TTFont('LiberationSans-BI', 'LiberationSans-BoldItalic.ttf')) pdfmetrics.registerFont( TTFont('LiberationSans-Bold', 'LiberationSans-Bold.ttf')) self.id_atei = self.usuario self.cursor.execute("SELECT * FROM ST WHERE N_S_FK = '" + self.uid.Edit_N_S_2.text() + "' AND ESTADO != 'Caso Cerrado'") self.con.commit() self.estado = "Alta de Ticket" self.today = date.today() self.fecha = (self.today.strftime("%d"), self.today.strftime("%m"), self.today.strftime("%Y")) self.datos_ticket = (self.uid.Edit_Ticket_2.text(), self.uid.Edit_N_S_2.text(), self.id_atei, self.uid.comboBox_2.currentText(), self.estado, (self.fecha[0] + '/' + self.fecha[1] + '/' + self.fecha[2]), self.uid.Fecha_Conig_2.text(), self.uid.Edit_Comentarios_2.text()) if self.editar: self.cursor.execute( 'UPDATE PARQUE_ESCOLAR SET N_S = "' + str(self.uid.Edit_N_S_2.text()) + '", MARCA = "' + str(self.uid.Edit_Marca_2.text()) + '", MODELO = "' + str(self.uid.Edit_Modelo_2.text()) + '", CONDICION = "' + str(self.uid.cmb_condicion.currentText()) + '" WHERE N_S = ' + str(self.ns_viejo) + ' ') self.con.commit() self.cursor.execute( "INSERT INTO ST (N_TICKET,N_S_FK,ID_ATEI_FK,MOTIVO,ESTADO,FECHA_CARGA,FECHA_CONIG,COMENTARIOS) VALUES (?,?,?,?,?,?,?,?)", self.datos_ticket) self.con.commit() self.cursor.execute('SELECT CUE,CIUDAD,COLEGIO FROM DIRECTIVO') datos = self.cursor.fetchone() """ self.datos_colegio = { 'colegio' : datos[2], 'cue' : datos[0], 'ciudad' : datos[1] } """ self.datos_colegio = {} c = canvas.Canvas("Tickets\Ticket " + self.uid.Edit_Ticket_2.text() + " - " + self.uid.Edit_AyN_2.text() + ".pdf", pagesize=legal) c.alignment = "TA_JUSTIFY" width, height = legal Modulos.ST.Escribir_Parque.escribir_Texto( c, self.uid.Edit_Ticket_2.text(), self.uid.Edit_CUIT_2.text(), self.uid.Edit_AyN_2.text(), self.uid.Edit_Dom_2.text(), self.uid.Edit_Tel_2.text(), self.uid.Edit_N_S_2.text(), self.uid.Edit_Marca_2.text(), self.uid.Edit_Modelo_2.text(), self.uid.Fecha_Conig_2.text(), self.uid.comboBox_2.currentText(), self.uid.Edit_Comentarios_2.text(), self.uid.Edit_Mail_2.text(), self.datos_colegio) Modulos.ST.Cargar_Movimientos.cargar_Movimiento( self.uid.Edit_Ticket_2.text(), self.usuario, 'Alta de Ticket ' + self.uid.Edit_Ticket_2.text()) c.save() self.close() QtGui.QMessageBox.about( self, "Registro guardado", "Registro Guardado satisfactoriamente")
def sloturunmaliyet(self): myddb1 = Myddb() print("urunmaliyet") self.tableWidget.clearContents() deger1 = self.dateEdit.date().toPyDate() self.deger1 = deger1.replace(day=1) self.deger2 = self.last_day_of_month(deger1) tar1 = self.deger1.strftime('%d%m%Y') tar2 = self.deger2.strftime('%d%m%Y') c = canvas.Canvas("./tempnenra/GELİRTABLO" + tar1 + tar2 + ".pdf") pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf')) c.setFont("Verdana", 16) item = " BISHOP RESTAURANT AYRINTILI GELİR TABLOSU " + self.deger1.strftime( '%B %Y') c.drawString(10, 810, item) c.setFont("Verdana", 10) tar1 = self.deger1.strftime('%Y-%m-%d') tar2 = self.deger2.strftime('%Y-%m-%d') sql = """SELECT b.muhad ,a.aciklama,a.miktar1 FROM bishop.genelrapor a JOIN bishop.muhkodt b ON b.muhkod=a.aciklama where tarih=%s """ bul2 = myddb1.cur.execute(sql, (tar2, )) print(bul2, tar1, tar2) bul = myddb1.cur.fetchall() i = bul2 self.tableWidget.setRowCount(i) aa = 0 bb = 0 toplam = 0.0 toplam1 = 0.0 toplam2 = 0.0 for row1 in bul: item = (row1[0]) self.tableWidget.setItem(aa, 0, QtWidgets.QTableWidgetItem(item)) c.drawString(45, 800 - (15 * (bb + 1)), item) item = row1[1] c.drawString(180, 800 - (15 * (bb + 1)), item) self.tableWidget.setItem(aa, 1, QtWidgets.QTableWidgetItem(item)) if len(item) < 4: c.setFont("Verdana", 12) item = str(row1[2]) if item == 'None': item = "0" toplam = toplam + float(item) self.tableWidget.setItem(aa, 2, QtWidgets.QTableWidgetItem(item)) c.drawRightString(330, 800 - (15 * (bb + 1)), item) c.setFont("Verdana", 10) item = " ." c.drawString(400, 800 - (15 * (bb + 1)), item) toplam1 = toplam1 self.tableWidget.setItem(aa, 3, QtWidgets.QTableWidgetItem(item)) aa = aa + 1 bb = bb + 1 if (15 * (bb + 1)) >= 760: c.setFont("Verdana", 11) c.drawString(210, 800 - (15 * (bb + 1)), str(toplam)) c.drawString(270, 800 - (15 * (bb + 1)), str(toplam1)) c.drawString(350, 800 - (15 * (bb + 1)), str(toplam2)) c.showPage() c.setFont("Verdana", 8) bb = 0 c.setFont("Verdana", 12) c.drawString(150, 800 - (15 * (bb + 2)), "Kar Zarar") try: c.drawRightString(330, 800 - (15 * (bb + 2)), str((bul[3][2]) - (bul[20][2]))) except: pass # c.drawString(450, 800 - (15 * (bb + 1)), "% " + str(int(toplam2 / toplam1 * 100))) c.setFont("Verdana", 6) c.drawRightString( 570, 20, datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")) c.save()
def satisrapor(self): print("satisrapor") myddb1 = Myddb() # self.tableWidget.clearContents() deger1 = self.dateEdit.date().toPyDate() self.deger1 = deger1.replace(day=1) self.deger2 = self.last_day_of_month(deger1) tar1 = self.deger1.strftime('%d%m%Y') tar2 = self.deger2.strftime('%d%m%Y') c = canvas.Canvas("./tempnenra/GELİRTABLO" + ".pdf") pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf')) c.setFont("Verdana", 14) item = " BISHOP RESTAURANT AYRINTILI GELİR TABLOSU " c.drawString(10, 810, item) c.setFont("Verdana", 8) tar1 = self.deger1.strftime('%Y-%m-%d') tar2 = self.deger2.strftime('%Y-%m-%d') sql = """SELECT * FROM test.genelrapor order by rkod """ bul2 = myddb1.cur.execute(sql) print(bul2, tar1, tar2) bul = myddb1.cur.fetchall() i = bul2 j = 5 self.tableWidget.setRowCount(i) self.tableWidget.setColumnCount(12) aa = 0 bb = 0 toplam = 0.0 toplam1 = 0.0 toplam2 = 0.0 for row1 in bul: item = str(row1[3]) toplam = toplam + float(row1[3]) self.tableWidget.setItem(aa, 2, QtWidgets.QTableWidgetItem(item)) c.drawRightString(290, 800 - (15 * (bb + 1)), item) item = " " c.drawString(350, 800 - (15 * (bb + 1)), item) toplam1 = toplam1 self.tableWidget.setItem(aa, 3, QtWidgets.QTableWidgetItem(item)) aa = aa + 1 bb = bb + 1 if (15 * (bb + 1)) >= 760: c.setFont("Verdana", 11) c.drawString(210, 800 - (15 * (bb + 1)), str(toplam)) c.drawString(270, 800 - (15 * (bb + 1)), str(toplam1)) c.drawString(350, 800 - (15 * (bb + 1)), str(toplam2)) c.showPage() c.setFont("Verdana", 8) bb = 0 c.setFont("Verdana", 12) c.drawString(210, 800 - (15 * (bb + 1)), "") c.drawRightString(300, 800 - (15 * (bb + 1)), str((bul[3][3]) - (bul[19][3]))) # c.drawString(450, 800 - (15 * (bb + 1)), "% " + str(int(toplam2 / toplam1 * 100))) c.save()
def form_03(request_data): """ Статистическая форма 066/у Приложение № 5 к приказу Минздрава России от 30 декабря 2002 г. № 413 """ num_dir = request_data["dir_pk"] direction_obj = Napravleniya.objects.get(pk=num_dir) hosp_nums_obj = hosp_get_hosp_direction(num_dir) hosp_nums = f"- {hosp_nums_obj[0].get('direction')}" ind_card = direction_obj.client patient_data = ind_card.get_data_individual() hospital: Hospitals = request_data["hospital"] hospital_name = hospital.safe_short_title hospital_address = hospital.safe_address hospital_kod_ogrn = hospital.safe_ogrn if sys.platform == 'win32': locale.setlocale(locale.LC_ALL, 'rus_rus') else: locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') pdfmetrics.registerFont( TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=25 * mm, rightMargin=5 * mm, topMargin=6 * mm, bottomMargin=10 * mm, allowSplitting=1, title="Форма {}".format("066/у-02")) width, height = portrait(A4) styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 12 style.leading = 15 style.spaceAfter = 0.5 * mm styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" styleCenter = deepcopy(style) styleCenter.alignment = TA_CENTER styleCenter.fontSize = 12 styleCenter.leading = 15 styleCenter.spaceAfter = 1 * mm styleCenterBold = deepcopy(styleBold) styleCenterBold.alignment = TA_CENTER styleCenterBold.fontSize = 12 styleCenterBold.leading = 15 styleCenterBold.face = 'PTAstraSerifBold' styleCenterBold.borderColor = black styleJustified = deepcopy(style) styleJustified.alignment = TA_JUSTIFY styleJustified.spaceAfter = 4.5 * mm styleJustified.fontSize = 12 styleJustified.leading = 4.5 * mm objs = [] styleT = deepcopy(style) styleT.alignment = TA_LEFT styleT.fontSize = 10 styleT.leading = 4.5 * mm styleT.face = 'PTAstraSerifReg' print_district = '' if SettingManager.get("district", default='True', default_type='b'): if ind_card.district is not None: print_district = 'Уч: {}'.format(ind_card.district.title) opinion = [ [ Paragraph( '<font size=11>{}<br/>Адрес: {}<br/>ОГРН: {} <br/><u>{}</u> </font>' .format(hospital_name, hospital_address, hospital_kod_ogrn, print_district), styleT), Paragraph( '<font size=9 >Код формы по ОКУД:<br/>Код организации по ОКПО: 31348613<br/>' 'Медицинская документация<br/>форма № 066/у-02</font>', styleT), ], ] tbl = Table(opinion, 2 * [90 * mm]) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.white), ('LEFTPADDING', (1, 0), (-1, -1), 80), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) space_symbol = ' ' if patient_data['age'] < SettingManager.get( "child_age_before", default='15', default_type='i'): patient_data['serial'] = patient_data['bc_serial'] patient_data['num'] = patient_data['bc_num'] else: patient_data['serial'] = patient_data['passport_serial'] patient_data['num'] = patient_data['passport_num'] card_num_obj = patient_data['card_num'].split(' ') p_card_num = card_num_obj[0] sex = patient_data['sex'] if sex == 'м': sex = f'{sex} - 1' if sex == 'ж': sex = f'{sex} - 2' doc_patient = f"{patient_data['type_doc']}, {patient_data['serial']} - {patient_data['num']}" polis_data = f"{patient_data['oms']['polis_serial']} {patient_data['oms']['polis_num']}" ############################################################################################################ # Получить данные из первичного приема (самого первого hosp-направления) hosp_first_num = hosp_nums_obj[0].get('direction') primary_reception_data = primary_reception_get_data(hosp_first_num) hospitalized = '' if primary_reception_data[ 'what_time_hospitalized'] and primary_reception_data[ 'plan_hospital']: if primary_reception_data['what_time_hospitalized'].lower().replace( ' ', '') == 'впервые': hospitalized = "первично - 1" if primary_reception_data['what_time_hospitalized'].lower().replace( ' ', '') == 'повторно': hospitalized = "повторно - 2" if primary_reception_data['plan_hospital'].lower().replace(' ', '') == 'да': hospitalized = f"{hospitalized}; в плановом порядке -4" if primary_reception_data['extra_hospital'].lower().replace( ' ', '') == 'да': hospitalized = f"{hospitalized}; по экстренным показаниям - 3" # Получить отделение - из названия услуги или самого главного направления hosp_depart = hosp_nums_obj[0].get('research_title') # взять самое последнее направленеие из hosp_dirs hosp_last_num = hosp_nums_obj[-1].get('direction') # 'Время выписки', 'Дата выписки', 'Основной диагноз (описание)', 'Осложнение основного диагноза (описание)', 'Сопутствующий диагноз (описание)' date_value, time_value, outcome, result_hospital = '', '', '', '' hosp_extract_data = hosp_extract_get_data(hosp_last_num) days_count = '__________________________' doc_fio = '' if hosp_extract_data: if hosp_extract_data['result_hospital']: result_hospital = hosp_extract_data['result_hospital'] if hosp_extract_data['outcome']: outcome = hosp_extract_data['outcome'] if hosp_extract_data['date_value']: date_value = hosp_extract_data['date_value'] if hosp_extract_data['time_value']: time_value = hosp_extract_data['time_value'] days_count = hosp_extract_data['days_count'] doc_fio = hosp_extract_data['doc_fio'] title_page = [ Indenter(left=0 * mm), Spacer(1, 8 * mm), Paragraph( '<font fontname="PTAstraSerifBold" size=13>СТАТИСТИЧЕСКАЯ КАРТА ВЫБЫВШЕГО ИЗ СТАЦИОНАРА<br/> ' 'круглосуточного пребывания, дневного стационара при больничном<br/> учреждении, дневного стационара при' ' амбулаторно-поликлиническом<br/> учреждении, стационара на дому<br/>' 'N медицинской карты {} {}</font>'.format(p_card_num, hosp_nums), styleCenter, ), Spacer(1, 2 * mm), Spacer(1, 2 * mm), Spacer(1, 2 * mm), Paragraph( '1. Код пациента: ________ 2. Ф.И.О.: {}'.format( patient_data['fio']), style), Paragraph( '3. Пол: {} {}4. Дата рождения {}'.format(sex, space_symbol * 24, patient_data['born']), style), Paragraph( '5. Документ, удостов. личность: (название, серия, номер) {} {}'. format(space_symbol * 2, doc_patient), style), Paragraph( '6. Адрес: регистрация по месту жительства: {}'.format( patient_data['main_address']), style), Paragraph( '7. Код территории проживания: ___ Житель: город - 1; село - 2.', style), Paragraph('8. Страховой полис (серия, номер):{}'.format(polis_data), style), Paragraph('Выдан: {}'.format(patient_data['oms']['polis_issued']), style), Paragraph('9. Вид оплаты:______________', style), Paragraph( '10. Социальный статус: {}'.format( primary_reception_data['social_status']), style), Paragraph( '11. Категория льготности: {}'.format( primary_reception_data['category_privilege']), style), Paragraph( '12. Кем направлен больной: {}'.format( primary_reception_data['who_directed']), style), Paragraph( '13. Кем доставлен: _________________________________ Код______ Номер наряда__________', style), Paragraph( '14. Диагноз направившего учреждения: {}'.format( primary_reception_data['diagnos_who_directed']), style), Paragraph( '14.1 Состояние при поступлении: {}'.format( primary_reception_data['state']), style), Paragraph( '15. Диагноз приемного отделения:{}'.format( primary_reception_data['diagnos_entered']), style), Paragraph( '16. Доставлен в состоянии опьянения: Алкогольного — 1; Наркотического — 2.', style), Paragraph( '17. Госпитализирован по поводу данного заболевания в текущем году: {}' .format(hospitalized), style), Paragraph( '18.Доставлен в стационар от начала заболевания(получения травмы): {}' .format(primary_reception_data['time_start_ill']), style), Paragraph( '19. Травма: {}'.format(primary_reception_data['type_trauma']), style), Paragraph( '20. Дата поступления в приемное отделение:______________ Время__________', style), Paragraph( '21. Название отделения: <u>{}</u>; дата поступления: <u>{}</u>; время: <u>{}</u>' .format(hosp_depart, primary_reception_data['date_entered_value'], primary_reception_data['time_entered_value']), style, ), Paragraph( 'Подпись врача приемного отделения ______________ Код __________', style), Paragraph( '22. Дата выписки (смерти): {}; Время {}'.format( date_value, time_value), style), Paragraph( '23. Продолжительность госпитализации (койко - дней): {}'.format( days_count), style), Paragraph('24. Исход госпитализации: {}'.format(outcome), style), Paragraph('24.1. Результат госпитализации: {}'.format(result_hospital), style), ] closed_bl_result = closed_bl(hosp_nums_obj[0].get('direction')) title_page.append( Paragraph( f"25. Листок нетрудоспособности: открыт <u>{closed_bl_result['start_date']}</u> закрыт: <u>{closed_bl_result['end_date']}</u>" f" к труду: <u>{closed_bl_result['start_work']}</u>", style, )) title_page.append( Paragraph(f"25.1. Номере ЛН : <u>{closed_bl_result['num']}</u>", style)) title_page.append( Paragraph(f"25.2. Выдан кому : {closed_bl_result['who_get']}", style)) title_page.append( Paragraph( '25.3. По уходу за больным Полных лет: _____ Пол: {}'.format(sex), style)) title_page.append(Paragraph('26. Движение пациента по отделениям:', style)) objs.extend(title_page) styleTB = deepcopy(style) styleTB.fontSize = 8.7 styleTB.alignment = TA_CENTER styleTB.leading = 3.5 * mm styleTC = deepcopy(style) styleTC.fontSize = 9.5 styleTC.alignment = TA_LEFT styleTCright = deepcopy(styleTC) styleTCright.alignment = TA_RIGHT styleTCcenter = deepcopy(styleTC) styleTCcenter.alignment = TA_CENTER opinion = [[ Paragraph('N', styleTB), Paragraph('Код отделения', styleTB), Paragraph('Профиль коек', styleTB), Paragraph('Код врача', styleTB), Paragraph('Дата поступления', styleTB), Paragraph('Дата выписки, перевода', styleTB), Paragraph('Код диагноза по МКБ', styleTB), Paragraph('Код медицинского стандарта', styleTB), Paragraph('Код прерванного случая', styleTB), Paragraph('Вид оплаты', styleTB), ]] patient_movement = hosp_patient_movement(hosp_nums_obj) x = 0 for i in patient_movement: x += 1 doc_code = '' if i['doc_confirm_code']: doc_code = str(i['doc_confirm_code']) tmp_data = [ [ Paragraph(str(x), styleTB), Paragraph('', styleTB), Paragraph(i['bed_profile_research_title'], styleTB), Paragraph(doc_code, styleTB), Paragraph(i['date_entered_value'], styleTB), Paragraph(i['date_oute'], styleTB), Paragraph(i['diagnos_mkb'], styleTB), Paragraph('', styleTB), Paragraph('', styleTB), Paragraph('ОМС', styleTB), ], ] opinion.extend(tmp_data.copy()) # получить структуру данных для таблицы tbl_act = Table(opinion, repeatRows=1, colWidths=(7 * mm, 15 * mm, 30 * mm, 20 * mm, 21 * mm, 21 * mm, 20 * mm, 14 * mm, 14 * mm, 20 * mm)) tbl_act.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) objs.append(tbl_act) objs.append(Spacer(1, 2 * mm)) objs.append( Paragraph( '27. Хирургические операции(обозначить: основную операцию, использование спец.аппаратуры):', style), ) opinion = [[ Paragraph('Дата, Час', styleTB), Paragraph('Код <br/>хирурга', styleTB), Paragraph('Код отделения', styleTB), Paragraph('наименование операции', styleTB), Paragraph('код операции', styleTB), Paragraph('наименование осложнения', styleTB), Paragraph('Код ослонения', styleTB), Paragraph('Анестезия (код врача)', styleTB), Paragraph('энд.', styleTB), Paragraph('лазер.', styleTB), Paragraph('криог.', styleTB), Paragraph('Вид оплаты', styleTB), ]] patient_operation = hosp_get_operation_data(num_dir) operation_result = [] for i in patient_operation: operation_template = [''] * 12 operation_template[0] = Paragraph( i['date'] + '<br/>' + i['time_start'] + '-' + i['time_end'], styleTB) operation_template[1] = Paragraph(str(i['doc_code']), styleTB) operation_template[3] = Paragraph( f"{i['name_operation']} <br/><font face=\"PTAstraSerifBold\" size=\"8.7\">({i['category_difficult']})</font>", styleTB) operation_template[4] = Paragraph( '{}'.format(i['code_operation'] + '<br/>' + i['plan_operation']), styleTB) operation_template[7] = Paragraph( '{}'.format(i['anesthesia method'] + '<br/> (' + i['code_doc_anesthesia'] + ')'), styleTB) operation_template[5] = Paragraph(i['complications'], styleTB) operation_template[11] = Paragraph(" ОМС", styleTB) operation_result.append(operation_template.copy()) opinion.extend(operation_result) tbl_act = Table(opinion, repeatRows=1, colWidths=(22 * mm, 12 * mm, 11 * mm, 26 * mm, 26 * mm, 20 * mm, 10 * mm, 15 * mm, 7 * mm, 7 * mm, 7 * mm, 16 * mm)) tbl_act.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) objs.append(tbl_act) objs.append(Spacer(1, 2 * mm)) space_symbol = ' ' objs.append( Paragraph('28. Обследован: RW {} AIDS '.format(space_symbol * 10), style), ) objs.append(Spacer(1, 2 * mm)) objs.append(Paragraph('29. Диагноз стационара(при выписке):', style), ) opinion = [[ Paragraph('Клинический заключительный', styleTB), Paragraph('Основное заболевание', styleTB), Paragraph('Код МКБ', styleTB), Paragraph('Осложнение', styleTB), Paragraph('Код МКБ', styleTB), Paragraph('Сопутствующее заболевание', styleTB), Paragraph('Код МКБ', styleTB), ]] hosp_last_num = hosp_nums_obj[-1].get('direction') hosp_extract_data = hosp_extract_get_data(hosp_last_num) opinion_diagnos = [] if hosp_extract_data: opinion_diagnos = [[ Paragraph('', styleTB), Paragraph(hosp_extract_data['final_diagnos'], styleTB), Paragraph(hosp_extract_data['final_diagnos_mkb'], styleTB), Paragraph(hosp_extract_data['other_diagnos'], styleTB), Paragraph(hosp_extract_data['other_diagnos_mkb'], styleTB), Paragraph( hosp_extract_data['near_diagnos'].replace('<', '<').replace( '>', '>'), styleTB), Paragraph(hosp_extract_data['near_diagnos_mkb'], styleTB), ]] opinion.extend(opinion_diagnos) opinion_pathologist = [[ Paragraph('Патологоанатомический ', styleTB), Paragraph('', styleTB), Paragraph('', styleTB), Paragraph('', styleTB), Paragraph('', styleTB), Paragraph('', styleTB), Paragraph('', styleTB), ]] opinion.extend(opinion_pathologist) tbl_act = Table(opinion, repeatRows=1, colWidths=(28 * mm, 45 * mm, 15 * mm, 30 * mm, 15 * mm, 30 * mm, 15 * mm)) tbl_act.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('SPAN', (0, 0), (0, 1)), ])) objs.append(tbl_act) objs.append(Spacer(1, 2 * mm)) objs.append( Paragraph( '30.В случае смерти указать основную причину:______________________________________________________________' 'Код МКБ', style), ) objs.append(Spacer(1, 20 * mm)) objs.append( Paragraph( '31. Дефекты догоспитального этапа: несвоевременность госпитализации - 1; недостаточный объем клинико - диагностического обследования - 2; ' 'неправильная тактика лечения - 3; несовпадение диагноза - 4.', style, ), ) objs.append(Spacer(1, 7 * mm)) objs.append( Paragraph( 'Подпись лечащего врача ({}) ____________________________'.format( doc_fio), style), ) objs.append(Spacer(1, 7 * mm)) objs.append(Paragraph('Подпись заведующего отделением', style), ) def first_pages(canvas, document): canvas.saveState() canvas.restoreState() def later_pages(canvas, document): canvas.saveState() canvas.restoreState() doc.build(objs, onFirstPage=first_pages, onLaterPages=later_pages) pdf = buffer.getvalue() buffer.close() return pdf
def form_02(request_data): """ Отдельный статталон по отдельному амбулаторному приему. Краткая форма - результата проткола. Учитываются те поля, к-рые имеют признак "для статталона" ------------------------------- Вход: Направление. Выходные: форма в файле .....\Lib\site-packages\anytree\render.py class ContStyle(AbstractStyle): необходимое мотод super сделать так:(изменить символы) super(ContStyle, self).__init__(u'\u2063 ', u'\u2063 ', u'\u2063 ') """ # получить направления ind_dir = json.loads(request_data["napr_id"]) hospital_name = SettingManager.get("org_title") if sys.platform == 'win32': locale.setlocale(locale.LC_ALL, 'rus_rus') else: locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') pdfmetrics.registerFont( TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) pdfmetrics.registerFont( TTFont('Symbola', os.path.join(FONTS_FOLDER, 'Symbola.ttf'))) buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=18 * mm, rightMargin=5 * mm, topMargin=6 * mm, bottomMargin=6 * mm, allowSplitting=1, title="Форма {}".format("Статталон пациента")) width, height = portrait(A4) styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 10 style.leading = 12 style.spaceAfter = 0.5 * mm styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" styleCenter = deepcopy(style) styleCenter.alignment = TA_CENTER styleCenter.fontSize = 12 styleCenter.leading = 10 styleCenter.spaceAfter = 1 * mm styleCenterBold = deepcopy(styleBold) styleCenterBold.alignment = TA_CENTER styleCenterBold.fontSize = 12 styleCenterBold.leading = 15 styleCenterBold.face = 'PTAstraSerifBold' styleCenterBold.borderColor = black styleJustified = deepcopy(style) styleJustified.alignment = TA_JUSTIFY styleJustified.spaceAfter = 4.5 * mm styleJustified.fontSize = 12 styleJustified.leading = 4.5 * mm objs = [] styleT = deepcopy(style) styleT.alignment = TA_LEFT styleT.fontSize = 10 styleT.leading = 4.5 * mm styleT.face = 'PTAstraSerifReg' for dir in ind_dir: obj_dir = Napravleniya.objects.get(pk=dir) ind_card = obj_dir.client patient_data = ind_card.get_data_individual() if patient_data['age'] < SettingManager.get( "child_age_before", default='15', default_type='i'): patient_data['serial'] = patient_data['bc_serial'] patient_data['num'] = patient_data['bc_num'] else: patient_data['serial'] = patient_data['passport_serial'] patient_data['num'] = patient_data['passport_num'] card_num_obj = patient_data['card_num'].split(' ') p_card_num = card_num_obj[0] if len(card_num_obj) == 2: p_card_type = '(' + str(card_num_obj[1]) + ')' else: p_card_type = '' space_symbol = ' ' # Добавить сведения о пациента content_title = [ Indenter(left=0 * mm), Spacer(1, 1 * mm), Paragraph('{}'.format(hospital_name), styleCenterBold), Spacer(1, 2 * mm), Paragraph('<u>Статистический талон пациента</u>', styleCenter), Paragraph( '{}<font size=10>Карта № </font><font fontname="PTAstraSerifBold" size=10>{}</font><font size=10> из {}</font>' .format(3 * space_symbol, p_card_num, p_card_type), styleCenter), Spacer(1, 2 * mm), Paragraph('<font size=11>Данные пациента:</font>', styleBold), Paragraph( "1. Фамилия, имя, отчество: <font size=11.7 fontname ='PTAstraSerifBold'> {} </font> " .format(patient_data['fio']), style), Paragraph( '2. Пол: {} {} 3. Дата рождения: {}'.format( patient_data['sex'], 3 * space_symbol, patient_data['born']), style), Paragraph( '4. Место регистрации: {}'.format( patient_data['main_address']), style), Paragraph( '5. Полис ОМС: серия {} №: {} {}' '6. СНИЛС: {}'.format(patient_data['oms']['polis_serial'], patient_data['oms']['polis_num'], 13 * space_symbol, patient_data['snils']), style, ), Paragraph( '7. Наименование страховой медицинской организации: {}'.format( patient_data['oms']['polis_issued']), style), ] objs.extend(content_title) # добавить данные об услуге objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph('<font size=11>Данные об услуге:</font>', styleBold)) objs.append(Spacer(1, 1 * mm)) obj_iss = Issledovaniya.objects.filter(napravleniye=obj_dir, parent_id=None).first() date_proto = utils.strfdatetime(obj_iss.time_confirmation, "%d.%m.%Y") opinion = [ [ Paragraph('Основная услуга', styleT), Paragraph( '<font fontname="PTAstraSerifBold">{}</font> <font face="Symbola">\u2013</font> {}' .format(obj_iss.research.code, obj_iss.research.title), styleT), ], [ Paragraph('Направление №', styleT), Paragraph('{}'.format(dir), styleT) ], [ Paragraph('Дата протокола', styleT), Paragraph('{}'.format(date_proto), styleT) ], ] # Найти и добавить поля у к-рых флаг "for_talon". Отсортировано по 'order' (группа, поле) field_iss = ParaclinicResult.objects.filter( issledovaniye=obj_iss, field__for_talon=True).order_by('field__group__order', 'field__order') for f in field_iss: v = f.value.replace("\n", "<br/>") field_type = f.get_field_type() if field_type == 1: vv = v.split('-') if len(vv) == 3: v = "{}.{}.{}".format(vv[2], vv[1], vv[0]) list_f = [[ Paragraph(f.field.get_title(force_type=field_type), styleT), Paragraph(v, styleT) ]] opinion.extend(list_f) tbl = Table(opinion, colWidths=(60 * mm, 123 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BOTTOMPADDING', (0, 0), (-1, -1), 1 * mm), ])) objs.append(tbl) # Заключительные положения objs.append(Spacer(1, 4 * mm)) objs.append( Paragraph('<font size=11>Заключительные положения:</font>', styleBold)) objs.append(Spacer(1, 1 * mm)) empty = '-' purpose = empty if not obj_iss.purpose else obj_iss.purpose outcome_illness = empty if not obj_iss.outcome_illness else obj_iss.outcome_illness result_reception = empty if not obj_iss.result_reception else obj_iss.result_reception diagnos = empty if not obj_iss.diagnos else obj_iss.diagnos opinion = [ [ Paragraph('Цель посещения', styleT), Paragraph('{}'.format(purpose), styleT) ], [ Paragraph('Исход заболевания', styleT), Paragraph('{}'.format(outcome_illness), styleT) ], [ Paragraph('Результат обращения', styleT), Paragraph('{}'.format(result_reception), styleT) ], [ Paragraph('Основной диагноз', styleT), Paragraph('{}'.format(diagnos), styleT) ], ] tbl = Table(opinion, colWidths=(60 * mm, 123 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BOTTOMPADDING', (0, 0), (-1, -1), 1 * mm), ])) objs.append(tbl) # Добавить Дополнительные услуги add_research = Issledovaniya.objects.filter( parent_id__napravleniye=obj_dir) if add_research: objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph('<font size=11>Дополнительные услуги:</font>', styleBold)) objs.append(Spacer(1, 1 * mm)) for i in add_research: objs.append( Paragraph( '{} <font face="Symbola">\u2013</font> {}'.format( i.research.code, i.research.title), style)) objs.append(Spacer(1, 5 * mm)) objs.append( HRFlowable(width=185 * mm, thickness=0.7 * mm, spaceAfter=1.3 * mm, spaceBefore=0.5 * mm, color=colors.black, hAlign=TA_LEFT)) objs.append(Paragraph('<font size=11>Лечащий врач:</font>', styleBold)) objs.append(Spacer(1, 1 * mm)) personal_code = '' doc_fio = '' if obj_iss.time_confirmation: personal_code = empty if not obj_iss.doc_confirmation or not obj_iss.doc_confirmation.personal_code else obj_iss.doc_confirmation.personal_code doc_fio = obj_iss.doc_confirmation_fio objs.append( Paragraph( '{} /_____________________/ {} Код врача: {} '.format( doc_fio, 42 * space_symbol, personal_code), style)) objs.append(Spacer(1, 5 * mm)) # Получить структуру Направлений если, направление в Дереве не важно в корне в середине или в начале root_dir = tree_directions.root_direction(dir) num_iss = root_dir[-1][-2] tree_dir = tree_directions.tree_direction(num_iss) final_tree = {} pattern = re.compile('<font face=\"Symbola\" size=10>\u2713</font>') node_dir = Node("Структура направлений") for j in tree_dir: if not Researches.objects.get(pk=j[8]).is_hospital: continue if len(j[9]) > 47: research = j[9][:47] + '...' else: research = j[9] diagnos = ' --' + j[-2] if j[-2] else "" temp_s = f"{j[0]} - {research}. Создано {j[1]} в {j[2]} {diagnos}" if dir == j[0]: temp_s = f"{temp_s} -- <font face=\"Symbola\" size=10>\u2713</font>" if not j[3]: final_tree[j[5]] = Node(temp_s, parent=node_dir) else: final_tree[j[5]] = Node(temp_s, parent=final_tree.get(j[3])) counter = 0 opinion = [] for row in RenderTree(node_dir): counter += 1 result = pattern.search(row.node.name) current_style = styleBold if result else styleT count_space = len(row.pre) // 2 * 2 para = [ Paragraph( '{}{}'.format(space_symbol * count_space, row.node.name), current_style) ] opinion.append(para) tbl = Table(opinion, colWidths=(190 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.white), ('BOTTOMPADDING', (0, 0), (-1, -1), 1 * mm), ])) objs.append(tbl) objs.append(PageBreak()) doc.build(objs) pdf = buffer.getvalue() buffer.close() return pdf
def generatePdf(facility_name, Facility_data, Funding, current_year): """ generatePdf creates a PDF document based on the reporting data supplied. It is using very strict formatting, but is quite simple to edit. This function will print the name of the facility its working on, and any warnings that may arise. The excel document can be edited to fix warnings and to change the information in the PDFs. """ print("\nFacility report {}: {}".format(current_year, facility_name)) if not os.path.isdir("pdfs_onepagers/"): os.mkdir("pdfs_onepagers/") # Setting the document sizes and margins. showBoundary is useful for debugging doc = BaseDocTemplate( "pdfs_onepagers/{}_{}.pdf".format( current_year, facility_name.lower().replace(" ", "_")), pagesize=A4, rightMargin=18 * mm, leftMargin=14 * mm, topMargin=16 * mm, bottomMargin=20 * mm, showBoundary=0, ) # These are the fonts available, in addition to a number of "standard" fonts. # These are used in setting paragraph styles pdfmetrics.registerFont(TTFont("Lato-B", "Lato-Black.ttf")) # looks bolder pdfmetrics.registerFont(TTFont("Lato", "Lato-Regular.ttf")) # I have used spaceAfter, spaceBefore and leading to change the layout of the "paragraphs" created with these styles styles = getSampleStyleSheet() styles.add( ParagraphStyle( name="onepager_inner_heading", parent=styles["Heading1"], fontName="Lato-B", fontSize=10, color="#FF00AA", leading=16, spaceAfter=0, spaceBefore=8, )) styles.add( ParagraphStyle( name="onepager_chart_heading", parent=styles["Heading1"], fontName="Lato-B", fontSize=10, color="#FF00AA", leading=16, spaceAfter=4, spaceBefore=8, )) styles.add( ParagraphStyle( name="onepager_title", parent=styles["Heading1"], fontName="Lato-B", fontSize=16, bold=0, color="#000000", leading=16, spaceBefore=0, )) styles.add( ParagraphStyle( name="onepager_text", parent=styles["Normal"], fontName="Lato", fontSize=10, bold=0, color="#000000", leading=14, )) styles.add( ParagraphStyle( name="onepager_footnote", parent=styles["Normal"], fontName="Lato", fontSize=7, bold=0, color="#000000", leading=14, spaceBefore=20, )) # The document is set up with two frames, one frame is one column, and their widths are set according to SciLifeLab design policy frame1 = Frame( doc.leftMargin, doc.bottomMargin + (doc.height / 2), doc.width / 3, # - 3.5 * mm, (doc.height / 2) - 18 * mm, id="col1", # showBoundary=1, #this can be used to show where the frame sits - useful for setting up layout leftPadding=0 * mm, topPadding=5 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) frame2 = Frame( doc.leftMargin + doc.width / 3 + 2 * mm, # 2 + 3.5 * mm, doc.bottomMargin + (doc.height / 2), doc.width / 3, # 2 - 3.5 * mm, (doc.height / 2) - 18 * mm, id="col2", # showBoundary=1, leftPadding=0 * mm, topPadding=5 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) frame3 = Frame( doc.leftMargin + (3.5 * mm) + doc.width * 0.61, doc.bottomMargin + (doc.height / 2), doc.width / 2.7, # 2 - 3.5 * mm, (doc.height / 2) - 18 * mm, id="col3", # showBoundary=1, leftPadding=0 * mm, topPadding=5 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) # top 3 frames contain the text # Next frames the Figures # Bar charts go first - divide the page in halves for them frame4 = Frame( doc.leftMargin, doc.bottomMargin + (doc.height / 4), doc.width / 2, # 2 - 3.5 * mm, (doc.height / 4), # + 50 * mm, # - 18 * mm, id="pic1", # showBoundary=1, leftPadding=0 * mm, topPadding=3 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) frame5 = Frame( doc.leftMargin + (doc.width / 2), doc.bottomMargin + (doc.height / 4), doc.width / 2, # 2 - 3.5 * mm, (doc.height / 4), # + 50 * mm, # - 18 * mm, id="pic2", # showBoundary=1, leftPadding=0 * mm, topPadding=3 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) # NOW 3 PIE CHARTS frame6 = Frame( doc.leftMargin, doc.bottomMargin, doc.width / 3, # 2 - 3.5 * mm, (doc.height / 4), # + 50 * mm, # - 18 * mm, id="pic3", # showBoundary=1, leftPadding=0 * mm, topPadding=0 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) frame7 = Frame( doc.leftMargin + doc.width / 3, doc.bottomMargin, doc.width / 3, # 2 - 3.5 * mm, (doc.height / 4), # + 50 * mm, # - 18 * mm, id="pic4", # showBoundary=1, leftPadding=0 * mm, topPadding=0 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) frame8 = Frame( doc.leftMargin + doc.width / 3 + doc.width / 3, doc.bottomMargin, doc.width / 3, # 2 - 3.5 * mm, (doc.height / 4), # + 50 * mm, # - 18 * mm, id="pic5", # showBoundary=1, leftPadding=0 * mm, topPadding=0 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) header_content = Paragraph( "<b>{}</b><br/><font name=Lato size=12> {} platform</font>".format( (Facility_data["Facility"]).to_string(index=False), (Facility_data["Platform"]).to_string(index=False), ), styles["onepager_title"], ) template = PageTemplate( id="test", frames=[ frame1, frame2, frame3, frame4, frame5, frame6, frame7, frame8 ], onPage=partial(header, content=header_content), ) doc.addPageTemplates([template]) # frames=[frame1,frame2] # The Story list will contain all Paragraph and other elements. In the end this is used to build the document Story = [] ### Below here will be Paragraph and Image elements added to the Story, they flow through frames automatically, ### however I have set a framebreak to correctly organise things in left/right column. pd.options.display.max_colwidth = 600 Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Basic information</b></font>", styles["onepager_inner_heading"], )) # Drug Discovery and Development (DDD) is a platform. needs different formatting if facility_name == "Drug Discovery and Development": Story.append( Paragraph( "<font name=Lato-B><b>Platform directors: </b></font> {}". format((Facility_data["FD"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( "<font name=Lato-B><b>SciLifeLab platform since: </b></font> {}" .format((Facility_data["SLL_since"]).to_string(index=False), ), styles["onepager_text"], )) else: Story.append( Paragraph( "<font name=Lato-B><b>Facility director(s): </b></font> {}". format((Facility_data["FD"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( "<font name=Lato-B><b>Head(s) of facility: </b></font> {}". format((Facility_data["HOF"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( "<font name=Lato-B><b>SciLifeLab facility since: </b></font> {}" .format((Facility_data["SLL_since"]).to_string(index=False), ), styles["onepager_text"], )) pd.options.display.max_colwidth = 600 Story.append( Paragraph( "<font name=Lato-B><b>Host university: </b></font>{}".format( (Facility_data["H_uni"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( "<font name=Lato-B><b>FTEs: </b></font>{}".format( (Facility_data["FTEs"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( u"<font name=Lato-B><b>FTEs financed by SciLifeLab: </b></font>{}". format((Facility_data["SLL_FTEs"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( "<font color='#A7C947'><font name=Lato-B><b>Funding in {} (kSEK)</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) # Funding (need to have Scilifelab, other sources and then total) # SLL funding in file provided by OO. Calculated total using this and 'other funding' Story.append( Paragraph( "<font name=Lato-B><b>SciLifeLab: </b></font>{}".format( (Facility_data["Amount (kSEK)"]).to_string(index=False), ), styles["onepager_text"], )) # Scilifelab funding is in funding data and total funding is in there too, but other financiers vary # Need to take out Scilifelab funding and total funding to be able to go through other funders without issue fundwosll = Funding[~Funding.Financier.eq("SciLifeLab")] fundwoslltot = fundwosll[~fundwosll.Financier.eq("Total")] for i in fundwoslltot["Financier"].unique(): temp = fundwoslltot[(fundwoslltot["Financier"] == i)] if temp is not None: Story.append( Paragraph( "<font name=Lato-B><b>{}: </b></font>{}".format( i, temp["Amount (kSEK)"][ temp["Amount (kSEK)"].first_valid_index()], ), styles["onepager_text"], )) # now a line above the total value Story.append( HRFlowable( width="40%", thickness=0.5, lineCap="round", color=SCILIFE_COLOURS_GREYS[1], spaceBefore=1, spaceAfter=1, hAlign="LEFT", vAlign="BOTTOM", dash=None, )) # now the totals fundstot = Funding[Funding.Financier.eq("Total")] Story.append( Paragraph( "<font name=Lato-B><b>Total: </b></font>{}".format( (fundstot["Amount (kSEK)"]).to_string(index=False), ), styles["onepager_text"], )) Story.append(CondPageBreak(100 * mm)) ### RESOURCE ALLOCATION total_percentage = total_percentage = (int(Facility_data["RA_nat"]) + int(Facility_data["RA_int"]) + int(Facility_data["RA_tech"]) + int(Facility_data["RA_Ind"]) + int(Facility_data["RA_Health"]) + int(Facility_data["RA_ogov"])) if total_percentage == 100: Story.append( Paragraph( "<font color='#A7C947'><font name=Lato-B><b>Resource allocation {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) else: print( "WARNING: PERCENTAGE DOES NOT ADD UP TO 100 IN RESOURCE_ALLOCATION FOR", facility_name, total_percentage, ) Story.append( Paragraph( "<font color='#FF0000'><font name=Lato-B><b>Resource allocation {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) if int(Facility_data.RA_nat) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_nat"])) Story.append( Paragraph( "<font name=Lato-B><b>Academia (national): </b></font>{}".format( tmp_input), styles["onepager_text"], )) if int(Facility_data.RA_int) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_int"])) Story.append( Paragraph( "<font name=Lato-B><b>Academia (international): </b></font>{}". format(tmp_input), styles["onepager_text"], )) if int(Facility_data.RA_tech) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_tech"])) Story.append( Paragraph( "<font name=Lato-B><b>Internal tech. dev.: </b></font>{}".format( tmp_input), styles["onepager_text"], )) if int(Facility_data.RA_Ind) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_Ind"])) Story.append( Paragraph( "<font name=Lato-B><b>Industry: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.RA_Health) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_Health"])) Story.append( Paragraph( "<font name=Lato-B><b>Healthcare: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.RA_ogov) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_ogov"])) Story.append( Paragraph( "<font name=Lato-B><b>Other gov. agencies: </b></font>{}".format( tmp_input), styles["onepager_text"], )) # Story.append(CondPageBreak(50 * mm)) ### USER FEES - reagents, instruments... total_percentage = (int(Facility_data["UF_reag"]) + int(Facility_data["UF_instr"]) + int(Facility_data["UF_sal"]) + int(Facility_data["UF_rent"]) + int(Facility_data["UF_other"])) if total_percentage == 100: Story.append( Paragraph( "<font color='#A7C947'><font name=Lato-B><b>User Fees {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) else: print( "WARNING: PERCENTAGE DOES NOT ADD UP TO 100 IN COSTS FOR", facility_name, total_percentage, ) Story.append( Paragraph( "<font color='#FF0000'><font name=Lato-B><b>User Fees {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) Story.append( Paragraph( "<font name=Lato-B><b>Total (kSEK): </b></font>{}".format( (Facility_data["UF_Tot"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( HRFlowable( width="40%", thickness=0.5, lineCap="round", color=SCILIFE_COLOURS_GREYS[1], spaceBefore=1, spaceAfter=1, hAlign="LEFT", vAlign="BOTTOM", dash=None, )) if int(Facility_data.UF_reag) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_reag"])) Story.append( Paragraph( "<font name=Lato-B><b>Reagents: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_instr) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_instr"])) Story.append( Paragraph( "<font name=Lato-B><b>Instrument: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_sal) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sal"])) Story.append( Paragraph( "<font name=Lato-B><b>Salaries: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_rent) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_rent"])) Story.append( Paragraph( "<font name=Lato-B><b>Rent: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_other) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_other"])) Story.append( Paragraph( "<font name=Lato-B><b>Other: </b></font>{}".format(tmp_input), styles["onepager_text"], )) Story.append(CondPageBreak(100 * mm)) ### USER FEES BY SECTOR total_percentage = (int(Facility_data["UF_sect_nat"]) + int(Facility_data["UF_sect_int"]) + int(Facility_data["UF_sect_ind"]) + int(Facility_data["UF_sect_health"]) + int(Facility_data["UF_sect_othgov"])) if total_percentage == 100: Story.append( Paragraph( "<font color='#A7C947'><font name=Lato-B><b>User fees by sector {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) else: print( "WARNING: PERCENTAGE DOES NOT ADD UP TO 100 IN USER FEES FOR", facility_name, total_percentage, ) Story.append( Paragraph( "<font color='#FF0000'><font name=Lato-B><b>User fees by sector {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) if int(Facility_data.UF_sect_nat) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sect_nat"])) Story.append( Paragraph( "<font name=Lato-B><b>Academia (national): </b></font>{}".format( tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_sect_int) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sect_int"])) Story.append( Paragraph( "<font name=Lato-B><b>Academia (international): </b></font>{}". format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_sect_ind) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sect_ind"])) Story.append( Paragraph( "<font name=Lato-B><b>Industry: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_sect_health) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sect_health"])) Story.append( Paragraph( "<font name=Lato-B><b>Healthcare: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_sect_othgov) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sect_othgov"])) Story.append( Paragraph( "<font name=Lato-B><b>Other gov. agencies: </b></font>{}".format( tmp_input), styles["onepager_text"], )) # Story.append(CondPageBreak(50 * mm)) #### SERVICES Story.append( Paragraph( "<font color='#A7C947'><font name=Lato-B><b>Services</b></font></font>", styles["onepager_inner_heading"], )) if Facility_data["Services"].notnull: pd.options.display.max_colwidth = 600 bullet_pointing = Facility_data["Services"].to_string(index=False) bullet_points = bullet_pointing.replace("\\n", "*") bullet_points = bullet_points.split("*") # .explode(bullet_points) for bullet in bullet_points: Story.append(Paragraph(bullet, styles["onepager_text"])) else: Story.append( Paragraph( "Service information goes here, please input text in excel file", styles["onepager_text"], )) # special notes # This puts an asterisk at the bottom of the services, with some info if there was any in the data file if facility_name == "Mass Cytometry (KI)": Story.append( Paragraph( "Note: publication data is combined for the two Mass Cytometry facilities", styles["onepager_footnote"], )) elif facility_name == "Mass Cytometry (LiU)": Story.append( Paragraph( "Note: publication data is combined for the two Mass Cytometry facilities", styles["onepager_footnote"], )) else: print("no special notes for this facility") # Now I need to put in the Figures.. (5 plots if data is available for everything, or some might be missing) # figs already made in .svg format, they need to be imported Story.append(CondPageBreak(200 * mm)) # move to next frame # pubs by cat first, then pubs by JIF Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Publication by category</b></font>", styles["onepager_chart_heading"], )) filepath_cats = "/Users/liahu895/Documents/GitHub/IAB_2021/Facility_one_pagers/Updated_2021scripts/Plots/pubcat_plots/{}_cats.svg".format( (facility_name), ) isFile_cats = os.path.isfile(filepath_cats) if isFile_cats == True: im_cats = svg2rlg(filepath_cats) im_cats = Image(im_cats, width=70 * mm, height=55 * mm) im_cats.hAlign = "CENTER" Story.append(im_cats) else: Story.append( Paragraph( "No publication data available", styles["onepager_text"], )) # Now JIF barchart Story.append(CondPageBreak(200 * mm)) # move to next frame Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Publication by Journal Impact Factor</b></font>", styles["onepager_chart_heading"], )) filepath_JIF = "/Users/liahu895/Documents/GitHub/IAB_2021/Facility_one_pagers/Updated_2021scripts/Plots/JIF_plots/{}_JIF.svg".format( (facility_name), ) isFile_JIF = os.path.isfile(filepath_JIF) if isFile_JIF == True: im_JIF = svg2rlg(filepath_JIF) im_JIF = Image(im_JIF, width=70 * mm, height=55 * mm) im_JIF.hAlign = "CENTER" Story.append(im_JIF) else: Story.append( Paragraph( "No publication data available", styles["onepager_text"], )) Story.append(CondPageBreak(200 * mm)) # move to next frame # # Now the pie charts (in the lowest part of the page)- ascending year left to right Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Users {}</b></font>".format( int(current_year) - 2), styles["onepager_chart_heading"], )) filepath_u18 = "/Users/liahu895/Documents/GitHub/IAB_2021/Facility_one_pagers/Updated_2021scripts/Plots/Aff_Pies/{}_{}_affs.svg".format( (facility_name), (int(current_year) - 2), ) isFile_u18 = os.path.isfile(filepath_u18) if isFile_u18 == True: im_u18 = svg2rlg(filepath_u18) im_u18 = Image(im_u18, width=58 * mm, height=58 * mm) im_u18.hAlign = "CENTER" Story.append(im_u18) else: Story.append( Paragraph( "No user information", styles["onepager_text"], )) Story.append(CondPageBreak(200 * mm)) # move to next frame Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Users {}</b></font>".format( int(current_year) - 1), styles["onepager_chart_heading"], )) filepath_u19 = "/Users/liahu895/Documents/GitHub/IAB_2021/Facility_one_pagers/Updated_2021scripts/Plots/Aff_Pies/{}_{}_affs.svg".format( (facility_name), (int(current_year) - 1), ) isFile_u19 = os.path.isfile(filepath_u19) if isFile_u19 == True: im_u19 = svg2rlg(filepath_u19) im_u19 = Image(im_u19, width=58 * mm, height=58 * mm) im_u19.hAlign = "CENTER" Story.append(im_u19) else: Story.append( Paragraph( "No user information", styles["onepager_text"], )) Story.append(CondPageBreak(200 * mm)) # move to next frame Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Users {}</b></font>".format( int(current_year)), styles["onepager_chart_heading"], )) filepath_u20 = "/Users/liahu895/Documents/GitHub/IAB_2021/Facility_one_pagers/Updated_2021scripts/Plots/Aff_Pies/{}_{}_affs.svg".format( (facility_name), (int(current_year)), ) isFile_u20 = os.path.isfile(filepath_u20) if isFile_u20 == True: im_u20 = svg2rlg(filepath_u20) im_u20 = Image(im_u20, width=58 * mm, height=58 * mm) im_u20.hAlign = "CENTER" Story.append(im_u20) else: Story.append( Paragraph( "No user information", styles["onepager_text"], )) # Finally, build the document. doc.build(Story)
def sloturunmaliyet(self): firma = "%" + self.lineEdit.text() + "%" print("firma ", firma) myddb1 = Myddb() self.kontrol = 1 self.tableWidget.clearContents() self.tableWidget.setColumnWidth(0, 75) self.tableWidget.setColumnWidth(1, 400) self.tableWidget.setColumnWidth(2, 100) self.tableWidget.setColumnWidth(3, 25) self.tableWidget.setColumnWidth(4, 25) deger1 = self.dateEdit.date().toPyDate() deger2 = self.dateEdit_2.date().toPyDate() tar1 = deger1.strftime('%d%m%Y') tar2 = deger2.strftime('%d%m%Y') tar3 = deger2.strftime('%B %Y') # if sys.platform=="win32": # tar3=unicode(tar3,'cp1254') # else: # tar3=unicode(tar3,'utf-8') self.wb = xlwt.Workbook(encoding="utf-8") self.dest_filename = "EKSTRE" + tar1 + tar2 + ".xls" date_format = xlwt.XFStyle() date_format.num_format_str = u'#,##0.00₺' date_xf = xlwt.easyxf(num_format_str='DD-MM-YYYY') self.ws1 = self.wb.add_sheet("ekstre") self.style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;') c = canvas.Canvas("EKSTRE" + tar1 + tar2 + ".pdf") pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf')) print(c.getAvailableFonts()) c.setFont("Verdana", 12) item = u"BISHOP CARİ BAKİYE LİSTESİ " + tar3 c.drawString(55, 815, item) c.setFont("Verdana", 8) item = "KOD FİRMA ADI " \ "BAKİYE " c.drawString(10, 800, item) tar1 = deger1.strftime('%Y-%m-%d') tar2 = deger2.strftime('%Y-%m-%d') sql = """select c2.cariid ,c2.cariad ,sum(c1.tutar) AS TUTAR from (cari_har c1 join cari c2) where ((c1.cariid = c2.cariid) and (c1.tarih >=%s ) and (c1.tarih <=%s ) and (c1.fistipi=10 or c1.fistipi=11)) and c2.cariad like %s group by c2.cariid,c2.cariad order by TUTAR DESC """ myddb1.conn.commit() bul2 = myddb1.cur.execute(sql, (tar1, tar2, firma)) print(bul2, tar1, tar2) bul = myddb1.cur.fetchall() i = bul2 self.tableWidget.setRowCount(i) aa = 0 bb = 0 toplam = 0.0 toplam1 = 0.0 toplam2 = 0.0000 for row1 in bul: if row1[2] < 1000 and self.checkBox.isChecked(): continue item = str(row1[0]) self.tableWidget.setItem(aa, 0, QtWidgets.QTableWidgetItem(item)) c.drawString(45, 800 - (15 * (bb + 1)), item) self.ws1.write(aa, 0, item) item = row1[1] c.drawString(80, 800 - (15 * (bb + 1)), item) self.ws1.write(aa, 1, item) self.tableWidget.setItem(aa, 1, QtWidgets.QTableWidgetItem(item)) item = str(row1[2]) toplam = toplam + float(row1[2]) self.tableWidget.setItem(aa, 2, QtWidgets.QTableWidgetItem(item)) c.drawRightString(380, 800 - (15 * (bb + 1)), "{:10.2f}".format(row1[2])) self.ws1.write(aa, 2, float(row1[2])) aa = aa + 1 bb = bb + 1 if (15 * (bb + 1)) >= 760: c.setFont("Verdana", 11) c.drawString(210, 800 - (15 * (bb + 1)), ".") c.drawString(320, 800 - (15 * (bb + 1)), str(toplam)) c.drawString(550, 800 - (15 * (bb + 1)), ".") c.showPage() c.setFont("Verdana", 8) bb = 0 self.tableWidget.setRowCount(aa + 2) font = QFont("Courier New", 11) self.tableWidget.setItem(aa + 1, 2, QtWidgets.QTableWidgetItem(str(toplam))) self.tableWidget.item(aa + 1, 2).setBackground(QColor(255, 128, 128)) self.tableWidget.item(aa + 1, 2).setFont(font) c.setFont("Verdana", 11) c.drawString(210, 800 - (15 * (bb + 1)), "Genel Toplam") c.drawString(320, 800 - (15 * (bb + 1)), str(toplam)) c.drawString(550, 800 - (15 * (bb + 1)), ".") self.ws1.write(aa + 1, 2, toplam) c.setFont("Courier", 60) # This next setting with make the text of our # watermark gray, nice touch for a watermark. c.setFillGray(0.3, 0.3) # Set up our watermark document. Our watermark # will be rotated 45 degrees from the direction # of our underlying document. c.saveState() c.translate(500, 100) c.rotate(45) c.drawCentredString(0, 0, "BISHOP NEN ©") c.drawCentredString(0, 300, "BISHOP NEN ©") c.drawCentredString(0, 600, "BISHOP NEN ©") c.restoreState() c.save() self.wb.save(self.dest_filename)
def createpdf(orders, fname, count): reportlab.rl_config.warnOnMissingFontGlyphs = 0 pdfmetrics.registerFont(TTFont('hei', 'simhei.ttf')) fonts.addMapping('hei', 0, 0, 'hei') fonts.addMapping('hei', 0, 1, 'hei') ts = [('FONT', (0, 0), (-1, -1), 'hei'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('LEFTPADDING', (0, 0), (-1, -1), 1), ('RIGHTPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('TOPPADDING', (0, 0), (-1, -1), 3), ('LINEABOVE', (0, 0), (-1, 1), 0.5, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 9)] ts2 = [('FONT', (0, 0), (-1, -1), 'hei'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('LEFTPADDING', (0, 0), (-1, -1), 1), ('RIGHTPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('TOPPADDING', (0, 0), (-1, -1), 3), ('FONTSIZE', (0, 0), (-1, -1), 9)] phdsize = setting.PeiHuoDanSize.split(';') #配货单打印尺寸设置 第一个数表示当前应用的是第几个尺寸 arrsize = phdsize[int(phdsize[0])].split(',') width = int(arrsize[0]) #285 height = int(arrsize[1]) #350 doc = SimpleDocTemplate('upload/' + fname, pagesize=(width, height), leftMargin=3, rightMargin=3, topMargin=8, bottomMargin=2) stylesheet = getSampleStyleSheet() stylesheet.add(ParagraphStyle(name='p', alignment=TA_JUSTIFY, fontSize=9)) stylesheet.add(ParagraphStyle(name='hh1', alignment=TA_CENTER, fontSize=18)) stylesheet.add( ParagraphStyle(name='td1', alignment=TA_JUSTIFY, fontSize=9, wordWrap='CJK')) stylesheet['hh1'].fontName = 'hei' stylesheet['p'].fontName = 'hei' stylesheet['td1'].fontName = 'hei' elements = [] for o in orders: elements.append(Paragraph('易 凡 网 配 货 单', stylesheet['hh1'])) elements.append(Spacer(1, 16)) title = [] title.append([ '订单号:' + str(o.ordernum), '日期:' + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(o.ordered))) ]) table = Table(title, (133, 133), 18, ts2) elements.append(table) elements.append(Spacer(1, 3)) data = [] data.append(['名称(规格)', '单价', '数量', '小计']) for item in o.items: if item.item_type == 2: gift = u'(积分换购)' elif item.item_type == 9: gift = u'(赠品)' else: gift = '' if item.product_standard_name: td = [ Paragraph( item.product.name + u'(' + item.product_standard_name + u')' + gift, stylesheet['td1']), item.price, item.quantity, item.quantity * item.price ] else: td = [ Paragraph( item.product.name + u'(' + item.product_standard.name + u')' + gift, stylesheet['td1']), item.price, item.quantity, item.quantity * item.price ] # styleTd = Paragraph(td[0], stylesheet['BodyText']) data.append(td) table = Table(data, (176, 30, 30, 30), 18, ts) elements.append(table) elements.append( flowables.Preformatted( '-----------------------------------------------------------', stylesheet['p'])) elements.append(Spacer(1, 3)) total = [] total.append( ['商品费用(元):' + str(o.price), '物流费用(元):' + str(o.shippingprice)]) total.append([ '本次优惠(元):' + str(o.price + o.shippingprice - o.currentprice), '合计(元):' + str(o.currentprice) ]) if o.payment == 0: collect_price = o.currentprice - o.pay_balance else: collect_price = 0 total.append( ['使用余额(元):' + str(o.pay_balance), '代收金额(元):' + str(collect_price)]) table2 = Table(total, (133, 133), 18, ts2) elements.append(table2) elements.append(Spacer(1, 3)) elements.append( flowables.Preformatted( '-----------------------------------------------------------', stylesheet['p'])) elements.append(Spacer(1, 3)) elements.append( flowables.Preformatted( u'客户:' + o.take_name + u' (' + o.take_tel + u')', stylesheet['p'])) elements.append(Spacer(1, 3)) elements.append( flowables.Preformatted(u'地址:' + o.take_address, stylesheet['p'])) elements.append(flowables.PageBreak()) doc.build(elements)
def generate_pdf(request, projectid): p = Projects.objects.get(id=projectid) phash = (hashlib.sha3_256('{0}{1}'.format( p.project_name, projectid).encode('utf-8')).hexdigest()) project = load_template(phash) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="ProjectReport.pdf"' pdfmetrics.registerFont(TTFont('SantanderTextW05-Regular', "./static/fonts/SantanderText-Regular.ttf")) pdfmetrics.registerFont(TTFont('SantanderTextW05-Bold', "./static/fonts/SantanderText-Bold.ttf")) buffer = BytesIO() p = canvas.Canvas(buffer) data = [[],[],[],[],[],['PROJECT REPORT']] #First eements to give a space for the logo image data.append([" "]) # Create the PDF object, using the BytesIO object as its "file." data.append(["•Project Owner:"]) data.append([" "+str(project['project_owner'])]) data.append(["•Project Name:"]) data.append([" "+str(project['project_name'])]) data.append(["•Project ID:"]) data.append([" "+str(project['project_id'])]) data.append(["•Project Description:"]) data.append([" "+str(project['project_description'])]) data.append(["•Project Created:"]) data.append([" "+str(add_one_hour(time.strftime("%m/%d/%Y %H:%M:%S",time.strptime(project['project_created'][:19], "%Y-%m-%dT%H:%M:%S"))))]) data.append(["•Project Level:"]) data.append([" "+str(project['project_level'])]) data.append([" "]) data.append(["COMPLETION"]) data.append([str(calculate_completion(project['requirements'])['percentage'])+"%"]) data.append([str(calculate_completion(project['requirements'])['enabled'])+"/"+str(calculate_completion(project['requirements'])['total'])]) data.append([" "]) data.append(["Requirements:"]) data.append([" "]) data.append([" "]) for r in project['requirements']: data.append([r['chapter_name']+":"]) data.append([" "]) split_description = chunkstring("("+r['req_id']+") "+r['req_description'], 123) for sd in split_description: data.append([sd]) if r.get('enabled') and r['enabled'] > 0: data.append([" "]) data.append(["Complete"]) if (len(r['note'])>0): data.append(['"'+str(r['note'])+'"']) data.append([" "]) elif r.get('disabled') and r['disabled'] > 0: data.append([" "]) data.append(["Incomplete"]) if (len(r['note'])>0): data.append(['"'+str(r['note'])+'"']) data.append([" "]) else: data.append([" "]) data.append(["N/A"]) if (len(r['note'])>0): data.append(['"'+str(r['note'])+'"']) data.append([" "]) if len(data) >= 40: pagenumber=0 for x in range(len(data)+1): if (((x % 40 == 0) and (x > 0)) or x == len(data)): smalldata = data[x-40:x] width = 800 height = 200 x = 20 y = 90 canvasBackground(p,"#E3FFFA") if pagenumber==0: detailsBackground(p,"#D3D3D3") p.drawImage('./static/img/logoicon3.jpg',227.5,730,width = 100, height = 100) p.drawImage('./static/img/logoicon3.jpg',530,40,width = 40, height =40) table_style = TableStyle([('FONTNAME', (0,0), (0,-1), 'SantanderTextW05-Regular')]) for row, values, in enumerate(smalldata): for column, value in enumerate(values): if (value=="PROJECT REPORT" or value=="Requirements:" or value=="•Project Owner:" or value=="•Project Name:" or value=="•Project ID:" or value=="•Project Description:" or value=="•Project Created:" or value=="•Project Level:"or value=="COMPLETION"): table_style.add('FONTNAME', (column, row), (column, row), 'SantanderTextW05-Bold') if (value=="COMPLETION" or value=="PROJECT REPORT"): table_style.add('ALIGN', (column, row), (column, row), "CENTRE") table_style.add('ALIGN', (column, row+1), (column, row+1), "CENTRE") table_style.add('SIZE', (column, row), (column, row), 12) if (value=="COMPLETION"): table_style.add('ALIGN', (column, row+2), (column, row+2), "CENTRE") if value == "Complete": table_style.add('TEXTCOLOR', (column, row), (column, row), "#49b675") if value == "Incomplete": table_style.add('TEXTCOLOR', (column, row), (column, row), "#e71837") if value == "N/A": table_style.add('TEXTCOLOR', (column, row), (column, row), "#0e4bef") if value.startswith("Architecture"): table_style.add('BACKGROUND', (column, row), (column, row), "#F6C2AE") if value.startswith("Authentication"): table_style.add('BACKGROUND', (column, row), (column, row), "#AEF6EE") if value.startswith("Session"): table_style.add('BACKGROUND', (column, row), (column, row), "#AECEF6") if value.startswith("Access"): table_style.add('BACKGROUND', (column, row), (column, row), "#F5F6AE") if value.startswith("Validation"): table_style.add('BACKGROUND', (column, row), (column, row), "#97E995") if value.startswith("Cryptography") or value.startswith("Stored Cryptography"): table_style.add('BACKGROUND', (column, row), (column, row), "#7CC4A5") if value.startswith("Error"): table_style.add('BACKGROUND', (column, row), (column, row), "#FF8282") if value.startswith("Data"): table_style.add('BACKGROUND', (column, row), (column, row), "#C290BA") if value.startswith("Communications"): table_style.add('BACKGROUND', (column, row), (column, row), "#6986A0") if value.startswith("Malicious"): table_style.add('BACKGROUND', (column, row), (column, row), "#AFBA7F") if value.startswith("BusLogic") or value.startswith("Business Logic"): table_style.add('BACKGROUND', (column, row), (column, row), "#FFB962") if value.startswith("Files") or value.startswith("File"): table_style.add('BACKGROUND', (column, row), (column, row), "#73E2D7") if value.startswith("API"): table_style.add('BACKGROUND', (column, row), (column, row), "#80DAAD") if value.startswith("Configuration"): table_style.add('BACKGROUND', (column, row), (column, row), "#CD0C2E") f = Table(smalldata,style=table_style) f.wrapOn(p, width, height) f.drawOn(p, x, y) p.showPage() pagenumber=pagenumber+1 else: width = 800 height = 200 x = 20 y = 767-17*len(data) canvasBackground(p,"#E3FFFA") detailsBackground(p,"#D3D3D3") p.drawImage('./static/img/logoicon3.jpg',530,40,width = 40, height =40) grid = [('FONTNAME', (0,0), (0,-1), 'SantanderTextW05-Regular')] f = Table(data,style=TableStyle(grid)) f.wrapOn(p, width, height) f.drawOn(p, x, y) p.showPage() p.save() # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def form_01(request_data): """ форма Пасопрт здоровья Приказ Министерства здравоохранения и социального развития РФ от 12 апреля 2011 г. N 302н """ ind_card = Card.objects.get(pk=request_data["card_pk"]) patient_data = ind_card.get_data_individual() work_data = patient_data['work_position'] work_data = work_data.split(';') work_department, work_position = "", "" if len(work_data) >= 2: work_department = work_data[1] if len(work_data) >= 1: work_position = work_data[0] else: work_position = work_data hospital: Hospitals = request_data["hospital"] hospital_name = hospital.title hospital_address = hospital.safe_address hospital_kod_ogrn = hospital.safe_ogrn health_passport_num = request_data["card_pk"] # номер id patient из базы list_result = [ 'Общ. анализ крови', 'Общ.анализ мочи', 'Глюкоза крови', 'Холестерин', 'RW', 'Флюорография', 'ЭКГ', 'Спирометрия', 'УЗИ м/желёз (маммогр.)', 'Аудиометрия', 'УЗИ огр.м/таза', 'Исслед. вестибулярн. аппарата', 'Исслед.вибрационн. чувствительности', 'Острота зрения', 'Рефрактометрия', 'Объём аккомодации', 'Исслед.бинокулярн. зрения', 'Цветоощущение', 'Офтальмотонометрия', 'Биомикроскопия сред глаза', 'Поля зрения', 'Бактериоскопия мазка', 'Офтальмоскопия глазного дня', 'Мазок из зева и носа', 'Ретикулоциты', 'АЛК или КП в моче', 'Метгемоглобины', 'Базальн. Зернист. Эритроцитов', ] # список лабораторных, инструментальных исследований list_doctor = [ 'Терапевт', 'Психиатр', 'Нарколог', 'Гинеколог', 'Офтальмолог', 'Лор', 'Невролог', 'Дерматолог', 'Хирург', 'Стоматолог' ] # список врачей-специалистов for i in range(0, 3): list_doctor.append('') if sys.platform == 'win32': locale.setlocale(locale.LC_ALL, 'rus_rus') else: locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') pdfmetrics.registerFont( TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=10 * mm, rightMargin=10 * mm, topMargin=10 * mm, bottomMargin=10 * mm, allowSplitting=1, title="Форма {}".format("Паспорт здоровья")) width, height = landscape(A4) styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifBold" style.fontSize = 9 style.leading = 6 styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" styleCenter = deepcopy(style) styleCenter.alignment = TA_CENTER styleCenter.leading = 1 styleCenterBold = deepcopy(styleBold) styleCenterBold.alignment = TA_CENTER styleCenterBold.leading = 10 styleJustified = deepcopy(style) styleJustified.alignment = TA_JUSTIFY styleJustified.spaceAfter = 4 * mm styleJustified.fontSize = 12 styleJustified.leading = 4.5 * mm righ_frame = Frame(148.5 * mm, 0 * mm, width=148.5 * mm, height=210 * mm, leftPadding=10 * mm, bottomPadding=6, rightPadding=10 * mm, topPadding=6, showBoundary=1) left_frame = Frame(0 * mm, 0 * mm, width=148.5 * mm, height=210 * mm, leftPadding=10 * mm, bottomPadding=6, rightPadding=10 * mm, topPadding=6, showBoundary=1) doc.addPageTemplates( PageTemplate(id='TwoCol', frames=[righ_frame, left_frame], pagesize=landscape(A4))) space = 5.5 * mm space_symbol = ' ' work_p = patient_data['work_place_db'] if patient_data[ 'work_place_db'] else patient_data['work_place'] objs = [ Spacer(1, 3 * mm), Paragraph( '<font face="PTAstraSerifBold">Министерство здравоохранения Российской Федерации</font>', styleCenter), Spacer(1, 5 * mm), Paragraph( '<font face="PTAstraSerifBold"><u>{}</u></font>'.format( hospital_name), styleCenterBold), Spacer(1, 1), Paragraph( '<font face="PTAstraSerifReg"><font size=9>(наименование медицинской организации)</font></font>', styleCenter), Spacer(1, 7 * mm), Paragraph( '<font face="PTAstraSerifBold"><u>{}</u></font>'.format( hospital_address), styleCenter), Spacer(1, 5 * mm), Paragraph( '<font face="PTAstraSerifBold" size=12>Код ОГРН {}</font>'.format( hospital_kod_ogrn), styleCenter), Spacer(1, 10 * mm), Paragraph( '<font face="PTAstraSerifBold" size=12>ПАСПОРТ ЗДОРОВЬЯ РАБОТНИКА № <u>{}</u></font>' .format(health_passport_num), styleCenter), Spacer(1, space), Paragraph( '<font face="PTAstraSerifReg"size=10><u>{} года</u></font>'.format( pytils.dt.ru_strftime(u"%d %B %Y", inflected=True, date=datetime.datetime.now())), styleCenter), Spacer(1, 3 * mm), Paragraph( '<font face="PTAstraSerifReg" size=7>(дата оформления)</font>', styleCenter), Spacer(1, space), Paragraph( '<font face="PTAstraSerifReg">1.Фамилия, имя, отчество:' '<u>{}</u> </font>'.format(patient_data['fio']), styleJustified), Paragraph( '<font face="PTAstraSerifReg">2.Пол: <u>{}</u> <img src="forms/img/FFFFFF-space.png" width="90" />' '3.Дата Рождения: <u>{}</u> </font>'.format( patient_data['sex'], patient_data['born']), styleJustified, ), Paragraph( '<font face="PTAstraSerifReg">4.Паспорт: серия <u>{}</u> <img src="forms/img/FFFFFF-space.png" width="25"/>' 'номер: <u>{}</u></font>'.format(patient_data['passport_serial'], patient_data['passport_num']), styleJustified, ), Paragraph( '<font face="PTAstraSerifReg">Дата выдачи: <u>{}</u></font>'. format(patient_data['passport_date_start']), styleJustified), Paragraph( '<font face="PTAstraSerifReg"> Кем Выдан: <u>{}</u></font>'.format( patient_data['passport_issued']), styleJustified), Paragraph( '<font face="PTAstraSerifReg">5. Адрес регистрации по месту жительства (пребывания):' ' <u>{}</u></font>'.format(patient_data['main_address']), styleJustified), Paragraph( '<font face="PTAstraSerifReg">6. Номер страхового полиса(ЕНП):' ' <u>{}</u></font>'.format(patient_data['oms']['polis_num']), styleJustified), Paragraph( '<font face="PTAstraSerifReg">7. Наименование работодателя:' ' <u>{}</u></font>'.format(work_p), styleJustified), Paragraph( '<font face="PTAstraSerifReg">7.1 Форма собственности и вид экономической деятельности ' 'работодателя по ОКВЭД: <u>{}</u></font>'.format( 50 * space_symbol), styleJustified), Paragraph( '<font face="PTAstraSerifReg">7.2 Наименование структурного подразделения (цех, участок, отдел):<u> {}</u></font>' .format(work_department), styleJustified), Paragraph( '<font face="PTAstraSerifReg">8. Профессия (должность) (в настоящее время):' ' <u>{}</u></font>'.format(work_position), styleJustified), FrameBreak(), Spacer(1, space), Paragraph('<font face="PTAstraSerifReg">12. Заключение:</font>', styleJustified), ] styleT = deepcopy(style) styleT.alignment = TA_CENTER styleT.fontSize = 10 styleT.leading = 4.5 * mm opinion = [ [ Paragraph( '<font face="PTAstraSerifReg">Заключение по результатам предварительного ' 'и периодического медицинского осмотра</font>', styleT), Paragraph( '<font face="PTAstraSerifReg">Дата получения заключения</font>', styleT), Paragraph( '<font face="PTAstraSerifReg"> Подпись профпатолога</font>', styleT), ], ] for i in range(0, 5): para = [ Paragraph( '<font face="PTAstraSerifReg" size=11>Профпригоден/\nпрофнепригоден</font>', styleT) ] opinion.append(para) tbl = Table( opinion, colWidths=(48 * mm, 40 * mm, 40 * mm), hAlign='LEFT', style=[ ('GRID', (0, 0), (-1, -1), 0.7, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TOPPADDING', (0, 0), (-1, -1), 1.5 * mm), ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm), ], ) objs.append(tbl) objs.append(Spacer(1, 10 * mm)) objs.append( Paragraph('<font face="PTAstraSerifReg">Для заметок:</font>', styleJustified)) s = "___________________________________________________________" for i in range(0, 6): objs.append(Spacer(1, 1 * mm)) objs.append( Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(s), styleJustified)) objs.append(NextPageTemplate("TwoCol")) objs.append(FrameBreak()) objs.append(Spacer(1, 7 * mm)) objs.append( Paragraph( '<font face="PTAstraSerifReg">11. Результаты лабораторных и инструментальных исследований' '</font>', styleJustified)) tbl_result = [ [ Paragraph( '<font face="PTAstraSerifReg" size=11>Вид исследования</font>', styleT), Paragraph( '<font face="PTAstraSerifReg" size=11>Даты исследований</font>', styleT), '', '', '', '', ], ['', '', '', '', '', ''], ] styleTR = deepcopy(styleT) styleTR.alignment = TA_LEFT styleTR.fontSize = 11 styleTR.spaceAfter = 12 * mm for i in list_result: para = [ Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(i), styleTR) ] tbl_result.append(para) tbl = Table( tbl_result, colWidths=(41 * mm, 22 * mm, 17 * mm, 17 * mm, 17 * mm, 17 * mm), hAlign='LEFT', style=[ ('GRID', (0, 0), (-1, -1), 0.7, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm), ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm), ('SPAN', (0, 0), (0, 1)), ('SPAN', (1, 0), (-1, 0)), ], ) objs.append(tbl) objs.append(FrameBreak()) objs.append(Spacer(1, 7 * mm)) objs.append( Paragraph( '<font face="PTAstraSerifReg">9. Условия труда в настоящее время</font>', styleJustified)) tbl_result = [[ Paragraph( '<font face="PTAstraSerifReg" size=10>Наименование производственного фактора, вида работы с ' 'указанием пункта</font>', styleT), Paragraph( '<font face="PTAstraSerifReg" size=10>Стаж работы с фактором</font>', styleT), ]] for i in range(0, 4): para = ['', ''] tbl_result.append(para) row_height = [] for i in tbl_result: row_height.append(8 * mm) row_height[0] = None tbl = Table( tbl_result, colWidths=(75 * mm, 55 * mm), rowHeights=row_height, hAlign='LEFT', style=[ ('GRID', (0, 0), (-1, -1), 0.7, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm), ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm), ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm), ('SPAN', (1, 1), (1, -1)), ], ) objs.append(tbl) objs.append(Spacer(1, 5 * mm)) styleDoc = deepcopy(styleJustified) styleDoc.spaceAfter = 1 * mm objs.append( Paragraph( '<font face="PTAstraSerifReg">10. Заключения врачей - специалистов:</font>', styleDoc, )) tbl_result = [ [ Paragraph( '<font face="PTAstraSerifReg" size=11>Врач-специалист</font>', styleT), Paragraph( '<font face="PTAstraSerifReg" size=11>Даты исследований</font>', styleT), '', '', '', '', ], ['', '', '', '', '', ''], ] for i in list_doctor: para = [ Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(i), styleTR) ] tbl_result.append(para) row_height = [] for i in tbl_result: row_height.append(9 * mm) row_height[0] = None row_height[1] = None tbl = Table( tbl_result, colWidths=(41 * mm, 22 * mm, 17 * mm, 17 * mm, 17 * mm, 17 * mm), rowHeights=row_height, hAlign='LEFT', style=[ ('GRID', (0, 0), (-1, -1), 0.7, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm), ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm), ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm), ('SPAN', (0, 0), (0, 1)), ('SPAN', (1, 0), (-1, 0)), ], ) objs.append(tbl) def first_pages(canvas, document): canvas.saveState() canvas.restoreState() def later_pages(canvas, document): canvas.saveState() canvas.restoreState() doc.build(objs, onFirstPage=first_pages, onLaterPages=later_pages) pdf = buffer.getvalue() buffer.close() return pdf
def drawimg(): global cursor c.drawImage(r"/home/thedamnchillguy/Desktop/Table Recognition/images/image"+str(random.randrange(1,5))+".jpg",0,cursor,100,200) cursor+=200+5 return cursor=0 pixel=0.24 inv=1/pixel FontsHeader=['Ubuntu-B','Ubuntu-Bo'] Fonts=['DejaVuSans','FreeMono','FreeSans','Ubuntu-L','Ubuntu-LI'] from django.conf import settings reportlab.rl_config.TTFSearchPath.append("/home/thedamnchillguy/Desktop/Table Recognition/fonts") for i in Fonts: pdfmetrics.registerFont(TTFont(i,i+'.ttf')) for i in FontsHeader: pdfmetrics.registerFont(TTFont(i,i+'.ttf')) numberdoc=int(input("How many documents do you want?")) n=1 exceed=noexceed=tableno=noofsentences=imageno=lineno=0 tabledoc=numberdoc while(n<=numberdoc): c=canvas.Canvas(r"/home/thedamnchillguy/Desktop/Table Recognition/pdf/"+str(n)+".pdf") cursor=t=0 pixel=0.24 border(random.uniform(0.25,0.5))
from reportlab.lib import colors, utils from reportlab.lib.units import mm from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.pagesizes import A4 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.barcode import code39 from reportlab.graphics.barcode import code128 from reportlab.lib.enums import TA_LEFT, TA_CENTER logger = logging.getLogger(__name__) pdfmetrics.registerFont(TTFont('Tahoma', settings.FONT_ROOT + 'Tahoma.ttf')) pdfmetrics.registerFont(TTFont('Garuda', settings.FONT_ROOT + 'Garuda.ttf')) logo_height = 70 class AckDocTemplate(BaseDocTemplate): id = 0 top_padding = 150 def __init__(self, filename, **kwargs): if "id" in kwargs: self.id = kwargs["id"] try: self.company = kwargs['company'] except KeyError:
#----------------------------------------------------------------------------------------------- # Se define la fechas para la cual se corre el informe #----------------------------------------------------------------------------------------------- str_semana = 'Semana: 14 de agosto hasta 20 de agosto de 2017' #----------------------------------------------------------------------------------------------- # Parametros necesarios para hacer el reporte #----------------------------------------------------------------------------------------------- path_elem = '/home/atlas/informe_hidromet/20170821/' path_reps = '/home/atlas/informe_hidromet/20170821/informe/' # Se define el tipo de letra con el que se va a trabjar # en este caso sera Avenir. barcode_font = path_reps+'avenir/AvenirLTStd-Roman.ttf' pdfmetrics.registerFont(TTFont("Avenir", barcode_font)) barcode_font_blk = path_reps+'avenir/AvenirLTStd-Black.ttf' pdfmetrics.registerFont(TTFont("Avenir_blk", barcode_font_blk)) # Se define el RGB de los colores a utilizar color_RGB1 = [34, 71, 94] # Azul franja principal superior color_RGB2 = [9, 32, 46] # Azul del banner de los logos y logos siata color_RGB3 = [31, 115, 116] # Banda pequeña azul claro color_RGB4 = [55, 123, 148] gris70 = (112/255., 111/255., 111/255.) ColorInfo1 = (82 /255., 183/255.,196/255.) ColorInfo2 = (55 /255., 123/255.,148/255.) ColorInfo3 = (43 /255., 72/255.,105/255.) ColorInfo4 = (32 /255., 34/255., 72/255.) ColorInfo5 = (34 /255., 71/255., 94/255.) ColorInfo6 = (31 /255., 115/255.,116/255.) ColorInfo7 = (39 /255., 165/255.,132/255.)
from PyPDF2 import PdfFileWriter, PdfFileReader import io import xlrd from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont # Adding custom fonts. 1st parm is the name of the font and 2nd is the path to the ttf font file. pdfmetrics.registerFont(TTFont('Roboto', 'RobotoMono-Medium.ttf')) pdfmetrics.registerFont(TTFont('RobotoL', 'RobotoMono-Light.ttf')) #packet = io.BytesIO() # Function to return a pdf page with the parameters added into it. def createpage(name): packet = io.BytesIO() can = canvas.Canvas(packet) #can.setFont('Roboto', 70) # Setting the font and size of text. #can.drawString(300, 925, name) # Drawing a string onto the page. (x, y, string) #can.setFont('RobotoL', 48) #can.drawString(160, 290, name) #can.drawString(2110, 785, seat) #can.drawString(2110, 648, food.upper()) #if cusat=="cusat": # can.drawString(2110,510,"CUSAT") #can.drawInlineImage("image.jpg",1560,270,)
import io from django.conf import settings from plantilla_reporte.funciones.funciones import insert_data_pdf, texto_pdf from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas from django.http import HttpResponse from reportlab.pdfbase.pdfmetrics import registerFont from reportlab.pdfbase.ttfonts import TTFont from datetime import datetime registerFont(TTFont('Arial', 'Arial.ttf')) def reporte(request, datos, nombre): ##Esta data nosotros la generaremos con django serán las consultas # esta siendo generado aleatoriamente todo lo saqué de un ejemplo de inter y lo fui modificando data = [("Fecha", "Usuario", "Acciones")] # Este es el encabezado for i in datos: data.append( ('{}'.format(datetime.strftime(i.fecha, '%d/%m/%Y')), i.usuario, i.accion)) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename={}.pdf'.format( nombre) buffer = io.BytesIO() c = canvas.Canvas(buffer, pagesize=A4) w, h = A4 max_rows_per_page = 25 #Aquí ponemos cuantos registros queremos por páginas # Margin. x_offset = 50
def exportPDF(request, slug): """Exports recipes to a pdf""" pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf')) pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf')) pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf')) pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf')) registerFontFamily('Vera', normal='Vera', bold='VeraBd', italic='VeraIt', boldItalic='VeraBI') recipe = get_object_or_404(Recipe, slug=slug) # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(mimetype='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=' + recipe.slug + '.pdf' # Our container for 'Flowable' objects elements = [] # set up our styles styles = getSampleStyleSheet() styleH1 = styles['Heading1'] styleH1.textColor = colors.green styleH1.fontName = 'VeraBd' styleH2 = styles['Heading2'] styleH2.textColor = colors.goldenrod styleH2.fontName = 'Vera' styleNormal = styles['Normal'] styleNormal.fontName = 'Vera' styleBullet = styles['Bullet'] styleBullet.fontName = 'VeraIt' # create the pdf doc doc = SimpleDocTemplate(response) # set the openeats logo logo = settings.STATIC_ROOT + "/" + settings.OELOGO I = Image(logo) I.hAlign = 'LEFT' elements.append(I) elements.append(Spacer(0, 1 * cm)) # add the recipe photo if the recipe has one if recipe.photo: photo = settings.BASE_PATH + recipe.photo.url I = Image(photo) I.height = "CENTER" elements.append(I) elements.append(Spacer(0, 0.5 * cm)) # add the meat of the pdf elements.append(Paragraph(recipe.title, styleH1)) elements.append(Paragraph('info', styleH2)) elements.append(Paragraph(recipe.info, styleNormal)) elements.append(Paragraph('ingredients', styleH2)) for ing in recipe.ingredients.all(): ing = "%s %s %s %s" % (ing.quantity, ing.measurement, ing.title, ing.preparation) elements.append(Paragraph(ing, styleBullet)) elements.append(Paragraph('directions', styleH2)) elements.append(Paragraph(recipe.directions, styleNormal)) # build the pdf and return it doc.build(elements) return response
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfdoc from django.conf import settings from django.utils import translation from django.utils.translation import ugettext as _ from zeus.core import PARTY_SEPARATOR from stv.parser import STVParser PAGE_WIDTH, PAGE_HEIGHT = A4 default_path = '/usr/share/fonts/truetype/linux-libertine/LinLibertine_Re.ttf' linlibertine = TTFont( 'LinLibertine', # '/Users/Panos/Library/Fonts/LinLibertine_Rah.ttf') getattr(settings, 'ZEUS_RESULTS_FONT_REGULAR_PATH', default_path)) pdfmetrics.registerFont(linlibertine) default_path = '/usr/share/fonts/truetype/linux-libertine/LinLibertine_Bd.ttf' linlibertineb = TTFont( 'LinLibertineBd', # '/Users/Panos/Library/Fonts/LinLibertine_RBah.ttf') getattr(settings, 'ZEUS_RESULTS_FONT_BOLD_PATH', default_path)) pdfmetrics.registerFont(linlibertineb) ZEUS_LOGO = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logo-positive.jpg') def load_results(data, repr_data, qdata):
# -*- coding: utf-8 -*- import datetime import os from django.conf import settings from django.utils.translation.trans_real import translation from reportlab.pdfgen import canvas from reportlab.lib.units import cm from reportlab.lib.pagesizes import A4, landscape from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont CURRENT_DIR = os.path.realpath(os.path.dirname(__file__)) FONT_FILE = os.path.join(CURRENT_DIR, 'Arial.ttf') pdfmetrics.registerFont(TTFont("Arial", FONT_FILE)) ### Variables ### width, height = landscape(A4) # width and height of A4 Landscape format marginX, marginY = 0, 0 titleX, titleY = 3.57 * cm + 100, 9.95 * cm + 100 nameX, nameY = 2.17 * cm + 100, 7.71 * cm + 100 mainContentX, mainContentY = 2.17 * cm + 100, 7.04 * cm + 100 dateX, dateY = 2.17 * cm + 100, 3.74 * cm + 100
def test1(self): "This makes one long multi-page paragraph." # Build story. story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] bt = styleSheet['BodyText'] text = '''If you imagine that the box of X's tothe left is an image, what I want to be able to do is flow a series of paragraphs around the image so that once the bottom of the image is reached, then text will flow back to the left margin. I know that it would be possible to something like this using tables, but I can't see how to have a generic solution. There are two examples of this in the demonstration section of the reportlab site. If you look at the "minimal" euro python conference brochure, at the end of the timetable section (page 8), there are adverts for "AdSu" and "O'Reilly". I can see how the AdSu one might be done generically, but the O'Reilly, unsure... I guess I'm hoping that I've missed something, and that it's actually easy to do using platypus.We can do greek letters <greek>mDngG</greek>. This should be a u with a dieresis on top <unichar code=0xfc/>="<unichar code="0xfc"/>" and this &#xfc;="ü" and this \\xc3\\xbc="\xc3\xbc". On the other hand this should be a pound sign &pound;="£" and this an alpha &alpha;="α". You can have links in the page <link href="http://www.reportlab.com" color="blue">ReportLab</link> & <a href="http://www.reportlab.org" color="green">ReportLab.org</a>. Use scheme "pdf:" to indicate an external PDF link, "http:", "https:" to indicate an external link eg something to open in your browser. If an internal link begins with something that looks like a scheme, precede with "document:". Empty hrefs should be allowed ie <a href=""><a href="">test</a></a> should be allowed. <strike>This text should have a strike through it.</strike> ''' from reportlab.platypus.flowables import ImageAndFlowables, Image gif = os.path.join(testsFolder, 'pythonpowered.gif') heading = Paragraph('This is a heading', h3) story.append( ImageAndFlowables(Image(gif), [heading, Paragraph(text, bt)])) phrase = 'This should be a paragraph spanning at least three pages. ' description = ''.join([('%d: ' % i) + phrase for i in range(250)]) story.append( ImageAndFlowables(Image(gif), [heading, Paragraph(description, bt)], imageSide='left')) story.append(NextPageTemplate('special')) story.append(PageBreak()) VERA = ('Vera', 'VeraBd', 'VeraIt', 'VeraBI') for v in VERA: registerFont(TTFont(v, v + '.ttf')) registerFontFamily(*(VERA[:1] + VERA)) story.append( ImageAndFlowables( Image(gif, width=280, height=120), Paragraph( '''<font name="Vera">The <b>concept</b> of an <i>integrated</i> one <b><i>box</i></b> solution for <i><b>advanced</b></i> voice and data applications began with the introduction of the IMACS. The IMACS 200 carries on that tradition with an integrated solution optimized for smaller port size applications that the IMACS could not economically address. An array of the most popular interfaces and features from the IMACS has been bundled into a small 2U chassis providing the ultimate in ease of installation.</font>''', style=ParagraphStyle( name="base", fontName="Helvetica", leading=12, leftIndent=0, firstLineIndent=0, spaceBefore=9.5, fontSize=9.5, )), imageSide='left', )) story.append( ImageAndFlowables( Image(gif, width=240, height=120), Paragraph( '''The concept of an integrated one box solution for advanced voice and data applications began with the introduction of the IMACS. The IMACS 200 carries on that tradition with an integrated solution optimized for smaller port size applications that the IMACS could not economically address. An array of the most popular interfaces and features from the IMACS has been bundled into a small 2U chassis providing the ultimate in ease of installation.''', style=ParagraphStyle( name="base", fontName="Helvetica", leading=12, leftIndent=0, firstLineIndent=0, spaceBefore=9.5, fontSize=9.5, )), imageSide='left', )) story.append(PageBreak()) story.append(Paragraph('Image larger than the frame', h3)) story.append( ImageAndFlowables( Image(gif, width=6 * 110, height=6 * 44), Paragraph( '''The concept of an integrated one box solution for advanced voice and data applications began with the introduction of the IMACS. The IMACS 200 carries on that tradition with an integrated solution optimized for smaller port size applications that the IMACS could not economically address. An array of the most popular interfaces and features from the IMACS has been bundled into a small 2U chassis providing the ultimate in ease of installation.''', style=ParagraphStyle( name="base", fontName="Helvetica", leading=12, leftIndent=0, firstLineIndent=0, spaceBefore=9.5, fontSize=9.5, )), imageSide='left', )) text = '''With this clarification, an important property of these three types of EC can be defined in such a way as to impose problems of phonemic and morphological analysis. Another superficial similarity is the interest in simulation of behavior, this analysis of a formative as a pair of sets of features does not readily tolerate a stipulation to place the constructions into these various categories. We will bring evidence in favor of the following thesis: the earlier discussion of deviance is not to be considered in determining the extended c-command discussed in connection with (34). Another superficial similarity is the interest in simulation of behavior, relational information may remedy and, at the same time, eliminate a descriptive fact. There is also a different approach to the [unification] problem, the descriptive power of the base component delimits the traditional practice of grammarians.''' from reportlab.platypus.flowables import ImageAndFlowables, Image gif = os.path.join(testsFolder, 'pythonpowered.gif') heading = Paragraph('This is a heading', h3) story.append(NextPageTemplate('template2')) story.append(PageBreak()) story.append(heading) story.append( ImageAndFlowables(Image(gif, width=66, height=81), [Paragraph(text, bt)], imageSide='left', imageRightPadding=10)) doc = MyDocTemplate(outputfile('test_platypus_imageandflowables.pdf'), showBoundary=1) #raise AssertionError("This test just hangs with Wordaxe NewParagraph class!") doc.multiBuild(story)
def slotekstre(self, item, item2): if self.kontrol == 0: fisno = self.tableWidget.item(item, 0).text() self.my_signal.emit(fisno) return myddb1 = Myddb() carikod = self.tableWidget.item(item, 0).text() self.logger.info("caribakiye listesi " + self.tableWidget.item(item, 1).text()) print("ekstrerapor") self.tableWidget.clearContents() self.tableWidget.setColumnWidth(0, 60) self.tableWidget.setColumnWidth(1, 100) self.tableWidget.setColumnWidth(2, 200) self.tableWidget.setColumnWidth(3, 75) self.tableWidget.setColumnWidth(4, 75) self.tableWidget.setColumnWidth(5, 75) deger1 = self.dateEdit.date().toPyDate() deger2 = self.dateEdit_2.date().toPyDate() tar1 = deger1.strftime('%d%m%Y') tar2 = deger2.strftime('%d%m%Y') self.wb = xlwt.Workbook(encoding="utf-8") self.dest_filename = "EKSTRE" + tar1 + tar2 + ".xls" date_format = xlwt.XFStyle() date_format.num_format_str = u'#,##0.00₺' date_xf = xlwt.easyxf(num_format_str='DD/MM/YYYY') self.ws1 = self.wb.add_sheet("ekstre") self.style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;') c = canvas.Canvas("EKSTRE" + tar1 + tar2 + ".pdf") pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf')) c.setFont("Verdana", 8) item = "FİŞ NO TARİH AÇIKLAMA BORÇ ALACAK " \ " BAKİYE " c.drawString(10, 810, item) tar1 = deger1.strftime('%Y-%m-%d') tar2 = deger2.strftime('%Y-%m-%d') sql = """select `c1`.`fistipi`,`c1`.`tarih` AS `tarih`,`c1`.`fisno` AS `fisno`,concat(`c1`.`serino`,'_', `c1`.`sirano`,' nolu '), `c1`.`tutar` AS `TUTAR` from (`cari_har` `c1` join `cari` `c2`) where (( `c1`.`cariid` = `c2`.`cariid`) and (`c1`.`cariid`=%s) and (`c1`.`tarih` >=%s ) and (`c1`.`tarih` <=%s ) and (`c1`.`fistipi`=10 or `c1`.`fistipi`=11)) order by `c1`.`tarih`,`c1`.`fisno` asc """ bul2 = myddb1.cur.execute(sql, (carikod, tar1, tar2)) print(bul2, tar1, tar2) bul = myddb1.cur.fetchall() i = bul2 j = 5 self.tableWidget.setRowCount(i) aa = 0 bb = 0 dep = 0 toplam = 0.0 toplam1 = 0.0 toplam2 = 0.0000 for row1 in bul: item = str(row1[2]) self.ws1.write(aa, 0, item) self.tableWidget.setItem(aa, 0, QtWidgets.QTableWidgetItem(item)) c.drawString(45, 800 - (15 * (bb + 1)), item) item = (row1[1]).strftime("%d-%m-%Y") self.ws1.write(aa, 1, item) c.drawString(80, 800 - (15 * (bb + 1)), item) self.tableWidget.setItem(aa, 1, QtWidgets.QTableWidgetItem(item)) if row1[0] == 10: item = str(row1[3]) + "Fatura " self.ws1.write(aa, 2, item) self.tableWidget.setItem(aa, 2, QtWidgets.QTableWidgetItem(item)) c.drawString(150, 800 - (15 * (bb + 1)), item) if row1[4] is None: item = "0" else: item = str(row1[4]) self.ws1.write(aa, 3, float(item)) c.drawRightString(310, 800 - (15 * (bb + 1)), item) toplam = toplam + float(item) toplam2 = Decimal(toplam2) + (Decimal(item)) self.tableWidget.setItem(aa, 3, QtWidgets.QTableWidgetItem(item)) item = "" c.drawRightString(390, 800 - (15 * (bb + 1)), item) self.tableWidget.setItem(aa, 4, QtWidgets.QTableWidgetItem(item)) if row1[0] == 11: item = row1[3] + u" Ödeme" self.ws1.write(aa, 2, item) self.tableWidget.setItem(aa, 2, QtWidgets.QTableWidgetItem(item)) c.drawString(150, 800 - (15 * (bb + 1)), item) if row1[4] is None: item = "0" else: item = str(row1[4]) self.ws1.write(aa, 4, float(item)) c.drawString(350, 800 - (15 * (bb + 1)), item) toplam1 = toplam1 + float(item) toplam2 = Decimal(toplam2) + (Decimal(item)) self.tableWidget.setItem(aa, 4, QtWidgets.QTableWidgetItem(item)) item = "" c.drawString(270, 800 - (15 * (bb + 1)), item) self.tableWidget.setItem(aa, 3, QtWidgets.QTableWidgetItem(item)) item = str(toplam2) self.ws1.write(aa, 5, toplam2) self.tableWidget.setItem(aa, 5, QtWidgets.QTableWidgetItem(item)) c.drawRightString(470, 800 - (15 * (bb + 1)), str(toplam2)) aa = aa + 1 bb = bb + 1 if (15 * (bb + 1)) >= 760: c.setFont("Verdana", 10) c.drawString(210, 800 - (15 * (bb + 1)), "{:10.2f}".format((toplam))) c.drawString(270, 800 - (15 * (bb + 1)), "{:10.2f}".format((toplam1))) c.drawString(350, 800 - (15 * (bb + 1)), "{:10.2f}".format((toplam2))) c.showPage() c.setFont("Verdana", 8) bb = 0 c.setFont("Verdana", 10) self.ws1.write(aa + 1, 3, toplam) self.ws1.write(aa + 1, 4, toplam1) self.ws1.write(aa + 1, 5, toplam2) c.drawString(270, 800 - (15 * (bb + 1)), "{:10.2f}".format((toplam))) c.drawString(350, 800 - (15 * (bb + 1)), "{:10.2f}".format((toplam1))) c.drawString(430, 800 - (15 * (bb + 1)), "{:10.2f}".format((toplam2))) # todo genel toplam yazılacak c.setFont("Courier", 60) # This next setting with make the text of our # watermark gray, nice touch for a watermark. c.setFillGray(0.3, 0.3) # Set up our watermark document. Our watermark # will be rotated 45 degrees from the direction # of our underlying document. c.saveState() c.translate(500, 100) c.rotate(45) c.drawCentredString(0, 0, "BISHOP NEN ©") c.drawCentredString(0, 300, "BISHOP NEN ©") c.drawCentredString(0, 600, "BISHOP NEN ©") c.restoreState() c.save() self.wb.save(self.dest_filename) self.kontrol = 0
def form_01(request_data): """ Ведомость статталонов по амбулаторным приемам. Входные параметры врач, дата. Выходные: форма """ doc_confirm = request_data['user'].doctorprofile req_date = request_data['date'] str_date = json.loads(req_date) date_confirm = datetime.datetime.strptime(str_date, "%d.%m.%Y") doc_results = get_doc_results(doc_confirm, date_confirm) data_talon = get_finaldata_talon(doc_results) pdfmetrics.registerFont( TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) pdfmetrics.registerFont( TTFont('Symbola', os.path.join(FONTS_FOLDER, 'Symbola.ttf'))) buffer = BytesIO() doc = SimpleDocTemplate( buffer, pagesize=landscape(A4), leftMargin=12 * mm, rightMargin=5 * mm, topMargin=25 * mm, bottomMargin=28 * mm, allowSplitting=1, title="Форма {}".format("Ведомость по статталонам")) styleSheet = getSampleStyleSheet() styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 9 style.leading = 12 style.spaceAfter = 0 * mm style.alignment = TA_JUSTIFY style.firstLineIndent = 15 styleFL = deepcopy(style) styleFL.firstLineIndent = 0 styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" styleBold.fontSize = 11 styleBold.alignment = TA_LEFT styleBold.firstLineIndent = 0 styleCenter = deepcopy(style) styleCenter.alignment = TA_CENTER styleCenter.fontSize = 9 styleCenter.leading = 10 styleCenter.spaceAfter = 0 * mm styleCenterBold = deepcopy(styleBold) styleCenterBold.alignment = TA_CENTER styleCenterBold.fontSize = 14 styleCenterBold.leading = 15 styleCenterBold.face = 'PTAstraSerifBold' styleJustified = deepcopy(style) styleJustified.alignment = TA_JUSTIFY styleJustified.spaceAfter = 4.5 * mm styleJustified.fontSize = 12 styleJustified.leading = 4.5 * mm objs = [] objs.append(Spacer(1, 1 * mm)) styleT = deepcopy(style) styleT.alignment = TA_LEFT styleT.firstLineIndent = 0 styleT.fontSize = 9 param = request_data.get('param', '0') == '1' if param: title = 'Ведомость статистических талонов по услугам пациентов' opinion = [[ Paragraph('№ п.п.', styleT), Paragraph('ФИО пациента, дата рождени', styleT), Paragraph('Дата осмотра,   №', styleT), Paragraph('№ карты', styleT), Paragraph('Данные полиса', styleT), Paragraph('Код услуги', styleT), Paragraph('Наименование услуги', styleT), ]] else: title = 'Ведомость статистических талонов по посещениям пациентов' opinion = [[ Paragraph('№ п.п.', styleT), Paragraph('ФИО пациента, дата рождения ', styleT), Paragraph('Дата осмотра,   №', styleT), Paragraph('№ карты', styleT), Paragraph('Данные полиса', styleT), Paragraph('Цель посещения (код)', styleT), Paragraph('Первичный прием', styleT), Paragraph('Диагноз МКБ', styleT), Paragraph('Впервые', styleT), Paragraph('Результат обращения (код)', styleT), Paragraph('Исход (код)', styleT), Paragraph('Д-учет<br/>Стоит', styleT), Paragraph('Д-учет<br/>Взят', styleT), Paragraph('Д-учет<br/>Снят', styleT), Paragraph('Причина снятия', styleT), Paragraph('Онко<br/> подозрение', styleT), ]] new_page = False list_g = [] if param: talon = data_talon[1] else: talon = data_talon[0] for k, v in talon.items(): if len(talon.get(k)) == 0: continue if new_page: objs.append(PageBreak()) objs.append( Paragraph('Источник финансирования - {}'.format(str(k).upper()), styleBold)) objs.append(Spacer(1, 1.5 * mm)) t_opinion = opinion.copy() for u, s in v.items(): list_t = [Paragraph(str(u), styleT)] for t, q in s.items(): list_t.append(Paragraph(str(q).replace("\n", "<br/>"), styleT)) list_g.append(list_t) t_opinion.extend(list_g) if param: tbl = Table( t_opinion, colWidths=( 10 * mm, 60 * mm, 19 * mm, 15 * mm, 75 * mm, 30 * mm, 70 * mm, ), ) else: tbl = Table(t_opinion, colWidths=(10 * mm, 30 * mm, 19 * mm, 15 * mm, 46 * mm, 20 * mm, 10 * mm, 13 * mm, 11 * mm, 20 * mm, 18 * mm, 16 * mm, 14 * mm, 14 * mm, 17 * mm, 13 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BOTTOMPADDING', (0, 0), (-1, -1), 1 * mm), ])) objs.append(tbl) new_page = True list_g = [] styleTatr = deepcopy(style) styleTatr.alignment = TA_LEFT styleTatr.firstLineIndent = 0 styleTatr.fontSize = 11 opinion = [ [ Paragraph('ФИО врача:', styleTatr), Paragraph('{}'.format(doc_confirm.get_full_fio()), styleTatr), Paragraph('{}'.format(date_confirm.strftime('%d.%m.%Y')), styleTatr) ], [ Paragraph('Специальность:', styleTatr), Paragraph('{}'.format(doc_confirm.specialities), styleTatr), Paragraph('', styleTatr) ], ] def later_pages(canvas, document): canvas.saveState() # вывести Название и данные врача width, height = landscape(A4) canvas.setFont('PTAstraSerifBold', 14) canvas.drawString(99 * mm, 200 * mm, '{}'.format(title)) tbl = Table(opinion, colWidths=(35 * mm, 220 * mm, 25 * mm), rowHeights=(5 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.white), ('BOTTOMPADDING', (0, 0), (-1, -1), 1 * mm), ])) tbl.wrapOn(canvas, width, height) tbl.drawOn(canvas, 30, 530) canvas.restoreState() doc.build( objs, onFirstPage=later_pages, onLaterPages=later_pages, ) pdf = buffer.getvalue() buffer.close() return pdf