Esempio n. 1
4
def dotest(outputname, nostamp):
    try:
        from bidi.algorithm import get_display
    except ImportError:
        from unittest import SkipTest
        raise SkipTest("Need python-bidi")
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.compress = False
    pdf.add_page()
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, 'font/DejaVuSans.ttf'), uni=True)
    pdf.set_font('DejaVu', '', 14)
    # this will be displayed wrong as actually it is stored LTR:
    text= u"این یک متن پارسی است. This is a Persian text !!"
    pdf.write(8, text)
    pdf.ln(8)
    # Reverse the RLT using the Bidirectional Algorithm to be displayed correctly:
    # (http://unicode.org/reports/tr9/)
    rtl_text = get_display(text)
    pdf.write(8, rtl_text)

    pdf.output(outputname, 'F')
Esempio n. 2
1
def pdf_convert(fname, data):
    pdf = FPDF()
    pdf.set_margins(left=10, top=15, right=10)
    pdf.add_page()
    pdf.add_font('calibri', fname=r'c:\Windows\Fonts\calibri.ttf', uni=True)
    pdf.image('gables.jpg', x=90, w=30)
    pdf.set_font("calibri", size=12)
    pdf.multi_cell(0, 5, txt=data)
    pdf.output(fname)
Esempio n. 3
0
def generateBoardPDF():
    pdf = FPDF()
    # Add a page
    pdf.add_page()

    # set style and size of font
    # that you want in the pdf
    pdf.set_font("Arial", size=15)
    pdf.cell(200, 5, txt='Tactile Overlay for Board', ln=1, align='C')
    pdf.image('static/finalFiles/finalBoard.jpeg', x=5, y=30, w=200, h=200)

    if os.path.exists("static/userData/brailleForBoard.txt"):
        pdf.add_page()
        pdf.set_font("Arial", size=30)
        pdf.cell(200, 5, txt='Braille Labels for Board', ln=1, align='C')
        pdf.add_font('Braille', '', 'static/qbraille-regular.ttf', uni=True)

        # open the text file in read mode
        f = open("static/userData/brailleForBoard.txt", "r")
        # insert the texts in pdf
        for x in f:
            theText = x.split(':')
            theText[0] = re.sub('[^A-Za-z0-9 ]+', '', theText[0])
            pdf.set_font("Arial", size=10)
            pdf.multi_cell(200, 10, txt=theText[0], align='L')
            pdf.set_font('Braille', '', size=24)
            pdf.multi_cell(200, 10, txt=theText[0], align='L')
    generateTactileTitlePage()
    # save the pdf with name .pdf
    pdf.output("static/userData/theBoard.pdf")
Esempio n. 4
0
def make_pdf(f_name, s_name, score):
	pdf = FPDF('L', 'mm', 'A4')
	pdf.add_page()
	pdf.add_font('FreeMono', '', 'task/static/task/sertificate/20294.ttf', uni=True)

	pdf.image('task/static/task/sertificate/sert.jpg', x=0, y=0)

	pdf.ln(60)
	pdf.set_font("FreeMono", size=70)
	pdf.cell(270, 10, txt='Сертификат', align='C')

	pdf.ln(18)
	pdf.set_font("FreeMono", size=25)
	pdf.cell(270, 10, txt='Подтверждает, что {} {}'.format(s_name, f_name), align='C')


	pdf.ln(13)
	pdf.set_font("FreeMono", size=25)
	pdf.cell(270, 10, txt='Завершил(а) курс \"Знакомство с космосом\"', align='C')

	pdf.ln(13)
	pdf.set_font("FreeMono", size=25)
	pdf.cell(270, 10, txt='Количество баллов: {}'.format(score), align='C')

	pdf.output("task/static/task/sertificate/sertificate.pdf")
def createPDF(tFile):
    #Create PDF output dir if not exist
    if args.op.split("/")[0] not in listdir(curdir):
        mkdir(args.op)

    #Set fuzzed pdf name
    sPfile = tFile.split(".ttf")[0]
    tempPDF = FPDF()
    #Add our fuzzed ttf into PDF
    try:
        tempPDF.add_font(sPfile, "", args.o + "/" + tFile, uni=True)
    except:
        return
    tempPDF.set_font(sPfile, "", 16)

    #Create blank page and fill it with data
    tempPDF.add_page()
    tempPDF.cell(40, 10, "PDF TEST FILE")

    #Create fuzzed PDF
    try:
        tempPDF.output(args.op + sPfile + ".pdf", "F")
    except:
        return

    tempPDF.close()
Esempio n. 6
0
def simple_demo():
  pdf = FPDF(orientation='P', unit='mm', format='A4')
  pdf.add_page()
  pdf.add_font('FreeSans', '', './fonts/FreeSans.ttf', uni=True)
  pdf.set_font("FreeSans")
  pdf.cell(200, 10, txt="Привет", ln=1, align="C")
  pdf.output("simple_demo.pdf")
Esempio n. 7
0
def create_order_pdf(image_path, data, image_name, spacing=1):

    pdf = FPDF(orientation='P', unit='mm', format='A4')
    pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)
    pdf.set_font("DejaVu", size=12)
    pdf.add_page()
    text = "Automatic order form 'CRISPY MACHINE'"

    pdf.cell(200, 10, txt=text, ln=1, align="C")
    pdf.image(image_path, x=60, y=20, w=100, type='', link='')
    pdf.ln(150)  # ниже на 100
    col_width = pdf.w / 2.2
    row_height = 2 * pdf.font_size
    for row in data:
        for item in row:
            if len(item) < 36:
                pdf.cell(col_width, row_height * spacing, txt=item, border=1)
            else:
                pdf.multi_cell(col_width,
                               row_height * spacing,
                               txt=item,
                               border=1)

        pdf.ln(row_height * spacing)
    text2 = "© 2020 Copyright: 'CRISPY MACHINE'"
    pdf.cell(200, 10, txt=text2, ln=1, align="C")
    im_name = image_name[:-3]
    im_name2 = im_name + 'PDF'
    im_name2 = im_name2.replace('C:/PP/ORP/ORP_site/OR/media/image_preview/',
                                '')
    pdf_path = 'C:/PP/ORP/ORP_site/OR/media/temp/' + im_name2
    pdf.output(pdf_path)
    return pdf_path
Esempio n. 8
0
def dotest(outputname, nostamp):
    try:
        from bidi.algorithm import get_display
    except ImportError:
        from unittest import SkipTest
        raise SkipTest("Need python-bidi")
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.compress = False
    pdf.add_page()
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, 'font/DejaVuSans.ttf'), uni=True)
    pdf.set_font('DejaVu', '', 14)
    # this will be displayed wrong as actually it is stored LTR:
    text = u"این یک متن پارسی است. This is a Persian text !!"
    pdf.write(8, text)
    pdf.ln(8)
    # Reverse the RLT using the Bidirectional Algorithm to be displayed correctly:
    # (http://unicode.org/reports/tr9/)
    rtl_text = get_display(text)
    pdf.write(8, rtl_text)

    pdf.output(outputname, 'F')
Esempio n. 9
0
class Document(object):

    def __init__(self, **kwargs):
        self.pdf = FPDF(**kwargs)
        self.pdf.add_page()
        self.pdf.set_margins(20, 20, 0)
        self.pdf.ln()
        self._add_font('DejaVu', 'DejaVuSansCondensed.ttf')
        self._add_font('DejaVu-Bold', 'DejaVuSansCondensed-Bold.ttf')

    def _add_font(self, font_name, file_name):
        self.pdf.add_font(font_name, '', asset_path(file_name), uni=True)

    def _font(self, size, bold=False):
        font_name = 'DejaVu' if not bold else 'DejaVu-Bold'
        self.pdf.set_font(font_name, '', size)

    def _text_cell(self, w, h, text, size=10, bold=False, align='L', border=BORDER_DEBUG):
        self._font(size, bold=bold)
        self.pdf.cell(w, h, text, align=align, border=border)

    def _multi_cell(self, w, h, text, size=10, bold=False, align='L', border=BORDER_DEBUG):
        self._font(size, bold=bold)
        self.pdf.multi_cell(w, h, text, align=align, border=border)

    def output(self):
        return self.pdf.output(dest='S')
