コード例 #1
0
ファイル: report1.py プロジェクト: my291178/PDF
 def _set_registerFont(self):
     Times_New_Roman = ttfonts.TTFont('Times New Roman', PATH + "times.ttf")
     pdfmetrics.registerFont(Times_New_Roman)
     #
     Times_New_Roman_Bold = ttfonts.TTFont('Times New Roman Bold',
                                           PATH + "timesbd.ttf")
     pdfmetrics.registerFont(Times_New_Roman_Bold)
コード例 #2
0
def _setup():
    from reportlab.pdfbase import pdfmetrics, ttfonts
    pdfmetrics.registerFont(ttfonts.TTFont("Vera", "Vera.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraBd", "VeraBd.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraIt", "VeraIt.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraBI", "VeraBI.ttf"))
    F = ['Times-Roman','Courier','Helvetica','Vera', 'VeraBd', 'VeraIt', 'VeraBI']
    if sys.platform=='win32':
        for name, ttf in [
            ('Adventurer Light SF','Advlit.ttf'),('ArialMS','ARIAL.TTF'),
            ('Arial Unicode MS', 'ARIALUNI.TTF'),
            ('Book Antiqua','BKANT.TTF'),
            ('Century Gothic','GOTHIC.TTF'),
            ('Comic Sans MS', 'COMIC.TTF'),
            ('Elementary Heavy SF Bold','Vwagh.ttf'),
            ('Firenze SF','flot.ttf'),
            ('Garamond','GARA.TTF'),
            ('Jagger','Rols.ttf'),
            ('Monotype Corsiva','MTCORSVA.TTF'),
            ('Seabird SF','seag.ttf'),
            ('Tahoma','TAHOMA.TTF'),
            ('VerdanaMS','VERDANA.TTF'),
            ]:
            for D in (r'c:\WINNT',r'c:\Windows'):
                fn = os.path.join(D,'Fonts',ttf)
                if os.path.isfile(fn):
                    try:
                        f = ttfonts.TTFont(name, fn)
                        pdfmetrics.registerFont(f)
                        F.append(name)
                    except:
                        pass
    return F
コード例 #3
0
ファイル: rml2pdf.py プロジェクト: TNT1314/site_salary
    def __init__(self, font_dir=None, static_dir=None):
        """
            构造方法
            @param font_dir 需要注册的字体文件目录
            @param static_dir 静态文件地址目录
        """

        super(RmlPdfUtils, self).__init__()
        font_dir = "{}/pdf_fonts".format(os.path.split(os.path.realpath(__file__))[0])
        self.statics_dir = static_dir

        try:
            # 注册宋体字体
            pdfmetrics.registerFont(ttfonts.TTFont('song', os.path.join(font_dir, 'STSONG.TTF')))
            # 注册宋体粗体字体
            pdfmetrics.registerFont(ttfonts.TTFont('song_b', os.path.join(font_dir, 'STZHONGS.TTF')))
        except Exception as e:
            logging.error(e)
            logging.error(traceback.format_exc())

        addMapping('song', 0, 0, 'song')     # normal
        addMapping('song', 0, 1, 'song')     # italic
        addMapping('song', 1, 1, 'song_b')   # bold, italic
        addMapping('song', 1, 0, 'song_b')   # bold

        # 设置自动换行
        reportlab.lib.styles.ParagraphStyle.defaults['wordWrap'] = "CJK"
コード例 #4
0
def draw_recent_week_pdf(filename, data_list):
    """
    画最近七天的流量计报表
    :param filename:
    :param data_list
    :return:
    """
    data = []
    max_val = 0
    for index in range(0, len(data_list)):
        data.append((index + 1, data_list[index]))
        max_val = max(max_val, data_list[index])

    drawing = Drawing(500, 800)
    lp = LinePlot()
    lp.x = 50
    lp.y = 80
    lp.height = 600
    lp.width = 400
    lp.data = [data]
    lp.joinedLines = 1
    lp.lines.symbol = makeMarker('FilledCircle')
    lp.xValueAxis.valueMin = 1
    lp.xValueAxis.valueMax = 7
    lp.xValueAxis.valueStep = 1
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = (int(max_val / 100) + 1) * 100
    lp.yValueAxis.valueStep = 100
    drawing.add(lp)

    x_title = Label()
    # 若需要显示中文,需要先注册一个中文字体
    pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc"))
    x_title.fontName = "haha"
    x_title.fontSize = 12
    title_text = '用气量'
    x_title._text = title_text
    x_title.x = 20
    x_title.y = 100
    x_title.textAnchor = 'middle'
    drawing.add(x_title)

    y_title = Label()
    # 若需要显示中文,需要先注册一个中文字体
    pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc"))
    y_title.fontName = "haha"
    y_title.fontSize = 12
    title_text = '最近七天'
    y_title._text = title_text
    y_title.x = 80
    y_title.y = 50
    y_title.textAnchor = 'middle'
    drawing.add(y_title)
    drawing.save(formats=['pdf'],
                 outDir=TMP_FILE_DIRECTORY_PATH,
                 fnRoot=filename)
