Example #1
0
 def test_diploma(self):
     self.label_5.setText("Готовим тестовый Docx...")
     template = str(self.comboBox.currentText())
     group_list = str(self.comboBox_2.currentText())
     lists_path = Path('user_lists')
     pattern_path = Path('learn_templates')
     shutil.rmtree("diplomas", ignore_errors=True)
     os.mkdir("diplomas")
     wb = openpyxl.load_workbook(lists_path / group_list)
     sheet = wb.active
     pattern_name = template  # название шаблона
     date1 = self.dateEdit_2.date().toString('dd.MM.yyyy')  # дата начала
     date2 = self.dateEdit.date().toString('dd.MM.yyyy')  # и окончания обучения
     duration = self.lineEdit.text()  # продолжительнсть учебной программы
     context = {
         'kvant': str(sheet.cell(row=1, column=1).value),
         'date1': date1,
         'date2': date2,
         'duration': duration,
         'fio': str(sheet.cell(row=2, column=1).value) + ' ' + str(sheet.cell(row=2, column=2).value) + ' ' +
                str(sheet.cell(row=2, column=3).value)
     }
     doc = DocxTemplate(pattern_path / pattern_name)
     doc.render(context)
     doc.save("TEST_DIPLOMA.docx")
     shutil.move("TEST_DIPLOMA.docx", "diplomas")
     self.progressBar.setValue(50)
     # CREATE PDF
     docx_list = os.listdir("diplomas")
     os.chdir("diplomas")
     word = comtypes.client.CreateObject('Word.Application')
     print(os.path.abspath(docx_list[0]))
     doc = word.Documents.Open(os.path.abspath(docx_list[0]))
     print(os.getcwd())
     print("Create TEST diploma")
     doc.SaveAs(os.getcwd() + '\\TEST_DIPLOMA.pdf', FileFormat=wdFormatPDF)
     doc.Close()
     word.Quit()
     self.progressBar.setValue(100)
     os.chdir("..")
Example #2
0
import sys
import os
import comtypes.client
from docxtpl import DocxTemplate

doc = DocxTemplate("shablon.docx")
all = 166.44 + 53.38 #сумма за телефонию и интернет
nds = 0.2*all #НДС
total = all + nds #Итого с НДС
context = { 'bank' : "ПАО Сбербанк", 'bik' : "123456789", 'sch1':"123456789123456789", 'inn':"47586907385", 'kpp':"4536758908", 'sch2':"123456789123654789", 'name':"ООО Палитра", 'number':"123", 'date1':"27 апреля", 'date2':"20", 'inn2':"12346907385", 'kpp2':"9876758908", 'index':"123321", 'city':"г. Санкт-Петербург", 'street':"Кронверкский пр-т", 'dom':"дом 49", 'name2':"Васильев А.Г.", 'tel':"933156729", 'osnova':"№ 12345 от 25.03.2020", 'telefonia':"Услуга Телефония", 'price1':"166,44", 'internet':"Услуга Интернет", 'price2':"53,38", 'together':all, 'nds':nds, 'itogo':total, 'itogo2':"Двести шестьдесят три рубля и семьдесят восемь копеек", 'N1':"Сидоров А.А.",'N2':"Панов П.П."}
doc.render(context)
doc.save("СЧЕТ.docx")

wdFormatPDF = 17

in_file = os.path.abspath ("СЧЕТ.docx")
out_file = os.path.abspath("Счёт.pdf")
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
doc.Close()
os.remove("СЧЕТ.docx")

def generatebuttonclicked():
    location = locselector.get()
    invoicenumber = nbr.get()
    eventdate = eventdatecal.selection_get()
    eventdate = str(eventdate)
    year, month, day = map(int, eventdate.split('-'))
    eventdate = datetime.date(year, month, day).strftime('%B %d, %Y')

    invoicedate = date.today().strftime("%m/%d/%Y")
    acctnbr = ""
    if location == "Bloomington":
        acctnbr = 2
    elif location == "Indy BR":
        acctnbr = 1

    # Define template
    doc = DocxTemplate("template.docx")

    # Add user's input to template
    context = {
        'invoicenumber': invoicenumber,
        'invoicedate': invoicedate,
        'eventdate': eventdate,
        'location': location,
        'acctnbr': acctnbr
    }
    doc.render(context)

    #Save to specific folder according to event location
    if location == "Bloomington":
        doc.save(
            "G:\\Pro Beer Sports\\Invoices\\Bloomington\\Pro Beer Sports %s Invoice #%s.docx"
            % (location, invoicenumber))
    elif location == "Indy BR":
        doc.save(
            "G:\\Pro Beer Sports\\Invoices\\Indy BR\\Pro Beer Sports %s Invoice #%s.docx"
            % (location, invoicenumber))

    # Convert generated invoice from .docx to .pdf
    filename = ("Pro Beer Sports %s Invoice #%s.docx" %
                (location, invoicenumber))
    filename2 = ("Pro Beer Sports %s Invoice #%s" % (location, invoicenumber))
    wdFormatPDF = 17

    if location == "Bloomington":
        in_file = os.path.abspath(
            "G:\\Pro Beer Sports\\Invoices\\Bloomington\\" + filename)
        out_file = os.path.abspath(
            "G:\\Pro Beer Sports\\Invoices\\Bloomington\\" + filename2 +
            ".pdf")
        print(out_file)
    elif location == "Indy BR":
        in_file = os.path.abspath("G:\\Pro Beer Sports\\Invoices\\Indy BR\\" +
                                  filename)
        out_file = os.path.abspath("G:\\Pro Beer Sports\\Invoices\\Indy BR\\" +
                                   filename2 + ".pdf")

    word = comtypes.client.CreateObject('Word.Application')
    doc = word.Documents.Open(in_file)
    doc.SaveAs(out_file, FileFormat=wdFormatPDF)
    doc.Close()
    word.Quit()

    # Remove the original .docx file
    os.remove(in_file)

    # Create a message box confirming the program ran successfully
    messagebox.showinfo('', 'The invoice has been successfully generated!')