Esempio n. 10
0
    def processing(self):

        img = qrcode.make(self.qr_text)
        img.save("./img/qr.png")

        pdf = FPDF()
        pdf.add_page()
        pdf.add_font("Times", "B", "./img/times.ttf", uni=True)
        pdf.set_font("Times", "B", 16)

        pdf.image("./img/logo.gif", 10, 10, 33)
        pdf.image("./img/qr.png", 160, 8, 45)
        pdf.image("./img/footer.png", 10, 220, 200)

        for header in self.header:
            pdf.cell(75)
            pdf.cell(30, 10, header, 0, 1, "C")

        pdf.ln(20)
        pdf.add_font("Times", "", "./img/times.ttf", uni=True)
        pdf.set_font("Times", "", 14)

        for t in self.main_text:
            pdf.cell(0, 10, t, 0, 1)

        pdf.output("./pdf/" + self.pdf_filename_to_save, "F")
        self.processed_flag = True
Esempio n. 11
0
def write_to_pdf(dictio, out):
    pdf = FPDF()
    pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', True)
    for key, text in dictio.items():
        text = '\n'.join(text.split('\n')[:-1])
        pdf.add_page()
        pdf.set_xy(10, 20)
        # pdf.set_font('arial', 'B', 11)
        pdf.set_font('DejaVu', size=10)

        # single cell
        # for line in text.split('\n'):
        # pdf.cell(0, 5, line, border=0, ln=1)

        # or multi_cell
        pdf.multi_cell(w=180.0,
                       h=7.0,
                       txt=text,
                       border=0,
                       align='J',
                       fill=False)
        # fpdf.multi_cell(w: float, h: float, txt: str, border = 0, align: str = 'J', fill: bool = False)

    pdf.output(out, 'F')
    return True
Esempio n. 12
0
def test_thai_text(tmp_path):
    pdf = FPDF()
    pdf.add_font("Waree", fname=HERE / "Waree.ttf")
    pdf.set_font("Waree")
    pdf.add_page()
    pdf.write(txt="สวัสดีชาวโลก ทดสอบฟอนต์, Hello world font test.")
    assert_pdf_equal(pdf, HERE / "thai_text.pdf", tmp_path)
Esempio n. 13
0
def createpdf(obj):
    data.append(obj)
    print(data)
    pdf = FPDF()
    pdf.add_page()
    pdf.add_font('pep', '', r"Montserrat/Montserrat-SemiBold.ttf", uni=True)
    pdf.add_font('reg', '', r"Montserrat/Montserrat-Regular.ttf", uni=True)
    pdf.add_font('zhop', '', r"Montserrat/Montserrat-Medium.ttf", uni=True)
    pdf.set_font("pep", size=28)
    pdf.image("Logo.png", x=12, y=15, w=70)
    pdf.cell(200, 65, txt="Indkøbsvogn", ln=1, align="L")
    pdf.set_font("reg", size=24)
    col_width = pdf.w / 2.5
    row_height = pdf.font_size
    c = 0
    for row in data:
        if c != 0:
            pdf.set_font("zhop", size=15)
        for item in row:
            print(item)
            pdf.cell(col_width, row_height * 1, txt=item, border=1)
        pdf.ln(row_height * 1)
        c += 1
    pdf.image("p.png", x=3, y=250, w=200)
    pdf.output("demo.pdf")
def createPDF(tFile):
    # Create PDF output dir if not exist
    if args.op.split("/")[0] not in listdir(curdir):
        mkdir(args.op)

    # Set fuzzed pdf name
    sPfile = tFile.split(".ttf")[0]
    tempPDF = FPDF()
    # Add our fuzzed ttf into PDF
    try:
        tempPDF.add_font(sPfile, "", args.o + "/" + tFile, uni=True)
    except:
        return
    tempPDF.set_font(sPfile, "", 16)

    # Create blank page and fill it with data
    tempPDF.add_page()
    tempPDF.cell(40, 10, "PDF TEST FILE")

    # Create fuzzed PDF
    try:
        tempPDF.output(args.op + sPfile + ".pdf", "F")
    except:
        return

    tempPDF.close()
Esempio n. 15
0
def create_participation_cert(uuid, name, author, journal):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_margins(10, 15, 60)

    pdf.image(settings.STATIC_ROOT + "/pdf/ref_publication_cert.jpg", 0, 0,
              210)

    pdf.add_font('Arial',
                 '',
                 settings.STATIC_ROOT + '/pdf/arial.ttf',
                 uni=True)

    pdf.set_font('Arial', '', 20)
    pdf.cell(0, 50, ln=1)

    pdf.set_font('Arial', '', 32)
    pdf.cell(0, 20, ln=1)
    pdf.cell(0, 6, str(journal), ln=1, align="C")

    pdf.set_font_size(16)
    pdf.cell(0, 20, ln=1)
    pdf.cell(0, 6, author, ln=1, align="C")
    pdf.cell(0, 20, ln=1)
    pdf.cell(0, 6, "Научная статья:", ln=1, align="C")
    pdf.cell(0, 6, name, ln=1, align="C")

    pathlib.Path(settings.MEDIA_ROOT + '/pdf/participation_cert').mkdir(
        parents=True, exist_ok=True)
    pdf.output(
        settings.MEDIA_ROOT + "/pdf/participation_cert/participation_cert_" +
        str(uuid) + ".pdf", 'F')
    return "/pdf/participation_cert/participation_cert_" + str(uuid) + ".pdf"
Esempio n. 16
0
def write_to_pdf(data: dict, filename: str):
    pdf = FPDF()
    effective_page_width = pdf.w - 2 * pdf.l_margin
    pdf.compress = False
    pdf.add_page()
    pdf.add_font("TimesNewRoman", '', 'TimesNewRoman.ttf', uni=True)
    pdf.set_font("TimesNewRoman", size=30)
    pdf.cell(w=0, txt=data['title'])
    pdf.ln(30)
    pdf.set_line_width(1)
    pdf.set_draw_color(255, 0, 0)
    for index_news, news_dict in enumerate(data['items']):
        pdf.set_font("TimesNewRoman", size=20)
        pdf.line(20, pdf.get_y() - 10, effective_page_width, pdf.get_y() - 10)
        pdf.multi_cell(effective_page_width, 10, news_dict['title'])
        if news_dict['contain_image']:
            download_image_and_paste_in_pdf(pdf, news_dict, index_news)
        pdf.multi_cell(effective_page_width, 10, news_dict['published'])
        pdf.multi_cell(effective_page_width, 10, news_dict['summary'][news_dict['summary'].rfind(']') + 1:])
        pdf.set_font("TimesNewRoman", size=15)
        pdf.ln(5)
        pdf.multi_cell(effective_page_width, 10, 'Link on news:\n' + news_dict['link'])
        if news_dict['contain_image']:
            pdf.multi_cell(effective_page_width, 10, 'Link on image:\n' + news_dict['link_on_image'])
        pdf.ln(40)
    try:
        pdf.output(filename, 'F')
    except PermissionError:
        raise RssReaderException.FileException(f'close file:\n{filename}')
Esempio n. 17
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.add_font('DejaVu',
                 '',
                 os.path.join(common.basepath, 'font/DejaVuSansCondensed.ttf'),
                 uni=True)
    pdf.set_font('DejaVu', '', 14)

    # Note: this line cause syntax error in Python 3.0-3.2
    text = u"""
Veľké písmená
A   Á   Ä   B   C   Č   D   Ď   DZ  DŽ  E   É   F   G   H   CH  I   Í   J   K   L   Ĺ   Ľ
Malé písmená
a   á   ä   b   c   č   d   ď   dz  dž  e   é   f   g   h   ch  i   í   j   k   l   ĺ   ľ
Veľké písmená
M   N   Ň   O   Ó   Ô   P   Q   R   Ŕ   S   Š   T   Ť   U   Ú   V   W   X   Y   Ý   Z   Ž
Malé písmená
m   n   ň   o   ó   ô   p   q   r   ŕ   s   š   t   ť   u   ú   v   w   x   y   ý   z   ž
"""

    pdf.write(8, text)
    pdf.ln(8)
    pdf.output(outputname, 'F')
Esempio n. 18
0
def create_pdf_file(cmd_args, all_news):
    """
    Creates and fills in the PDF file with the required data
    """
    path_to_pdf = create_path_to_file(cmd_args.to_pdf, 'RSS_NEWS.pdf')

    # --- normal cache mode ---
    set_global("FPDF_CACHE_MODE", 0)

    pdf = FPDF(orientation='P', unit='mm', format='A4')
    pdf.set_margins(5, 10, 5)
    pdf.add_page()

    # use downloaded unicode font
    pdf.add_font('dejavu',
                 '',
                 os.path.join(FONT_PATH, 'DejaVuSans.ttf'),
                 uni=True)

    pdf.set_font('dejavu', size=20)
    pdf.set_text_color(5, 14, 110)
    pdf.cell(200, 10, txt=f'RSS News', ln=1, align="C")
    pdf.ln(10)
    pdf.set_text_color(0, 0, 0)

    for new in all_news:
        add_new_to_pdf(cmd_args, new, pdf)

    LOGGER.info(f'Download PDF file with required news to the {path_to_pdf}')

    try:
        pdf.output(path_to_pdf, 'F')
    except FileNotFoundError:
        raise PATHError('Setted PATH is invalid')