コード例 #5
0
def getDrawing13():
    'Test Various TTF Fonts'
    from reportlab.pdfbase import pdfmetrics, ttfonts
    pdfmetrics.registerFont(ttfonts.TTFont("Vera", "Vera.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraBd", "VeraBd.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraIt", "VeraIt.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraBI", "VeraBI.ttf"))
    _FONTS[1]='Vera'
    _FONTS[1]='VeraBI'
    F = ['Times-Roman','Courier','Helvetica','Vera', 'VeraBd', 'VeraIt', 'VeraBI']
    if sys.platform=='win32':
        for name, ttf in [
            ('Adventurer Light SF','Advlit.ttf'),('ArialMS','ARIAL.TTF'),
            ('Arial Unicode MS', 'ARIALUNI.TTF'),
            ('Book Antiqua','BKANT.TTF'),
            ('Century Gothic','GOTHIC.TTF'),
            ('Comic Sans MS', 'COMIC.TTF'),
            ('Elementary Heavy SF Bold','Vwagh.ttf'),
            ('Firenze SF','flot.ttf'),
            ('Garamond','GARA.TTF'),
            ('Jagger','Rols.ttf'),
            ('Monotype Corsiva','MTCORSVA.TTF'),
            ('Seabird SF','seag.ttf'),
            ('Tahoma','TAHOMA.TTF'),
            ('VerdanaMS','VERDANA.TTF'),
            ]:
            for D in ('c:\WINNT','c:\Windows'):
                fn = os.path.join(D,'Fonts',ttf)
                if os.path.isfile(fn):
                    try:
                        f = ttfonts.TTFont(name, fn)
                        pdfmetrics.registerFont(f)
                        F.append(name)
                    except:
                        pass

    def drawit(F,w=400,h=200,fontSize=12,slack=2,gap=5):
        D = Drawing(w,h)
        th = 2*gap + fontSize*1.2
        gh = gap + .2*fontSize
        y = h
        maxx = 0
        for fontName in F:
            y -= th
            text = fontName+": I should be totally horizontal and enclosed in a box and end in alphabetagamma \xc2\xa2\xc2\xa9\xc2\xae\xc2\xa3\xca\xa5\xd0\x96\xd6\x83\xd7\x90\xd9\x82\xe0\xa6\x95\xce\xb1\xce\xb2\xce\xb3"
            textWidth = stringWidth(text, fontName, fontSize)
            maxx = max(maxx,textWidth+20)
            D.add(
                Group(Rect(8, y-gh, textWidth + 4, th, strokeColor=colors.red, strokeWidth=.5, fillColor=colors.lightgrey),
                    String(10, y, text, fontName=fontName, fontSize = fontSize)))
            y -= 5
        return maxx, h-y+gap, D
    maxx, maxy, D = drawit(F)
    if maxx>400 or maxy>200: _,_,D = drawit(F,maxx,maxy)
    return D
コード例 #6
0
ファイル: apps.py プロジェクト: Evgen25-max/foodgram-project
 def ready(self):
     Font_FreeSans = ttfonts.TTFont(
         'FreeSans',
         os.path.join(settings.BASE_DIR,
                      'recipes/static/fonts/FreeSans.ttf'))
     Font_FreeSansOblique = ttfonts.TTFont(
         'FreeSansOblique',
         os.path.join(settings.BASE_DIR,
                      'recipes/static/fonts/FreeSansOblique.ttf'))
     pdfmetrics.registerFont(Font_FreeSans)
     pdfmetrics.registerFont(Font_FreeSansOblique)
コード例 #7
0
def resetFonts():
    # testshapes._setup registers the Vera fonts every time which is a little
    # slow on all platforms. On Windows it lists the entire system font
    # directory and registers them all which is very slow.
    pdfmetrics.registerFont(ttfonts.TTFont("Vera", "Vera.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraBd", "VeraBd.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraIt", "VeraIt.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraBI", "VeraBI.ttf"))
    for f in ('Times-Roman', 'Courier', 'Helvetica', 'Vera', 'VeraBd',
              'VeraIt', 'VeraBI'):
        if f not in testshapes._FONTS:
            testshapes._FONTS.append(f)
コード例 #8
0
ファイル: utils.py プロジェクト: koshelevd/foodgram-project
def create_pdf(ingredients, filename):
    """
    Create pdf-document with filename specified.
    """
    def print_head():
        pdf_canvas.setFont('Arial', 40)
        pdf_canvas.drawString(150, 800, 'Список покупок')
        pdf_canvas.setFont('Arial', 20)

    buffer = io.BytesIO()
    pdf_canvas = canvas.Canvas(buffer)
    font = ttfonts.TTFont(
        'Arial', os.path.join(settings.BASE_DIR, 'static', 'fonts',
                              'arial.ttf'))
    pdfmetrics.registerFont(font)
    print_head()
    line_y = -1
    for pos, val in enumerate(ingredients):
        line_y += 1
        string = (f'{pos + 1}. {val["recipe__ingredients__name"]} '
                  f'({val["recipe__ingredients__unit"]}): '
                  f'{val["quantity"] or ""}')
        pdf_canvas.drawString(50, 750 - 50 * line_y, string)
        if (pos + 1) % 15 == 0:
            pdf_canvas.showPage()
            line_y = -1
            print_head()

    pdf_canvas.showPage()
    pdf_canvas.save()
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename=filename)
コード例 #9
0
def getAFont():
    '''register a font that supports most Unicode characters'''
    I = []
    font_name = 'DejaVuSans'
    I.append([
        (font_name, 0, 0, font_name),
        (font_name, 1, 0, font_name + '-Bold'),
        (font_name, 0, 1, font_name + '-Oblique'),
        (font_name, 1, 1, font_name + '-BoldOblique'),
    ])
    font_name = 'FreeSerif'
    I.append([
        (font_name, 0, 0, font_name),
        (font_name, 1, 0, font_name + 'Bold'),
        (font_name, 0, 1, font_name + 'Italic'),
        (font_name, 1, 1, font_name + 'BoldItalic'),
    ])
    for info in I:
        n = 0
        for font in info:
            fontName = font[3]
            try:
                pdfmetrics.registerFont(
                    ttfonts.TTFont(fontName, fontName + '.ttf'))
                addMapping(*font)
                n += 1
            except:
                pass
        if n == 4: return font[0]
    raise ValueError('could not find suitable font')
コード例 #10
0
ファイル: views.py プロジェクト: ush/pkcinema
def PDF(merop, name, booked):
    for i in range(len(booked)):
        packet = io.BytesIO()
        # create a new PDF with Reportlab
        MyFontObject = ttfonts.TTFont('Arial', 'arial.ttf')
        pdfmetrics.registerFont(MyFontObject)
        MyCanvas = canvas.Canvas(packet, pagesize=letter)
        MyCanvas.setFont("Arial", 20)
        MyCanvas.drawString(178, 69, str(merop))
        MyCanvas.drawString(167, 101, setMestaforPdf(''.join(str(booked[i]))))
        MyCanvas.drawString(139, 35, str(name))
        MyCanvas.drawImage('media/img/qrkode.jpg', 440, 30)
        MyCanvas.save()

        #move to the beginning of the StringIO buffer
        packet.seek(0)
        new_pdf = PdfFileReader(packet)
        # read your existing PDF
        existing_pdf = PdfFileReader(open(r"media/pdf/ticket.pdf", "rb"))
        output = PdfFileWriter()
        # add the "watermark" (which is the new pdf) on the existing page
        page = existing_pdf.getPage(0)
        page.mergePage(new_pdf.getPage(0))
        output.addPage(page)
        # finally, write "output" to a real file

        outputStream = open(r"media/pdf/destination" + str(i) + ".pdf", "wb")
        output.write(outputStream)
        outputStream.close()
コード例 #11
0
 def InitCanvas(self):
     pdfmetrics.registerFont (ttfonts.TTFont ('chinese', Constant.GetFont_msjhbd()))  # 註冊字型
     if os.path.exists(self.tempPdf):
         os.remove(self.tempPdf)
     cv = canvas.Canvas(self.tempPdf)
     cv.setFont ('chinese', 10)
     return cv
コード例 #12
0
 def __init__(self, master, verbose):
     # [Row(format_, glub, ampl, timdata, shir, dolg, vs, kurs, m_man, color_mm_, m_avto, all_data)...]
     self.master = master  # show_bso
     self.w, self.data, self.scr, self.scale, self.name = self.master.get_pdf_data(
     )
     self.W = 756.0  # слева на право  768.0
     self.H = 450  # снизу вверх                   ## 400 !!!
     self.dx = 30  # слева
     self.dy = 90  # снизу
     self.stic = 7  # засечка на осях
     self.dl = 15  # удление надписий от осей
     self.k = self.W / self.w
     # self.list_scale = [(0, 2), (1, 1), (2, 0.2), (3, 0.1), (4, 0.05), (5, 0.02), (6, 0.01), (7, 4.0/600), (8, 0.005), (9, 0.004)]
     self.list_scale = [(0, 2.0), (1, 1.0), (2, 0.4), (3, 0.2), (4, 0.1),
                        (5, 0.05), (6, 0.04), (7, 0.02), (8, 0.01),
                        (9, 4.0 / 600), (10, 0.005), (11, 0.004)]
     myFontObject = ttfonts.TTFont('Arial', 'arial.ttf')
     pdfmetrics.registerFont(myFontObject)
     self.dir = '.'
     cur_path = pathlib.Path('temp.pdf')
     self.tmp_name = cur_path.joinpath(bakdir, cur_path)
     if self.data:
         # name = os.path.join(bakdir, 'temp.pdf')
         # self.c = canvas.Canvas("temp.pdf", pagesize=landscape(A4))  # файл "temp.pdf"
         # в текущем каталоге
         self.c = canvas.Canvas(f"{self.tmp_name}", pagesize=landscape(A4))
         self.asix()
         self.grid()
         self.c.setFillColor('darkblue')
         self.c.drawString(self.dx + self.W + self.dl, self.dy + self.H - 5,
                           "0")
         self.data_pdf()
         self.pasteimg()
         self.run()
         self.go(verbose)
コード例 #13
0
ファイル: views.py プロジェクト: Weramax/Diplom_projects
def generate_pdf_users(request, pk):
	project = Project.objects.filter(user=pk)
	user = User.objects.filter(id = pk)

	response = HttpResponse(content_type='application/pdf')

	# response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'


	MyFontObject = ttfonts.TTFont('Arial', sys.path[0] + '/websystem/static/fonts/9041.ttf')
	pdfmetrics.registerFont(MyFontObject)
	p = canvas.Canvas(response)
	p.setLineWidth(.3)
	p.setFont('Arial', 12)

	def draw_header(user):
		p.setFont('Arial', 18)
		for itm in user.all():
			p.drawString(60, 780, itm.first_name + "  "+ itm.last_name)

	def draw_body(x, y, item):
		p.setFont('Arial', 12)
		p.drawString(x, y, "Задача" + "  "+item.name + ":" + " В проекте" + str(item.species))
		p.drawString(x+5, y-20, "Описание")
		p.drawString(x+5, y-35, item.description)
		p.drawString(x+5, y-55, "Исполнитель(и)")
		z = x

		for itm in item.user.all():
			p.drawString(z+5, y-65, itm.first_name + ' ' + itm.last_name + ";")
			z += 100
		p.drawString(x + 5, y - 85, 'Прогресс задачи:')
		for items in item.complete_value:
			if items != "0":
				p.drawString(x + 130, y - 85, 'Выполнено')
			else:
				p.drawString(x + 130, y -85, 'Не выполнено')
		p.line(x, y, x+250, y)

	draw_header(user)
	x = 30
	y = 700
	if len(project) > 0:
		for item in project:
			if y > 50:
				draw_body(x, y, item)
				y -= 120
			else:
				p.showPage()
				y = 700
				draw_header(user)
				draw_body(x, y, item)
				y -= 120

		p.showPage()
		p.save()
		context = {'response': response}
		return response
	else:
		return HttpResponse(request.META.get('HTTP_REFERER'))