Esempio n. 19
0
def generate(pdfname):
    datamanager = DataManager('127.0.0.1', 27017) 

    pdf = FPDF()

    pdf.add_page()
    pdf.set_author('GRE Master')
    pdf.set_title('GRE Word')
    #pdf.set_font('Arial', 'B', 16)

    pdf.add_font('eunjin', '', 'Eunjin.ttf', uni=True)
    pdf.set_font('eunjin', '', 16)

    pdf.add_font('bangwool', '', 'Bangwool.ttf', uni=True)
    pdf.set_font('bangwool', '', 16)

    #pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)
    #pdf.set_font('DejaVu', '', 16)

    for row in datamanager.find():
        text = row['text']
        meanings = row['meaning']
        synonyms = row['synonyms']

        meaning = ','.join(meanings)
        synonym = u','.join(synonyms)

        line = '%s : %s \n synonyms : %s' % (text, meaning, synonym)

        #pdf.cell(20, 10, row['text'], 0, 0)# + '  ' + ','.join(row['meaning']))
        pdf.multi_cell(0, 8, line, 1, 'J')
    pdf.output(pdfname, 'F')
Esempio n. 20
0
def output(player, q_list, a_list, c_list):
    pdf = FPDF()
    pdf.add_page()

    pdf.add_font('Roboto', '', 'font/Roboto-Regular.ttf', uni=True)
    pdf.set_font('Roboto', '', 20)

    pdf.cell(200, 10, f'Hráč {player}', 0, 1, 'C')

    pdf.set_font('Roboto', '', 10)
    
    for idx, line in enumerate(q_list):
        # Otázka
        pdf.set_text_color(0, 0, 0)
        pdf.cell(40, 10, q_list[idx], 0, 1)

        # Odpověď
        try:
            if c_list[idx] == 1:
                pdf.set_text_color(0, 255, 0)
            else:
                pdf.set_text_color(255, 0, 0)
            pdf.cell(180, 10, a_list[idx], 0, 1, 'R')
        except IndexError:
            raise Exception("Program byl příliš brzo ukončen!")

        if idx == 11:
            pdf.cell(40, 10, '', 0, 1)

    pdf.output(f'hrac{player}.pdf', 'F')
Esempio n. 21
0
def hourpdf(request): # use to see working of temporary employee.
    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page()
    ganY = [46, 54]  # line bettwen collumn.
    
    pdf.add_font('Kinnari', '', 'Kinnari.ttf', uni=True)
    pdf.set_font('Kinnari', '', 12)
    
    gen_single_text(pdf, 60, u'ใบลงเวลาทำงานลูกจ้างชั่วคราวรายชั่วโมง')
    gen_single_text(pdf, 45, u'มหาวิทยาลัยเทคโนโลยีพระจอมเกล้าพระนครเหนือ')
    gen_single_text(pdf, 70, u'ชื่อ')
    
    pdf.ln(8)
    pdf.cell(0, 18, u'    วัน           วันที่ เดือน ปี          เวลาทำงาน      รวมชั่วโมง       ลายมือชื่อ          หมายเหตุ')
    drawAttr2(pdf, ganY[0], ganY[1], True)
    
    gen_single_text(pdf, 90, u'รวมจำนวนชั่วโมง ' + u'ชั่วโมง') # call spacial funtion to write a text per line.
    gen_single_text(pdf, 90, u'อัตรา 45.45 บาท ชั่วโมง')
    gen_single_text(pdf, 90, u'รวมเป็นเงินทั้งสิ้น' + u'บาท')
    gen_single_text(pdf, 90, u'(                   )')
    gen_single_text(pdf, 90, u'ได้ตรวจสอบถูกต้องแล้ว')
    gen_single_text(pdf, 75, u'ลงชื่อ.......................................................')
    gen_single_text(pdf, 80, u'(...................................................)')
    
    pdf.output("group3/hour.pdf", 'F')
    
    with open('group3/hour.pdf', 'rb') as pdf: # path to pdf in directory views.
        response = HttpResponse(pdf.read(),content_type='application/pdf')
        response['Content-Disposition'] = 'filename=hour.pdf'
        return response
    pdf.closed
Esempio n. 22
0
def document(args):

    year = time.strftime('%Y')
    month = time.strftime('%m')
    day = time.strftime('%d')
    hour = time.strftime('%H')
    minute = time.strftime('%M')

    if (args.sexe == 'H'):
        sexe = ''
        genre = 'M.'
    else:
        sexe = 'e'
        genre = 'Mme'
    if (args.motif == 'Convocation'):
        motif = "Convocation judiciaire ou administrative et pour se rendre dans un service public"
    if (args.motif == 'Missions'):
        motif = "Participation à des missions d'intérêt général sur demande de l'autorité administrative"
    if (args.motif == 'Handicap'):
        motif = "Déplacement des personnes en situation de handicap et leur accompagnant."
    if (args.motif == 'Santé'):
        motif = "Consultations, examens et soins ne pouvant être assurés à distance et l’achat de médicaments."
    if (args.motif == 'Enfants'):
        motif = "Déplacement pour chercher les enfants à l’école et à l’occasion de leurs activités périscolaires"
    if (args.motif == 'Famille'):
        motif = "Déplacements pour motif familial impérieux, pour l'assistance aux personnes vulnérables et précaires ou la garde d'enfants."
    if (args.motif == 'Sports_animaux'):
        motif = "Déplacements brefs, dans la limite d'une heure quotidienne et dans un rayon maximal d'un kilomètre autour du domicile, liés soit à l'activité physique individuelle des personnes, à l'exclusion de toute pratique sportive collective et de toute proximité avec d'autres personnes, soit à la promenade avec les seules personnes regroupées dans un même domicile, soit aux besoins des animaux de compagnie."
    if (args.motif == 'Travail'):
        motif = "Déplacements entre le domicile et le lieu d’exercice de l’activité professionnelle ou un établissement d’enseignement ou de formation, déplacements professionnels ne pouvant être différés , déplacements pour un concours ou un examen."
    if (args.motif == 'Achats'):
        motif = "Déplacements pour effectuer des achats de fournitures nécessaires à l'activité professionnelle, des achats de première nécessité3 dans des établissements dont les activités demeurent autorisées, le retrait de commande et les livraisons à domicile."

    texte = f'''ATTESTATION DE DÉPLACEMENT DÉROGATOIRE

En application du décret n°2020-1310 du 29 octobre 2020 prescrivant les mesures générales nécessaires pour faire face à l'épidémie de Covid19 dans le cadre de l'état d'urgence sanitaire

Je soussigné{sexe},
{genre} {args.prenom} {args.nom}
Né{sexe} le {args.naissance} à {args.lieu}
Demeurant : {args.adresse} {args.ville} 
certifie que mon déplacement est lié au motif suivant autorisé par le décret n°2020-1310 du 29 octobre 2020 prescrivant les mesures générales nécessaires pour faire face à l'épidémie de Covid19 dans le cadre de l'état d'urgence sanitaire :

{motif}

Fait à {args.ville}
Le {day}/{month}/{year}  à {hour}:{minute}

Signature : {args.prenom} {args.nom}
'''

    file_name = os.path.join('/tmp', f'attestation-{uuid.uuid1()}.pdf')
    pdf = FPDF()
    pdf.add_page()
    pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)
    pdf.set_font('DejaVu', '', 12)
    pdf.multi_cell(180, 10, texte, 0, 'J', False)
    pdf.output(file_name, 'F')

    return file_name