コード例 #14
0
ファイル: pdf_gen.py プロジェクト: vanya2535/pdf_gen
 def set_font(self, font_size: int):
     """
     This function set up font and his size in file\n
     :param font_size: size of font
     """
     self.font_size = font_size
     using_font = ttfonts.TTFont("Calibri", "Calibri.ttf")
     pdfmetrics.registerFont(using_font)
     self.file.setFont("Calibri", self.font_size)
コード例 #15
0
ファイル: __init__.py プロジェクト: annndrey/npui
def _register_fonts(settings):
    default_fontdir = settings.get('netprofile.fonts.directory', '')
    default_family = settings.get('netprofile.fonts.default_family', 'tinos')
    fontcfg = make_config_dict(settings, 'netprofile.fonts.family.')
    fontcfg = as_dict(fontcfg)
    for fname, cfg in fontcfg.items():
        if 'normal' not in cfg:
            continue
        fname = cfg.get('name', fname)
        fontdir = cfg.get('directory', default_fontdir)
        pdfmetrics.registerFont(
            ttfonts.TTFont(fname, os.path.join(fontdir, cfg['normal'])))
        reg = {'normal': fname}

        if 'bold' in cfg:
            reg['bold'] = fname + '_b'
            pdfmetrics.registerFont(
                ttfonts.TTFont(reg['bold'], os.path.join(fontdir,
                                                         cfg['bold'])))
        else:
            reg['bold'] = fname

        if 'italic' in cfg:
            reg['italic'] = fname + '_i'
            pdfmetrics.registerFont(
                ttfonts.TTFont(reg['italic'],
                               os.path.join(fontdir, cfg['italic'])))
        else:
            reg['italic'] = fname

        if 'bold_italic' in cfg:
            reg['boldItalic'] = fname + '_bi'
            pdfmetrics.registerFont(
                ttfonts.TTFont(reg['boldItalic'],
                               os.path.join(fontdir, cfg['bold_italic'])))
        else:
            reg['boldItalic'] = fname

        pdfmetrics.registerFontFamily(fname, **reg)

    if default_family in fontcfg:
        return default_family
    return 'Times-Roman'
コード例 #16
0
ファイル: pdf.py プロジェクト: liuran2011/analyze
    def __init__(self, conf, env, db, notify):
        super(Generator, self).__init__(conf, env, db, notify)

        pdfmetrics.registerFont(
            ttfonts.TTFont('song',
                           '%s/fonts/simsun.ttc' % (self.env.share_dir())))
        self.style = copy.deepcopy(getSampleStyleSheet()['Normal'])
        self.style.fontName = 'song'
        self.style.fontSize = 12
        self.content = []
コード例 #17
0
    def __init__(self, font_path: str):
        pdfmetrics.registerFont(
            ttfonts.TTFont(Transformer.ARIAL_UNICODE, font_path))

        self.style_sheet = styles.getSampleStyleSheet()
        self.style_sheet.add(
            styles.ParagraphStyle(
                name='BasicText',
                fontName=Transformer.ARIAL_UNICODE)  # TODO: make configurable
        )
コード例 #18
0
	def __init__(self,setting):
		pdfmetrics.registerFont(ttfonts.TTFont('song', '/home/python/Database_To_PDF/simsun.ttc'))
		self.filename='report.pdf'
		self.pagesize=A4
		self.cm=cm
		self.styles = getSampleStyleSheet()
		self.styleN = self.styles['Normal']
		self.styleN.fontName ='song'
		self.styleH = self.styles['Heading1']
		self.styleH.fontName ='song'
		self.header_str=setting.doc_header
コード例 #19
0
def pdf_view(request, **kwargs):
    newspaper_id = kwargs.get('np')
    year_id = kwargs.get('year')
    issue_id = kwargs.get('issue')
    newspaper = Newspaper.objects.get(slug=newspaper_id)
    year = Year.objects.get(year=year_id)
    issue = Issue.objects.get(newspaper=newspaper, year=year, issue=issue_id)
    
    print(kwargs)
    response = HttpResponse(content_type='application/pdf')
    # response['Content-Disposition'] = 'attachment; filename="{}.pdf"'.format(kwargs.get('np', 'Unknown'))
    
    font = ttfonts.TTFont('Arial', 'arial.ttf')
    pdfmetrics.registerFont(font)
    # pdfmetrics.Encoding('Cp1251')
    
    #  p = canvas.Canvas(response, bottomup=True)
    doc = SimpleDocTemplate(response, title=str(issue), showBoundary=1)
    Story = []
    
    styles = getSampleStyleSheet()
    styles['Normal'].fontName = 'Arial'
    styles['Heading1'].fontName = 'Arial'
    styles['Heading2'].fontName = 'Arial'
    styles['Heading3'].fontName = 'Arial'
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontName='Arial'))
    
    page = 1
    for p in issue.article_set.all():
        while not page == p.page:
            generate_page(Story, page, p, "", "", styles, True)
            page += 1 
        
        generate_page(Story, page, p, p.unempty_title(), p.text(), styles)
        page += 1

    # p.drawString(50, 800, str(issue))

    # p.drawString(100, 100, "Hello World!")
    # p.showPage()
    
    # p.drawString(100, 100, "Hallo World!")
    # p.showPage()
    
    #  p.save()
    doc.build(Story)
    
    return response
コード例 #20
0
    def __init__(self, order):
        # Регистрируем шрифт с кириллцей
        font = ttfonts.TTFont('Arial', 'arial.ttf')
        pdfmetrics.registerFont(font)

        # Создаем путь к файлу
        self.file_name = f'Заказ_{order.id}.pdf'
        self.file_dir = os.path.join(settings.BASE_DIR, 'orders_pdf')
        if not os.path.exists(self.file_dir):
            os.makedirs(self.file_dir)
        self.path = os.path.join(self.file_dir, self.file_name)

        # Создаем файл
        self.pdf = canvas.Canvas(self.path, pagesize=A4)
        self.width, self.height = A4

        # Заголовок
        self.pdf.setFont('Arial', 18, leading=None)
        self.pdf.drawCentredString(self.width / 2, self.height - 2 * cm,
                                   f'Заказ №{order.id}')

        # Информация о заказчике
        self.pdf.setFont('Arial', 13, leading=None)
        if order.user.first_name and order.user.last_name:
            self.pdf.drawString(
                1 * cm, self.height - 4 * cm,
                f'Имя заказчика: {order.user.first_name} {order.user.last_name}'
            )
        else:
            self.pdf.drawString(1 * cm, self.height - 4 * cm,
                                'Имя заказчика: не указано')

        address = f'г.{order.contact.city}, ул.{order.contact.street}, д.{order.contact.house},'
        if order.contact.structure:
            address += f'корп.{order.contact.structure},'
        if order.contact.building:
            address += f'стр.{order.contact.building},'
        if order.contact.apartment:
            address += f'кв.{order.contact.apartment}'

        self.pdf.drawString(1 * cm, self.height - 4.75 * cm,
                            f'Адрес: {address}')
        self.pdf.drawString(1 * cm, self.height - 5.5 * cm,
                            f'E-mail: {order.user.email}')
        if order.contact.phone:
            self.pdf.drawString(1 * cm, self.height - 6.25 * cm,
                                f'Телефон: {order.contact.phone}')
コード例 #21
0
ファイル: pdf_creator.py プロジェクト: Tartorus/MyLibs
    def font_register(self, font_name, path=None, add_style=False):
        """
        Регистрирует шрифты
        :return:
        """
        name = font_name.split('.')[0]
        if name in self.fonts:
            return self

        if path is None:
            path = self.path
        pdfmetrics.registerFont(ttfonts.TTFont(name, path + '/' + font_name))
        self.fonts.add(name)

        if add_style:
            self.add_style(name)

        return self
コード例 #22
0
def export(grid, locked_cells):

    # Locate the Desktop as initial save path
    pdf_default_title = 'PySudoku.pdf'
    initial_save_path = join(expanduser('~'), 'Desktop/')

    try:

        # Hide Tkinter window
        Tk().withdraw()

        # Open dialog window from Tkinter
        pdf = filedialog.asksaveasfile(initialdir=initial_save_path,
                                       initialfile=pdf_default_title,
                                       title='Export as pdf',
                                       defaultextension='.pdf',
                                       filetypes=[('PDF file', '.pdf')])

        # Generate pdf
        sudoku_file = Canvas(pdf.name, pagesize=A4)

        # Draw logo and board
        sudoku_file.drawInlineImage('images/pdf/pdf_logo.png', 25, 715)
        sudoku_file.drawInlineImage('images/pdf/pdf_board.png', 48, 120)

        # Set custom font
        pdfmetrics.registerFont(
            ttfonts.TTFont('Ubuntu-Regular', 'fonts/Ubuntu-Regular.ttf'))
        sudoku_file.setFont('Ubuntu-Regular', 58)

        # Draw numbers on the board
        for cell in locked_cells:
            if cell in grid_to_pdf.keys():
                sudoku_file.drawString(grid_to_pdf[cell][0],
                                       grid_to_pdf[cell][1], str(grid[cell]))

        sudoku_file.setTitle(pdf.name[len(initial_save_path):])
        sudoku_file.save()

    except AttributeError:
        pass
コード例 #23
0
ファイル: Write.py プロジェクト: MalahovMV/Stego_Chich
def new_information(login, password):
    bynary_line = creat_key(login, password)
    pdfmetrics.registerFont(ttfonts.TTFont('Arial', 'arial.ttf'))
    packet = io.BytesIO()
    can = canvas.Canvas(packet)
    can.setFont('Arial', 10)
    file = open('Text with stego.txt')
    next_line = 0
    pointer_bynary_line = 0
    for line in file:
        out_line, pointer_bynary_line = replacement_letter(
            line[:-1], pointer_bynary_line, bynary_line)
        can.drawString(10, 800 - next_line, out_line)
        next_line += 12

    print(pointer_bynary_line)
    file.close()
    can.showPage()
    can.save()
    packet.seek(0)
    new_pdf = PyPDF2.PdfFileReader(packet)
    return new_pdf