Esempio n. 23
0
def makecards(cards):
    pdf = FPDF('P', 'mm', (WIDTH, HEIGHT))
    pdf.set_left_margin(3.0)
    pdf.set_right_margin(3.0)
    pdf.set_top_margin(3.0)

    # Load our font and then use it
    pdf.add_font('BebasNeue',
                 'B',
                 os.path.expanduser('~/gangserver-assets/BebasNeue.ttf'),
                 uni=True)

    pdf.set_auto_page_break(auto=False)

    for card in cards:
        pdf.add_page()

        # Logo
        pdf.set_y(10)
        pdf.image(os.path.expanduser('~/gangserver-assets/logo.png'),
                  w=LOGO,
                  x=((WIDTH - LOGO) / 2))

        # Name, in a bigger font
        pdf.set_font('BebasNeue', 'B', 20)
        pdf.set_y(LOGO + 15)

        if card['Preferred name'] != '':
            pdf.multi_cell(w=0,
                           h=6,
                           border=0,
                           align='C',
                           txt=card['Preferred name'])
        else:
            pdf.multi_cell(w=0,
                           h=6,
                           border=0,
                           align='C',
                           txt=card['Firstname'])

        pdf.set_y(LOGO + 23)
        pdf.multi_cell(w=0, h=6, border=0, align='C', txt=card['Last name'])

        # Team, in a smaller font
        pdf.set_y(LOGO + 35)
        pdf.set_font('BebasNeue', 'B', 12)
        pdf.multi_cell(w=0, h=6, border=0, align='C', txt=card['Team'])

        # Icons
        if card['Health'] == 'Yes':
            pdf.image(
                os.path.expanduser('~/gangserver-assets/icon_medical.png'),
                w=8,
                x=(WIDTH - 8) / 2,
                y=75)

    handle, filename = tempfile.mkstemp(dir='gangserver/local', suffix='.pdf')
    os.close(handle)
    pdf.output(filename, 'F')
    return filename
Esempio n. 24
0
def create_publication_cert(uuid, name, author, journal, publication_date,
                            created_date):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_margins(25, 15, 15)

    pdf.image(settings.STATIC_ROOT + "/pdf/logo.png", 25, 15, 50)

    pdf.add_font('Arial',
                 '',
                 settings.STATIC_ROOT + '/pdf/arial.ttf',
                 uni=True)

    pdf.set_font('Arial', '', 8)
    pdf.set_draw_color(50, 50, 50)
    pdf.cell(90, 5, ln=1)
    pdf.cell(90)
    pdf.cell(0, 3, "АНС «СибАК» ИНН 5404255395 КПП 540201001", ln=1)
    pdf.cell(90)
    pdf.cell(0,
             3,
             "Адрес: г.Новосибирск, ул. Красный проспект, 165, офис 4",
             ln=1)
    pdf.cell(90)
    pdf.cell(0, 3, "Телефон: 8-913-915-38-00", ln=1)
    pdf.cell(90)
    pdf.cell(0, 3, "Р/с 40703810029100000978 в ОАО АКБ \"АВАНГАРД\"", ln=1)
    pdf.cell(90)
    pdf.cell(0, 3, "к/с 3010181000000000201", ln=1)
    pdf.cell(90)
    pdf.cell(0, 3, "БИК 044525201", ln=1)

    pdf.set_font_size(16)
    pdf.cell(0, 30, "СПРАВКА", ln=1, align="C")

    pdf.set_font_size(12)
    pdf.cell(0,
             6,
             created_date.strftime('%d.%m.%Y') + " No. 14362",
             ln=1,
             align="L")
    pdf.cell(0, 6, ln=1)

    pdf.cell(0, 6, author, ln=1, align="R")

    pdf.cell(0, 6, ln=1)
    spisok = [name, journal, publication_date.strftime('%d.%m.%Y')]
    pdf.multi_cell(
        0, 6, "Издательство подтверждает, что Ваша статья «{}» \
    принята для публикации в научном журнале «{}». \
    Журнал будет опубликован на сайте издательства {}.".format(*spisok))
    pdf.cell(0, 24, ln=1)

    pathlib.Path(settings.MEDIA_ROOT + '/pdf/publication_cert').mkdir(
        parents=True, exist_ok=True)
    pdf.output(
        settings.MEDIA_ROOT + "/pdf/publication_cert/publication_cert_" +
        str(uuid) + ".pdf", 'F')
    return "/pdf/publication_cert/publication_cert_" + str(uuid) + ".pdf"
Esempio n. 25
0
def test_render_en_dash(tmp_path):  # issue-166
    pdf = FPDF()
    font_file_path = HERE / "Roboto-Regular.ttf"
    pdf.add_font("Roboto-Regular", fname=str(font_file_path))
    pdf.set_font("Roboto-Regular", size=120)
    pdf.add_page()
    pdf.cell(w=pdf.epw, txt="–")  # U+2013
    assert_pdf_equal(pdf, HERE / "render_en_dash.pdf", tmp_path)
Esempio n. 26
0
def test_add_font_unicode_with_str_fname_ok(tmp_path):
    pdf = FPDF()
    font_file_path = HERE / "../end_to_end_legacy/charmap/Roboto-Regular.ttf"
    pdf.add_font("Roboto-Regular", fname=str(font_file_path), uni=True)
    pdf.set_font("Roboto-Regular", size=64)
    pdf.add_page()
    pdf.cell(pdf.epw, 20, "Hello World!")
    assert_pdf_equal(pdf, HERE / "add_font_unicode.pdf", tmp_path)
Esempio n. 27
0
def generateDicePDF():
    # save FPDF() class into
    # a variable pdf
    pdf = FPDF()
    pdf.add_page()
    pdf.add_font('Braille', '', 'static/Swell-Braille.ttf', uni=True)

    # set style and size of font
    # that you want in the pdf

    pdf.set_font("Arial", size=30)
    pdf.multi_cell(200,
                   5,
                   txt='Braille Labels for Dice/Spinner\n\n',
                   align='C')
    pdf.set_font("Arial", size=10)
    pdf.multi_cell(
        200,
        5,
        txt='Cut out Braille labels and paste them onto the dice/spinner.\n\n',
        align='C')

    index = 0
    theText = ['0', '0']
    f = open("static/userData/brailleForDice.txt", "r")
    # insert the texts in pdf
    theX = pdf.get_x()
    theY = pdf.get_y()
    for x in f:
        if theX >= 170:
            theX = 5
            theY += 15
            if theY >= 260:
                pdf.add_page()
                theY = 15
        if index == 0:
            pdf.set_xy(theX - 5, theY)
        if index > 0:
            pdf.set_xy(theX + 17, theY)
        if index % 6 == 0:
            if int(theText[0]) > 9:
                theY += 15
            theX = 5
            pdf.set_xy(theX, theY)
        theX = pdf.get_x()
        theY = pdf.get_y()
        theText = x.split(':')
        pdf.set_font("Arial", size=8)
        pdf.multi_cell(15, 10, txt=theText[0], align='R')
        pdf.set_font('Braille', '', size=24)
        pdf.set_xy(theX + 15, theY)
        theX = pdf.get_x()
        theY = pdf.get_y()
        pdf.multi_cell(27, 10, txt=theText[1], align='L', border=1)
        index += 1

    # save the pdf with name .pdf
    pdf.output("static/userData/theDiceSpinner.pdf")
 def write_into_pdf(self, input):
     for code in input:
         print("Gift Code: ", code)
         pdf = FPDF()
         pdf.add_page()
         pdf.add_font('Raleway', '', r'./font/Raleway-SemiBold.ttf', uni=True)
         pdf.set_font(family='Raleway', size=12)
         pdf.text(85.0, 289.2, code)
         pdf.output('./gift-codes/a5-horizontal/gift-code-{}.pdf'.format(code))
Esempio n. 29
0
 def test_ttf(self):
     pdf=FPDF()
     pdf.add_font('test','','font/lmroman7-italic.ttf',uni=True)
     pdf.add_page()
     pdf.set_font('test', '', 14)
     pdf.write(10, 'hello')
     pdf.set_font('test', '', 24)
     pdf.write(10, 'hello')
     pdf.output('out/fpdf/test_ttf.pdf', 'F')
 def write_into_pdf(self, input):
     for code in input:
         print("Gift Code: ", code)
         pdf = FPDF()
         pdf.add_page()
         pdf.add_font('Raleway', '', r'./font/Raleway-SemiBold.ttf', uni=True)
         pdf.set_font(family='Raleway', size=9)
         pdf.text(38.6, 273.4, code)
         pdf.output('./gift-codes/a6-portrait/gift-code-{}.pdf'.format(code))