コード例 #24
0
def create_pdf(
    request,
    id_demand,
):
    demand = get_object_or_404(Demand, id=id_demand)
    positions = Position.objects.filter(id_demand=id_demand)

    #	Заявка
    demand_date = "%s" % demand.created_date.strftime('%d.%m.%Y')
    demand_number = "%s" % demand.id
    demand_description = "%s" % demand.description
    demand_quantity_pos = "%s" % demand.position_count()
    demand_quantity_prod = "%s" % demand.product_count()
    demand_price_all = "%s" % demand.price_all()

    today_date = datetime.datetime.today()
    filename = 'Demand_' + str(demand.id) + '_detail' + '.pdf'
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename

    myfont = ttfonts.TTFont(
        'Times', r'C:\Users\admin\djangopr\myapp\static\myapp\TIMES.TTF')
    pdfmetrics.registerFont(myfont)

    demand_date = demand.created_date.strftime('%d.%m.%Y')
    demand_number = "%s" % demand.id
    demand_description = "%s" % demand.description
    demand_quantity_pos = "%s" % demand.position_count()
    demand_quantity_prod = "%s" % demand.product_count()
    demand_price_all = "%s" % demand.price_all()

    styles = getSampleStyleSheet()
    # temp = BytesIO()

    #   Стили
    style_par = ParagraphStyle("text",
                               fontName="Times",
                               fontSize=12,
                               alignment=TA_LEFT,
                               spaceAfter=5,
                               spaceBefore=5)
    style_nametable = ParagraphStyle("text",
                                     fontName="Times",
                                     fontSize=14,
                                     alignment=TA_CENTER,
                                     spaceAfter=15,
                                     spaceBefore=30)
    style_title = ParagraphStyle("text",
                                 fontName="Times",
                                 fontSize=18,
                                 alignment=TA_CENTER,
                                 spaceAfter=30,
                                 spaceBefore=10)

    style_pos_name = ParagraphStyle("text",
                                    fontName="Times",
                                    fontSize=11,
                                    alignment=TA_CENTER,
                                    wordWrap=True)

    story = [Spacer(1, -0.5 * inch)]

    #   Шапка документа
    header = Paragraph("Информация по заявке №{0}".format(demand_number),
                       style=style_title)
    story.append(header)

    #   Описание заявки
    a = Paragraph("Дата создания: {0}".format(demand_date), style=style_par)
    b = Paragraph("Описание: {0}".format(demand_description), style=style_par)
    c = Paragraph("Кол-во позиций: {0}".format(demand_quantity_pos),
                  style=style_par)
    d = Paragraph("Кол-во товаров: {0}".format(demand_quantity_prod),
                  style=style_par)
    e = Paragraph("Общая ст-ть (руб): {0}".format(demand_price_all),
                  style=style_par)
    story.append(a)
    story.append(b)
    story.append(c)
    story.append(d)
    story.append(e)

    doc2 = SimpleDocTemplate(settings.MEDIA_ROOT + '\\' + today_date.strftime('%Y') + '\\' + today_date.strftime('%m') + '\\' + \
           filename, rightMargin=40, leftMargin=40, topMargin=50, bottomMargin=30)
    blok_table = []
    title = Paragraph("Позиции в заявке №{0}".format(demand_number),
                      style=style_nametable)
    story.append(title)
    if len(positions) == 0:
        no = Paragraph("Нет созданных позиций для данной заявки",
                       style=style_nametable)
        story.append(no)
    else:
        tablehead = [[
            u'Наименование товара', u'Артикул товара', u'Кол-во',
            u'Цена за 1 шт', u'Общая стоимость'
        ]]
        tabhead = Table(
            tablehead,
            rowHeights=[1 * cm],
            colWidths=[7.5 * cm, 4 * cm, 1.5 * cm, 3.5 * cm, 3.5 * cm])
        tabhead.setStyle(
            TableStyle([
                ('FONT', (0, 0), (-1, -1), 'Times', 10),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
            ]))
        story.append(tabhead)
    for position in positions:
        tablebody = [[
            Paragraph("%s" % position.id_product.name, style=style_pos_name),
            "%s" % position.id_product.art,
            "%s" % position.quantity,
            "%s" % position.id_product.price_one,
            "%s" % position.cost()
        ]]

        tabbody = Table(
            tablebody,
            colWidths=[7.5 * cm, 4 * cm, 1.5 * cm, 3.5 * cm, 3.5 * cm])
        tabbody.setStyle(
            TableStyle([
                ('FONT', (0, 0), (-1, -1), 'Times', 10),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
            ]))

        story.append(tabbody)

    #   Оформление подвала
    date_created = today_date.strftime("%d.%m.%Y")
    user_created = request.user.last_name + ' ' + request.user.first_name[
        0] + '. ' + request.user.profile.middle_name[0]
    tablefooter = [[u'Подписи:', u'Дата:      '],
                   [u'{0}'.format(user_created), u'{0}'.format(date_created)]]
    tabfoo = Table(tablefooter, rowHeights=30, colWidths=200, spaceBefore=50)

    tabfoo.setStyle(
        TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Times', 11),
            ('ALIGN', (0, 0), (0, -1), 'LEFT'),
            ('ALIGN', (1, 0), (1, -1), 'RIGHT'),
        ]))

    story.append(tabfoo)

    doc2.build(story)
    # f = open('test.pdf', 'w')
    # f.write(str(temp.getpdfdate()))
    # f.close()

    # pdf = temp.getvalue()
    # response.write(pdf)
    # temp.close()

    pdf_url = settings.MEDIA_URL + today_date.strftime(
        '%Y') + '/' + today_date.strftime('%m') + '/' + filename

    Documents.objects.create(
        date_create=today_date,
        user_create=Profile.objects.get(id=request.user.id),
        id_demand=Demand.objects.get(id=id_demand),
        name_doc=filename,
        url=pdf_url)

    return HttpResponse(pdf_url)