Esempio n. 31
0
def generate_fidb_pdf(yt_video_title, yt_link, captions_blanks, solutions, RTL):
    '''
    @summary: creates exercise pdf including link to video_title, exercise, and solution
    TODO: Handle language specific fonts https://pyfpdf.readthedocs.io/en/latest/Unicode/index.html
    '''
    # create pdf
    alignment = "L" if RTL is False else "R"

    pdf = FPDF()  # default: Portrait, A4, millimeter unit
    pdf.compress = 0
    # pdf.set_right_margin(20)
    pdf.add_page()
    pdf.add_font('DejaVu', '',
                 '{}/fonts/DejaVuSansCondensed.ttf'.format(
                     os.path.dirname(os.path.realpath(__file__))
                 ), uni=True)

    # video title and fill in blanks on first page
    pdf.set_font('Arial', 'B', 14)
    pdf.cell(w=200, h=10,
             txt="Fill-in-the-blanks exercise!",
             ln=1, align="C")
    pdf.cell(w=200, h=10,
             txt="Watch the following video and fill in the blanks:",
             ln=1, align="C")

    # important!! keep dejavu font so that title can be outputted correctly!
    # dejavu has no bold style
    pdf.set_font("DejaVu", size=14)

    pdf.set_text_color(0, 0, 255)

    title_to_print = yt_video_title  # todo: erase this fix, which limits to n letters
    if len(title_to_print) > 30:
        title_to_print = title_to_print[:30] + "..."

    print(yt_video_title)
    print(yt_video_title[:30])
    # todo: add fix- cell should provide error if string width > cell width; can't use multicell, because multicell does not support http link
    pdf.cell(w=200, h=10, txt=title_to_print,
             link=yt_link, ln=1, align="C")

    pdf.set_text_color(0, 0, 0)

    pdf.set_font("DejaVu", size=12)

    pdf.multi_cell(w=0, h=10, border=1, txt=captions_blanks, align=alignment)

    # solutions on second page
    pdf.add_page()
    pdf.set_font("Arial", "B", size=14)
    pdf.cell(w=200, h=10, txt="Solution:", ln=1, align="C")

    pdf.set_font("DejaVu", size=12)
    pdf.multi_cell(w=0, h=10, border=1, txt=solutions, align=alignment)

    return pdf
Esempio n. 32
0
def test_multi_cell_justified_with_unicode_font(tmp_path):  # issue 118
    pdf = FPDF()
    pdf.add_page()
    pdf.add_font("DejaVu", "", HERE / "../fonts/DejaVuSans.ttf")
    pdf.set_font("DejaVu", "", 14)
    text = 'Justified line containing "()" that is long enough to trigger wrapping and a line jump'
    pdf.multi_cell(w=0, h=8, txt=text, new_x=XPos.LMARGIN, new_y=YPos.NEXT)
    assert_pdf_equal(
        pdf, HERE / "test_multi_cell_justified_with_unicode_font.pdf", tmp_path
    )
Esempio n. 33
0
def generate(txt):
    pdf = FPDF()
    pdf.add_page()
    pdf.add_font("AppleLiGothic", "", "AppleLiGothic-Medium.ttf", uni=True)
    titles(pdf)
    texts(pdf, txt)

    append_payment_method(pdf, "")

    pdf.output('tuto1.pdf', 'F')
Esempio n. 34
0
 def get(self):
     pdf=FPDF()
     pdf.add_page()
     pdf.add_font('DejaVu','','font/DejaVuSansCondensed.ttf',uni=True)
     pdf.set_font('DejaVu','',16)
     #pdf.set_font('Arial','B',16)
     pdf.cell(40,10,u'Hello World! Здравствуй мир')
     pdf.image('images/LoadFile.png', 0, 50)
     self.response.headers['Content-Type'] = 'application/pdf'
     self.response.write(pdf.output('', 'S'))
Esempio n. 35
0
def pdfGen(Input,fontName,Output):
    pdf = FPDF()
    pdf.add_page()
    ttfName=fontName+'.ttf'
    pdf.add_font(fontName, '', ttfName, uni=True) 
    pdf.set_font(fontName, '', 14)
    linestring = open(Input, 'r').read()
    pdf.write(8,linestring)
    pdf.ln(20)
    pdf.output(Output, 'F')
Esempio n. 36
0
def test_add_font_with_str_fname_ok(tmp_path):
    font_file_path = HERE / "Roboto-Regular.ttf"
    for font_cache_dir in (True, str(tmp_path), None):
        with pytest.warns(DeprecationWarning):
            pdf = FPDF(font_cache_dir=font_cache_dir)
            pdf.add_font("Roboto-Regular", fname=str(font_file_path))
            pdf.set_font("Roboto-Regular", size=64)
            pdf.add_page()
            pdf.cell(txt="Hello World!")
            assert_pdf_equal(pdf, HERE / "add_font_unicode.pdf", tmp_path)
Esempio n. 37
0
 def write_file_pdf_fpdf(self):
     file = '/home/anton/PycharmProjects/training/DedMoroz/' + str(
         self.name) + '.pdf'
     pdf = FPDF()
     #pdf.SYSTEM_TTFONTS = '/some/path'
     pdf.add_font('DejaVuSerif', '', 'DejaVuSerif.ttf', uni=True)
     pdf.add_page()
     pdf.set_font("DejaVuSerif", size=15)
     pdf.multi_cell(200, 5, txt=self.out_message)
     pdf.output(file)
Esempio n. 38
0
def test_add_core_fonts():
    font_file_path = HERE / "Roboto-Regular.ttf"
    pdf = FPDF()
    pdf.add_page()
    pdf.add_font("Helvetica", fname=font_file_path)
    pdf.add_font("Helvetica", style="B", fname=font_file_path)
    pdf.add_font("helvetica", style="IB", fname=font_file_path)
    pdf.add_font("times", style="", fname=font_file_path)
    pdf.add_font("courier", fname=font_file_path)
    assert not pdf.fonts  # No fonts added, as all of them are core fonts
Esempio n. 39
0
 def test_unicode_font(self):
     pdf=FPDF()
     pdf.add_page()
     #pdf.add_font('DejaVu','','font/DejaVuSansCondensed.ttf',uni=True)
     pdf.add_font('DejaVu','I','font/DejaVuSerif-Italic.ttf',uni=True)
     pdf.set_font('DejaVu','I',16)
     #pdf.set_font('Arial','B',16)
     pdf.cell(40,10,u'Здравствуй мир  \u2200 x \u2203 y \u223c \u221e')
     pdf.output('HelloWorld.pdf', 'F')
     
     
Esempio n. 40
0
def plate(request):
	try:
		o = Order.objects.filter(session=request.shop_session, is_history=True).latest('id')
		config, create = ConfigModel.objects.get_or_create(id=1)
		domain = Site.objects.get_current().domain
	except: pass
	else:	
		if config.organization and config.office1 and o.address and o.name:
			pdf = FPDF('P','mm','A4')
			pdf.set_author(domain)
			pdf.add_page()
			pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)
			pdf.add_font('DejaVuBold', '', 'DejaVuSansCondensed-Bold.ttf', uni=True)
			pdf.set_fill_color(229, 229, 229);
			
			pdf.set_font('DejaVu', '', 5);
			pdf.write(9, _(u"Created by %(date)s on %(domain)s. Order #%(id)d.") % {'date':datetime.datetime.now().strftime('%d.%m.%Y %H:%M'), 'domain':domain, 'id':o.id})
			pdf.ln(9)
				
			pdf.set_font('DejaVuBold', '', 9);
			pdf.write(9, _(u"Recipient:"))
			pdf.ln(9)
			
			pdf.set_font('DejaVu', '', 8);
			if config.office1:
				pdf.write(5, _(u"Address: %s") % config.office1)
				pdf.ln(5)
			if config.organization:
				pdf.write(5, _(u"Name: %s") % config.organization)
				pdf.ln(5)
				
			pdf.set_font('DejaVuBold', '', 9);
			pdf.write(9, _(u"Sender:"))
			pdf.ln(9)
			
			pdf.set_font('DejaVu', '', 8);
			if o.address:
				pdf.write(5, _(u"Address: %s") % o.address)
				pdf.ln(5)
			if o.name:
				pdf.write(5, _(u"Name: %s") % o.name)
				pdf.ln(9)
				
			pdf.set_font('DejaVu', '', 5);
			pdf.write(5, _(u"Cut and paste on the packaging"))
			pdf.ln(5)
				
			s = pdf.output('Plate.pdf', 'S')
			
			response = HttpResponse(s, mimetype='application/pdf; charset=cp1251')
			response['Content-Disposition'] = 'attachment; filename=plate.pdf'
			return response
	return HttpResponse('')