コード例 #25
0
    def report(self, *args, **kwargs):
        # Create the PDF object, using the response object as its "file."
        pdf = canvas.Canvas(self.response)
        times_bold = ttfonts.TTFont('TimesBold', 'Times New Roman Cyr Bold.ttf')
        times = ttfonts.TTFont('Times', 'Times New Roman Cyr.ttf')
        pdfmetrics.registerFont(times_bold)
        pdfmetrics.registerFont(times)

        # Draw things on the PDF. Here's where the PDF generation happens.
        # See the ReportLab documentation for the full list of functionality.
        massmedia = MassMedia.objects.get(user=self.request.user)

        for reporter in massmedia.reporter_set.all():
            print(reporter)
            reporter.printed = False
            reporter.save()
            pdf.setFont("TimesBold", 16)
            pdf.drawString(3 * cm, 27 * cm, "УЧЕТНАЯ КАРТОЧКА КОРРЕСПОНДЕНТА")
            pdf.setFont("Times", 15)

            if reporter.image_crop:
                image = ImageReader(reporter.image_crop)
            else:
                image = ImageReader('main/static/main/img/unknown.jpg')
            pdf.drawImage(image, 17 * cm, 23.5 * cm, 3 * cm, 4 * cm)

            pdf.drawString(3 * cm, 21 * cm, "Полное наименование СМИ:")
            pdf.setFont("TimesBold", 16)
            pdf.drawString(11 * cm, 21 * cm, massmedia.__str__())

            pdf.setFont("Times", 15)
            pdf.drawString(7.6 * cm, 20 * cm, "Фамилия:")
            pdf.setFont("TimesBold", 16)
            pdf.drawString(11 * cm, 20 * cm, reporter.surname)

            pdf.setFont("Times", 15)
            pdf.drawString(8.75 * cm, 19 * cm, "Имя:")
            pdf.setFont("TimesBold", 16)
            pdf.drawString(11 * cm, 19 * cm, reporter.name)

            pdf.setFont("Times", 15)
            pdf.drawString(7.6 * cm, 18 * cm, "Отчество:")
            pdf.setFont("TimesBold", 16)
            pdf.drawString(11 * cm, 18 * cm, reporter.lastname)

            pdf.setFont("Times", 15)
            pdf.drawString(4.2 * cm, 17 * cm, "Занимаемая должность:")
            pdf.setFont("TimesBold", 16)
            pdf.drawString(11 * cm, 17 * cm, reporter.post)

            pdf.setFont("Times", 13)
            pdf.drawString(4 * cm, 14 * cm, "Я,")
            pdf.setFont("TimesBold", 16)
            pdf.drawString(6 * cm, 14 * cm, reporter.__str__())
            pdf.line(4.8 * cm, 13.8 * cm, 18.5 * cm, 13.8 * cm)

            pdf.setFont("Times", 13)
            pdf.drawString(3 * cm, 13 * cm, "даю свое согласие на обработку моих персональных данных, предусмотренное")
            pdf.drawString(3 * cm, 12 * cm, "Законом Российской Федерации от 27.07.2006 № 152-ФЗ «О персональных")
            pdf.drawString(3 * cm, 11 * cm, "данных».")

            pdf.setFont("Times", 9)

            pdf.drawString(10.3 * cm, 8 * cm, "подпись")
            pdf.line(9 * cm, 8.5 * cm, 13 * cm, 8.5 * cm)
            pdf.drawString(14.2 * cm, 8 * cm, "расшифровка подписи")
            pdf.line(13.2 * cm, 8.5 * cm, 18.5 * cm, 8.5 * cm)
            pdf.drawString(13.7 * cm, 8.7 * cm,
                           "%s.%s. %s" % (reporter.name[0].upper(), reporter.lastname[0].upper(), reporter.surname))
            # pdf.drawString(10 * cm, 7 * cm, "М.П.")

            pdf.drawString(4.7 * cm, 5 * cm, "должность")
            pdf.line(3 * cm, 5.5 * cm, 8 * cm, 5.5 * cm)
            pdf.drawString(10.3 * cm, 5 * cm, "подпись")
            pdf.line(9 * cm, 5.5 * cm, 13 * cm, 5.5 * cm)
            pdf.drawString(14.2 * cm, 5 * cm, "расшифровка подписи")
            pdf.line(13.2 * cm, 5.5 * cm, 18.5 * cm, 5.5 * cm)
            pdf.drawString(10 * cm, 4 * cm, "М.П.")

            pdf.drawString(3 * cm, 2 * cm, 'Дата "____" _______________ 20_____ г.')

            pdf.showPage()
        # style = ParagraphStyle(name='test')
        # text = Paragraph("предусмотренное Законом Российской Федерации от 27 июля 2006 года № 152-ФЗ «О персональных данных».", style)
        # pdf.drawString(text)


        # Close the PDF object cleanly, and we're done.

        pdf.save()
        return self.response
コード例 #26
0
#coding:utf-8
import os, sys
from reportlab.pdfgen import canvas
from reportlab.pdfbase import ttfonts
from reportlab.pdfbase import pdfmetrics
from reportlab.lib.units import mm