Esempio n. 41
0
def pdfGen(request):
    pdf = FPDF()
    pdf.add_page()
    #pdf.add_font('gargi', '', 'gargi.ttf', uni=True) 
    #pdf.set_font('gargi', '', 14)
    #pdf.write(8, u'Hindi: एक अमरीकि')
    pdf.add_font('Kedage-b', '', 'Kedage-b.ttf', uni=True) 
    pdf.set_font('Kedage-b', '', 14)
    #pdf.add_font('TSCu_SaiIndira', '', 'TSCu_SaiIndira.ttf', uni=True) 
    #pdf.set_font('TSCu_SaiIndira', '', 14)
    linestring = open('DigiFiles/KannadaInput.txt', 'r').read()
    pdf.write(8,linestring)
    pdf.ln(20)
    pdf.output("DigiFiles/KannadaOutput.pdf", 'F')
Esempio n. 42
0
 def test_greek_letters(self):
     pdf=FPDF()
     initPDF(pdf)
     setFontPDF(pdf,'symbol')
     
     p = lp.ListParser( lp.CommandParser(lp.ParagraphItemCreator) )
     s = r'\alpha\beta\gamma'
     p.match( s )
     self.assertTrue( p.hasMatch() )
     res =  p[0].docItem.writePDF()+' '+p[1].docItem.writePDF()+' '+p[2].docItem.writePDF()
     self.assertEquals( res, u'\u03b1 \u03b2 \u03b3')
     
     pdf.write(0, res)
     pdf.add_font('djv','','font/DejaVuSans.ttf',uni=True)
     pdf.set_font('djv','',12)
     pdf.write(0, u'  \u23a8 \u23a7 \u23a9 \u23aa \u239e \u2320 \u2321 \u23ae')
     
     pdf.ln(10)
     pdf.add_font('smb','','font/Symbola.ttf',uni=True)
     pdf.set_font('smb','',12)
     pdf.write(0, u'  \u23b7 \u03b1 \u03b2 \u03b3')
     
     pdf.ln(10)
     pdf.add_font('jax','','font/mathjax_amsregular.ttf',uni=True)
     pdf.set_font('jax','',12)
     pdf.write(0, u' abc \u23b7 \u03b1 \u03b2 \u03b3')
     
     pdf.ln(10)
     pdf.add_font('jax','','font/MathJax/ttf/mathjax_size1regular.ttf',uni=True)
     pdf.set_font('jax','',12)
     pdf.write(0, u' abc \u23b7 \u03b1 \u03b2 \u03b3')
     
     
     pdf.output('out/latex/test_greek_letters.pdf', 'F')
Esempio n. 43
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    # Add a Unicode font (uses UTF-8)
    pdf.add_font("DejaVu", "", os.path.join(common.basepath, "font", "DejaVuSansCondensed.ttf"), uni=True)
    pdf.set_font("DejaVu", "", 14)

    # Load a UTF-8 string from a file and print it
    with open(os.path.join(common.basepath, "HelloWorld.txt"), "rb") as file:
        txt = file.read().decode("UTF-8")
    pdf.write(8, txt)

    pdf.output(outputname, "F")
Esempio n. 44
0
def dotest(outputname, nostamp):

    pdf = FPDF()
    pdf.set_font('Arial','',14)
    s = 'Texto largo que no cabe en esta celda pero que será ajustado'
    w = pdf.get_string_width(s)
    if not nostamp:
        print (s, w)
    assert round(w, 2) == 135.90
    pdf.add_font('DejaVu', '', './font/DejaVuSans.ttf', uni=True)
    pdf.set_font('DejaVu', '', 14)
    s = u('Texto largo que no cabe en esta celda pero que será ajustado') 
    w = pdf.get_string_width(s)
    if not nostamp:
        print (s, w)
    assert round(w, 2) == 153.64
Esempio n. 45
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    # Add a Unicode font (uses UTF-8)
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, "font", 'DejaVuSansCondensed.ttf'), \
        uni = True)
    pdf.set_font('DejaVu','',14)

    # Load a UTF-8 string from a file and print it
    txt = open(os.path.join(common.basepath, "HelloWorld.txt"), "rb").\
        read().decode("UTF-8")
    pdf.write(8, txt)


    pdf.output(outputname, 'F')
Esempio n. 46
0
class PDF():
    """Basic export class. See Usage in module doc.
    """
    def __init__(self, fname, ffamily=None, fstyle='', fsize=0, ffname=None, fonts=None):
        """fname - name of the output pdf file
        you can initialize fonts in more ways, explicit (applies .add_font of fpdf) or explicit:
         - explicit with fonts= (see the implicit code bellow with DejaVu fonts where font styles B,I,BI are supported)
         - explicit with ffamily where just one font will be added
         - implicit DejaVu, if unicode fonts are installed for the fpdf package (in its font/ directory and so on)
         - implicit Arial, if fpdf cannot find unicode fonts
        """
        self.w_fname = fname
        self.w_pdf = FPDF()
        self.w_pdf.utils = Utils(self.w_pdf)
        self.w_pdf.add_page()
        explicit = ffamily or fonts
        if explicit:
            if not fonts:
                fonts = [(ffamily, '', ffname)] if ffname else []
        else:
            # try Unicode fonts from fpdf/font (or location defined by SYSTEM_TTFONTS or FPDF_FONTPATH) first
            fonts = [
                ('DejaVu', '', 'DejaVuSansCondensed.ttf'),
                ('DejaVu', 'B', 'DejaVuSansCondensed-Bold.ttf'),
                ('DejaVu', 'I', 'DejaVuSansCondensed-Oblique.ttf'),
                ('DejaVu', 'BI', 'DejaVuSansCondensed-BoldOblique.ttf'),
            ]
        try:
            for font in fonts:
                self.w_pdf.add_font(font[0], font[1], font[2], uni=True)
            self.w_pdf.set_font(fonts[0][0] if fonts else ffamily)
        except RuntimeError:
            if not explicit:    # fallback from unicode to latin-1
                self.w_pdf.set_font('Arial')
            else:
                raise RuntimeError(FONT_ERROR)

    def __enter__(self):
        return self.w_pdf

    def __exit__(self, *args):
        self.w_pdf.utils = None
        self.w_pdf.output(self.w_fname, 'F')
Esempio n. 47
0
def decodage(filename):

	# Je cherche l'encodage de mon fichier grâce à chardet
	rawdata = open(filename, 'r').read(100)
	codage = chardet.detect(rawdata)
	source = codage['encoding']

	# Je prépare mon PDF, j'utilise pyfpdf
	pdf=FPDF('P','pt','A4')
	pdf.add_page()
	# J'utlise une jolie police de caractère dont je doit indiqué le chemin (sur Mac OSX)
	pdf.add_font('fireflysung', '', '/Library/Fonts/fireflysung.ttf', uni=True)
	pdf.set_font('fireflysung','', 12)
	# Je décode et j'encode mon texte
	txt=file(filename).read().decode(source, errors='ignore').encode('utf8')
	pdf.write(14, txt)
	# Je retravaille le nom du fichier
	ext=os.path.basename(filename) # j'enlève le chemin
	namefile=os.path.splitext(ext)[0] # j'enlève l'extension
	# Je finalise le pdf
	pdf.output('/path/to/new_' + namefile + '.pdf','F')
Esempio n. 48
0
def dotest(outputname, nostamp):
    fpdf.set_global("FPDF_CACHE_MODE", 1)
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    # Add a Unicode font (uses UTF-8)
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, "font", 'DejaVuSans.ttf'), \
        uni = True)
    pdf.set_font('DejaVu', '', 14)
    with open(os.path.join(common.basepath, "HelloWorld.txt"), "rb") as file:
        txt = file.read().decode("UTF-8")

    if not nostamp:
        text(pdf, txt, 100, nostamp)
    text(pdf, txt, 75, nostamp)
    text(pdf, txt, 125, nostamp)

    pdf.output(outputname, 'F')
Esempio n. 49
0
 def test_ParagraphParaser(self):
     
     p = lp.ParagraphParser()
     s = r'\alpha+\beta=gamma'
     p.match(s)
     self.assertTrue( p.hasMatch() )
     self.assertEquals( p.getMatch(s), r'\alpha+\beta=gamma' )
     self.assertEquals( p.docItem.writePDF(), u'α + β =gamma ' )
     
     p = lp.ParagraphParser()
     f = open('20k_c1.txt','rU')
     s = f.read()
     f.close()
     p.match(s)
     self.assertTrue( p.hasMatch() )
     
     pdf=FPDF()
     pdf.add_page()
     pdf.add_font('DejaVu','','font/lmroman7-regular.ttf',uni=True)
     pdf.set_font('DejaVu','',11)
     pdf.write(10, p.docItem.writePDF())
     pdf.output('out/latex/test.pdf', 'F')