if sys.platform == 'win32': font = ttfonts.TTFont('Arial', 'arial.ttf')
else:
    font = ttfonts.TTFont(
        'Arial', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf')
pdfmetrics.registerFont(font)


class Pdf:
    def next(self, font=12):
        # переход на следующую страницу
        self.sk = 280
        self.pdf.showPage()
        self.pdf.setFont('Arial', font)

    def __init__(self, title='Это тест', fname='out.pdf'):
        self.sk = 280
        self.fname = fname
        if sys.platform == 'win32':
            self.pdf = canvas.Canvas(fname.encode('cp1251'))
        else:
            self.pdf = canvas.Canvas(fname.encode('utf-8'))

        self.pdf.setFont('Arial', 14)
        self.pdf.drawString(60 * mm, self.sk * mm, title)
コード例 #27
0
ファイル: views.py プロジェクト: PerMary/mynewapp
def create_pdf(
    request,
    id_demand,
):
    demand = get_object_or_404(Demand, id=id_demand)
    positions = Position.objects.filter(id_demand=id_demand)

    #	Заявка
    demand_date = "%s" % demand.created_date.strftime('%d.%m.%Y')
    demand_number = "%s" % demand.id
    demand_description = "%s" % demand.description
    demand_quantity_pos = "%s" % demand.position_count()
    demand_quantity_prod = "%s" % demand.product_count()
    demand_price_all = "%s" % demand.price_all()

    filename = 'Demand_' + str(demand.id) + '_detail.pdf'
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename

    myfont = ttfonts.TTFont(
        'Times', '/home/marina/django/myapp/static/myapp/TIMES.TTF')
    pdfmetrics.registerFont(myfont)

    styles = getSampleStyleSheet()
    temp = BytesIO()
    p = canvas.Canvas(temp)

    #   Стили
    style_par = ParagraphStyle("text",
                               fontName="Times",
                               fontSize=12,
                               alignment=TA_LEFT,
                               spaceAfter=5,
                               spaceBefore=5)
    style_nametable = ParagraphStyle("text",
                                     fontName="Times",
                                     fontSize=14,
                                     alignment=TA_CENTER,
                                     spaceAfter=15,
                                     spaceBefore=30)
    style_title = ParagraphStyle("text",
                                 fontName="Times",
                                 fontSize=18,
                                 alignment=TA_CENTER,
                                 spaceAfter=30,
                                 spaceBefore=10)
    style_footer_p = ParagraphStyle("text",
                                    fontName="Times",
                                    fontSize=12,
                                    alignment=TA_LEFT,
                                    spaceAfter=0,
                                    spaceBefore=50,
                                    bulletIndent=100,
                                    spaceShrinkage=20)
    style_footer_d = ParagraphStyle(
        "text",
        fontName="Times",
        fontSize=12,
        alignment=TA_LEFT,
        spaceAfter=0,
        spaceBefore=15,
        bulletIndent=100,
    )

    story = [Spacer(1, 0.25 * inch)]
    #   Шапка документа
    header = Paragraph("Информация по заявке №{0}".format(demand_number),
                       style=style_title)
    story.append(header)

    #   Описание заявки
    a = Paragraph("Дата создания: {0}".format(demand_date), style=style_par)
    b = Paragraph("Описание: {0}".format(demand_description), style=style_par)
    c = Paragraph("Кол-во позиций: {0}".format(demand_quantity_pos),
                  style=style_par)
    d = Paragraph("Кол-во товаров: {0}".format(demand_quantity_prod),
                  style=style_par)
    e = Paragraph("Общая ст-ть (руб): {0}".format(demand_price_all),
                  style=style_par)
    story.append(a)
    story.append(b)
    story.append(c)
    story.append(d)
    story.append(e)

    doc2 = SimpleDocTemplate(temp,
                             rightMargin=20,
                             leftMargin=20,
                             topMargin=0,
                             bottomMargin=0)
    blok_table = []
    title = Paragraph("Позиции в заявке №{0}".format(demand_number),
                      style=style_nametable)
    story.append(title)
    if len(positions) == 0:
        no = Paragraph("Нет созданных позиций для данной заявки",
                       style=style_nametable)
        story.append(no)
    else:
        tablehead = [[
            u'Наименование ', u'Артикул ', u'Кол-во', u'Цена за шт(руб)',
            u'Общая ст-ть (руб)'
        ]]
        tabhead = Table(
            tablehead,
            rowHeights=[1.25 * cm],
            colWidths=[7.5 * cm, 4 * cm, 1.5 * cm, 3.5 * cm, 3.5 * cm])
        tabhead.setStyle(
            TableStyle([
                ('FONT', (0, 0), (-1, -1), 'Times', 11),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
            ]))
        story.append(tabhead)
    for position in positions:
        tablebody = [[
            "%s" % position.name_reduction(),
            "%s" % position.art_product,
            "%s" % position.quantity,
            "%s" % position.price_one,
            "%s" % position.cost()
        ]]

        tabbody = Table(
            tablebody,
            colWidths=[7.5 * cm, 4 * cm, 1.5 * cm, 3.5 * cm, 3.5 * cm])
        tabbody.setStyle(
            TableStyle([
                ('FONT', (0, 0), (-1, -1), 'Times', 11),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
            ]))

        story.append(tabbody)

#   Оформление подвала
    date_created = datetime.datetime.today().strftime("%d.%m.%Y")
    user_created = request.user.last_name + ' ' + request.user.first_name + ' '
    tablefooter = [
        [u'Подписи:', u'Дата:      '],
        [u'{0}'.format(user_created), u'{0}'.format(date_created)],
    ]
    tabfoo = Table(tablefooter, rowHeights=30, colWidths=200, spaceBefore=50)
    tabfoo.setStyle(
        TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Times', 11),
            ('ALIGN', (0, 0), (0, -1), 'LEFT'),
            ('ALIGN', (1, 0), (1, -1), 'RIGHT'),
        ]))

    story.append(tabfoo)

    p.showPage()
    p.save()

    doc2.build(story)
    pdf = temp.getvalue()
    temp.close()
    response.write(pdf)

    return response
コード例 #28
0
ファイル: reports.py プロジェクト: akaKAIN/TradingStoreBot
from collections import namedtuple

from reportlab.pdfbase import pdfmetrics, ttfonts
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import mm

from settings import config

font_arial = ttfonts.TTFont('Arial', 'arial.ttf')
pdfmetrics.registerFont(font_arial)

HMARGIN = 20 * mm
RMARGIN = 5 * mm
TMARGIN = 10 * mm
BMARGIN = 20 * mm


def get_vertical():
    num = 270
    while True:
        yield num
        num -= 5


Item = namedtuple('Item', 'name, code, unit, quantity, price')


class ReportInvoice:
コード例 #29
0
from io import BytesIO
from datetime import date
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfbase import pdfmetrics, ttfonts
from PyPDF2 import PdfFileReader, PdfFileWriter

font_path = "application/static/TakaoExGothic.ttf"
pdfmetrics.registerFont(ttfonts.TTFont("Takao", font_path))

class PdfDocument(object):

    CENTER = 'center'
    RIGHT = 'right'
    LEFT = 'left'
    ALIGN = { CENTER: 'Centred', RIGHT: 'Right' }

    def __init__(self, instream, outstream, font=("Takao", 9)):
        self.base = PdfFileReader(instream)

        self.s = BytesIO()
        self.c = Canvas(self.s, pagesize=A4)

        self.font = font
        self.c.setFont(*self.font)

        self.output = outstream

    def string(self, pos, t, align=LEFT):
        getattr(self.c, 'draw%sString' % self.ALIGN.get(align, ''))(*pos, t)
コード例 #30
0
ファイル: document.py プロジェクト: sjustas/z3c.rml
 def process(self):
     args = self.getAttributeValues(valuesOnly=True)
     font = ttfonts.TTFont(*args)
     pdfmetrics.registerFont(font)