Esempio n. 50
0
def generate_pdf(card):
    """
    Make a PDF from a card

    :param card: dict from fetcher.py
    :return: Binary PDF buffer
    """
    from eclaire.base import SPECIAL_LABELS

    pdf = FPDF('L', 'mm', (62, 140))
    pdf.set_margins(2.8, 2.8, 2.8)
    pdf.set_auto_page_break(False, margin=0)

    pdf.add_page()

    font = pkg_resources.resource_filename('eclaire', 'font/Clairifont.ttf')
    pdf.add_font('Clairifont', fname=font, uni=True)
    pdf.set_font('Clairifont', size=48)

    pdf.multi_cell(0, 18, txt=card.name.upper(), align='L')

    qrcode = generate_qr_code(card.url)
    qrcode_file = mktemp(suffix='.png', prefix='trello_qr_')
    qrcode.save(qrcode_file)
    pdf.image(qrcode_file, 118, 35, 20, 20)
    os.unlink(qrcode_file)

    # May we never speak of this again.
    pdf.set_fill_color(255, 255, 255)
    pdf.rect(0, 55, 140, 20, 'F')

    pdf.set_font('Clairifont', '', 16)
    pdf.set_y(-4)
    labels = ', '.join([label.name for label in card.labels
                        if label.name not in SPECIAL_LABELS])
    pdf.multi_cell(0, 0, labels, 0, 'R')

    return pdf.output(dest='S')
Esempio n. 51
0
def text_download(request, title, file_format, juan=0):
    """
    Download a text or a single chapter as plain text file
    or as a (colored) pdf.
    """
    import pinyin

    pinyin_title = pinyin.get(title)

    qs = QuerySet(using=ExistDB(), xpath='/tei:TEI',
                  collection='docker/texts/', model=RocheTEI)

    qs = qs.filter(title=title)
    if juan:
        qs = qs.filter(chapter=juan)


    result = ""
    for q in qs:
        for d in q.body.div:
            result += d.text.replace(" ", "").replace("\n", "").replace("\t", "").replace(u"。", u"。\n\n")

    if file_format == 'txt':
        response = HttpResponse(content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename="{}.txt"'.format(pinyin_title)
        response.write(result)
    else:
        from fpdf import FPDF

        pdf = FPDF(unit='mm', format='A4')
        pdf.add_page()
        pdf.add_font('Droid', '', 'DroidSansFallbackFull.ttf', uni=True)
        pdf.set_font('Droid', '', 12)
        pdf.write(5, unicode(result))
        response = HttpResponse(pdf.output(dest='S'), content_type='application/pdf') 
        response['Content-Disposition'] = 'attachment; filename="{}.pdf"'.format(pinyin_title)

    return response
Esempio n. 52
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.add_font('DejaVu', '', os.path.join(common.basepath, 
        'font/DejaVuSansCondensed.ttf'), uni = True)
    pdf.set_font('DejaVu', '', 14)

    # Note: this line cause syntax error in Python 3.0-3.2
    text = u"""
Veľké písmená
A   Á   Ä   B   C   Č   D   Ď   DZ  DŽ  E   É   F   G   H   CH  I   Í   J   K   L   Ĺ   Ľ
Malé písmená
a   á   ä   b   c   č   d   ď   dz  dž  e   é   f   g   h   ch  i   í   j   k   l   ĺ   ľ
Veľké písmená
M   N   Ň   O   Ó   Ô   P   Q   R   Ŕ   S   Š   T   Ť   U   Ú   V   W   X   Y   Ý   Z   Ž
Malé písmená
m   n   ň   o   ó   ô   p   q   r   ŕ   s   š   t   ť   u   ú   v   w   x   y   ý   z   ž
"""

    pdf.write(8, text)
    pdf.ln(8)
    pdf.output(outputname, 'F')
Esempio n. 53
0
 def test_pdf_cell(self):
     pdf=FPDF()
     pdf.c_margin = 0.0
     pdf.add_font('symbol','','font/DejaVuSans.ttf',uni=True)
     pdf.add_page()
     f = 0.81
     font_name = 'times'
     
     text = 'small text'
     pdf.set_font(font_name,'',12)
     x,y = pdf.get_x(), pdf.get_y()
     w = pdf.get_string_width(text)
     h = pdf.font_size_pt / pdf.k
     pdf.cell(w, h, text)
     pdf.rect(x, y, w, h, '')
     pdf.line(x, y + f * h, x + w, y + f * h)
     
     text = 'Large text'
     pdf.set_font(font_name,'',24)
     x,y = pdf.get_x(), pdf.get_y()
     w = pdf.get_string_width(text)
     h = pdf.font_size_pt / pdf.k
     pdf.cell(w,h, text)
     pdf.rect(x, y, w, h, '')
     pdf.line(x, y + f * h, x + w, y + f * h)
     
     text = 'Larger text'
     pdf.set_font(font_name,'',48)
     x,y = pdf.get_x(), pdf.get_y()
     w = pdf.get_string_width(text)
     h = pdf.font_size_pt / pdf.k
     pdf.cell(w,h, text)
     pdf.rect(x, y, w, h, '')
     pdf.line(x, y + f * h, x + w, y + f * h)
     
     pdf.output('out/fpdf/test_pdf_cell.pdf', 'F')
    def handle(self, *args, **options):
    
        skaters = Skater.objects.exclude(status__name="inactive").order_by("derby_name")

        pdf=FPDF()
        pdf.add_font('DejaVu','','/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansCondensed.ttf',uni=True)
        
        for skater in skaters:
            
            pdf.add_page()
            pdf.set_margins(16, 2)
            pdf.ln(20)

            pdf.set_font('DejaVu','',16)
            pdf.cell(40,40,'Derby Name:')
            pdf.set_font('DejaVu','',48)
            pdf.cell(40,40, skater.derby_name)
            pdf.ln(20)

            pdf.set_font('DejaVu','',16)
            pdf.cell(40,40,'Real Name:')
            pdf.set_font('DejaVu','',24)
            pdf.cell(40,40, skater.first_name + " " + skater.last_name)
            pdf.ln(20)
            
            pdf.set_font('DejaVu','',16)
            pdf.cell(60,40,'Date of Birth:')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, str(skater.dob))
            pdf.ln(10)
            
            pdf.set_font('DejaVu','',16)
            pdf.cell(60,40,'Emergency Contact:')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, skater.emergency_contact)
            pdf.ln(10)
            pdf.cell(60,40,'')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, skater.emergency_phone)
            pdf.ln(10)
            pdf.cell(60,40,'')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, skater.emergency_relationship)
            pdf.ln(15)
            
            pdf.set_font('DejaVu','',16)
            pdf.cell(60,40,'Insurance Provider:')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, skater.insurance_provider)
            pdf.ln(15)
            
            pdf.set_font('DejaVu','',16)
            pdf.cell(60,40,'Hosptial Preference:')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, skater.hospital)
            pdf.ln(15)
            
            pdf.set_font('DejaVu','',12)
            pdf.multi_cell(0,40,'Medical Conditions:')
            pdf.ln(-15)
            pdf.set_font('DejaVu','',24)
            if skater.medical_details == "":
                details = "<none>"
            else:
                details = skater.medical_details
            
            pdf.write(12, details)
            pdf.ln(25)

            wftda = ""
            try:
                wftda = int(skater.wftda_number)
            except:
                pass

            pdf.set_font('Courier','',7)
            pdf.write(4, 'MWD #' + str(skater.id) + " | " + str(skater.email) + " | WFTDA #" + str(wftda) + " | generated on " + strftime("%Y-%m-%d", gmtime()))


        pdf.output('test.pdf','F')
Esempio n. 55
0
    + "]["
    + pdf_punct
    + "]|[\x00-\x7F][\x00-\x7F]|[\x00-\x7F]["
    + pdf_punct
    + "]|["
    + pdf_punct
    + "][\x00-\x7F])"
)
rsrcmgr = PDFResourceManager()
fp = file(options.in_file, "rb")
pagenos = set()

font_size = 9

pdf = FPDF("P", "mm", "A4")
pdf.add_font("DejaVu", "", "fireflysung.ttf", uni=True)
pdf.set_font("DejaVu", "", font_size)

page_count = 1
ASCII = "".join(chr(x) for x in range(128))


def parse_lt_objs(lt_objs, page_number):
    text_content = []
    images = []

    if lt_objs:
        if isinstance(lt_objs, LTTextBox) or isinstance(lt_objs, LTText):
            text_content.append(lt_objs.get_text().strip())
        elif isinstance(lt_objs, LTImage):
            images.append(lt_objs.stream.get_data())
Esempio n. 56
0
from fpdf import FPDF

#font_file_name = 'font/mathjax_amsregular.ttf'
font_file_name = 'font/MathJax/ttf/mathjax_size4regular.ttf'

size = 10
pdf = FPDF()
pdf.add_page()
pdf.add_font('jax','',font_file_name,uni=True)

lb = 0
for n in range(0xeffc):
    c = unichr(n)
    pdf.set_font('jax','',size)
    w = pdf.get_string_width(c)
    if w > 0:
        pdf.set_font('times','',size)
        pdf.cell(13, 10, hex(n) + ': ' )
        pdf.set_font('jax','',size)
        pdf.cell(10, 10, c)
        if lb == 6: 
            pdf.ln(10)
            lb = 0
        else:
            lb += 1
    #print unichr(i)
pdf.output('out/latex/font_view.pdf', 'F')
print 'done'
Esempio n. 57
0
    def getCMAP4(self, unicode_cmap_offset, glyphToChar, charToGlyph):
        TTFontFile.getCMAP4(self, unicode_cmap_offset, glyphToChar, charToGlyph)
        self.saveChar = charToGlyph
        
    def getCMAP12(self, unicode_cmap_offset, glyphToChar, charToGlyph):
        TTFontFile.getCMAP12(self, unicode_cmap_offset, glyphToChar, charToGlyph)
        self.saveChar = charToGlyph


pdf=FPDF()
pdf.compression = True
pdf.add_page()

#fontpath = "font/DroidSansFallback.ttf"
fontpath = "font/DejaVuSans.ttf"
pdf.add_font("font", '', fontpath, uni = True)
ttf = MyTTFontFile()
ttf.getMetrics(fontpath)

if sys.version_info >= (3, 0):
    unichr = chr

pdf.set_font("font", '', 10)

# create PDF with first 999 charters in font
cnt = 0
for char in ttf.saveChar:
    cnt += 1
    pdf.write(8, u"%03d) %06x - %c" % (cnt, char, char))
    pdf.ln()
    if cnt >= 999:
Esempio n. 58
0
#!/usr/bin/env python

"Simple test to check alias_nb_pages replacement under unicode fonts"

from fpdf import FPDF

pdf=FPDF()

# set default alias: {nb} that will be replaced with total page count
pdf.alias_nb_pages()

# Add a Unicode font (uses UTF-8)
pdf.add_font('DejaVu','','DejaVuSansCondensed.ttf',uni=True)
pdf.set_font('DejaVu','',14)

for i in range(5):
    pdf.add_page()
    pdf.set_font('Arial','B',16)
    pdf.cell(40,10,'Hello World! {nb}')
    pdf.set_font('DejaVu','',14)
    pdf.cell(40,10,'Hello World! unicode {nb}')
    
fn = 'nb_pages.pdf'
pdf.output(fn, 'F')

import os
try:
    os.startfile(fn)
except:
    os.system("xdg-open \"%s\"" % fn)
Esempio n. 59
0
def create_qc_pdf(**kwargs):
    try:
        kwargs['company'] = kwargs.get('company', u'台茂化工儀器原料行')
        kwargs['product'] = kwargs.get('product', u'product name?')
        kwargs['ASE_pn'] = kwargs.get('ASE_pn', u'ASE PN?')
        if not kwargs.get('lot_no'):
            kwargs['make_date'] = date.today()
            kwargs['test_date'] = date.today()
            kwargs['lot_no'] = u'lot number?'
        else:
            year = 2000 + int(kwargs['lot_no'][1:3])
            month = int(kwargs['lot_no'][3:5])
            day = int(kwargs['lot_no'][5:7])
            kwargs['make_date'] = date(year, month, day)
            kwargs['test_date'] = date(year, month, day)
        kwargs['exp_period'] = kwargs.get('exp_period', u'一年')
        kwargs['amount'] = kwargs.get('amount', u'amount?')
        kwargs['tester'] = kwargs.get('tester', u'tester?')
        kwargs['test_params'] = kwargs.get('test_params', [])
    except Exception as e:
        print e
        return

    # Set placement and style of values
    tm_branch = dict(x=30, y=25, w=178-30, h=10, align='C')
    product_name = dict(x=31, y=50, w=104-31, h=15, align='L')
    product_ASE_pn = dict(x=105, y=50, w=104-31, h=15, align='L')

    make_date = dict(x=31, y=65, w=104-31, h=8, align='L')
    test_date = dict(x=31, y=73, w=104-31, h=8, align='L')
    exp_period = dict(x=31, y=81, w=104-31, h=9, align='L')

    lot_no = dict(x=105, y=65, w=104-31, h=8, align='L')
    amount = dict(x=105, y=73, w=104-31, h=8, align='L')
    tester = dict(x=105, y=81, w=104-31, h=9, align='L')


    # Create PDF
    FPDF = myPDF('P','mm','A4')
    FPDF.set_compression(False)
    FPDF.set_creator('TM_2014')
    FPDF.set_title(u'Quality inspection report for lot# {}'.format(kwargs['lot_no']))
    FPDF.set_author(u'Taimau Chemicals')
    FPDF.set_subject(kwargs['lot_no'])
#    FPDF.set_subject(u'{} {}'.format(kwargs['product'], kwargs['lot_no']), isUTF8=True)
    FPDF.alias_nb_pages()
    FPDF.add_page() # Adding a page also creates a page break from last page


    FPDF.add_font(family=u'SimHei', style='', fname=font, uni=True) # Only .ttf and not .ttc

    FPDF.set_font(family=u'SimHei', style='', size=16)
    FPDF.xycell(txt=kwargs['company'], **tm_branch)

    FPDF.set_font(family=u'SimHei', style='B', size=13)
    FPDF.xycell(txt=u'產品: {}'.format(kwargs['product']), **product_name)
    FPDF.xycell(txt=u'料號: {}'.format(kwargs['ASE_pn']), **product_ASE_pn)

    FPDF.xycell(txt=u'製造日期: {}'.format(kwargs['make_date']), **make_date)
    FPDF.xycell(txt=u'檢驗日期: {}'.format(kwargs['test_date']), **test_date)
    FPDF.xycell(txt=u'保存期間: {}'.format(kwargs['exp_period']), **exp_period)

    FPDF.xycell(txt=u'批號: {}'.format(kwargs['lot_no']), **lot_no)
    FPDF.xycell(txt=u'生產數量: {}'.format(kwargs['amount']), **amount)
    FPDF.xycell(txt=u'取樣人員: {}'.format(kwargs['tester']), **tester)

    FPDF.set_left_margin(30)
    FPDF.set_xy(x=30, y=105)
    for (a, b, c) in kwargs['test_params']:
        if a+b+c == u'':
            break
        FPDF.cell(49, 10, txt=a, align='C')
        FPDF.cell(49, 10, txt=b, align='C')
        FPDF.cell(49, 10, txt=c, align='C')
        FPDF.ln()
    FPDF.cell(49)
    FPDF.cell(49, 10, txt=u'以下空白', align='C')




    initialfilename = u'QC_{}_{}'.format(kwargs['product'], kwargs['lot_no'])
    FILE_OPTS = dict(
        title = u'PDF name and location.',
        defaultextension = '.pdf',
        initialdir = os.path.expanduser('~') + '/Desktop/',
        initialfile = initialfilename,
    )
    if settings.load().get(u'pdfpath'):
        FILE_OPTS['initialdir'] = settings.load()[u'pdfpath']

    outfile = os.path.normpath(tkFileDialog.asksaveasfilename(**FILE_OPTS))


    if os.path.exists(outfile):
        os.remove(outfile)
    if outfile and not os.path.exists(outfile):
        FPDF.output(name=outfile)

        try:
            subprocess.call(['start', outfile],
                             shell=True)
            return
        except:
            pass

        try:
            print u'Trying alternate subprocess command.'
            subprocess.call(['start', '/D'] +
                            list(os.path.split(outfile)),
                            shell=True)
            return
        except UnicodeEncodeError:
            pass

        try:
            os.startfile(outfile)
            return
        except:
            pass

        print u'Failed to autoload PDF after creation.'
        return
    else:
        head = u'Cancelled'
        body = u'Canceled PDF creation.'
        tkMessageBox.showinfo(head, body)