コード例 #1
0
ファイル: utils.py プロジェクト: xujun10110/rudra
def file_to_pdf(filename):
  pdffile = '%s.pdf' % (os.path.basename(filename))
  pdffile = StringIO()
  pdfkit.from_file(filename, pdffile)

  print pdffile.getvalue()
  return None
コード例 #2
0
def com_pdf_create(pdf_from, pdf_data, pdf_out_file):
    if pdf_from == 'url':
        pdfkit.from_url(pdf_data, pdf_out_file)
    elif pdf_from == 'file':
        pdfkit.from_file(pdf_data, pdf_out_file)
    else:
        pdfkit.from_string(pdf_data, pdf_out_file)
コード例 #3
0
ファイル: resume.py プロジェクト: jeanlorencini/Resume
def main():
    args = parse_args()
    content = generate_markdown(args.markdown)
    template = create_template(content, args.css)
    filename = os.path.basename(args.markdown) # john-cadengo.md
    name = os.path.splitext(filename)[0] # john-cadengo

    if not os.path.exists('build/html'):
        os.makedirs('build/html')

    html = 'build/html/{}.html'.format(name)
    f = codecs.open(html, 'w', encoding='utf-8')
    f.write(template)
    f.close()

    # Generate a png
    #if not os.path.exists('build/png'):
    #    os.makedirs('build/png')

    #call(['wkhtmltoimage', html,
    #      './build/png/{}.png'.format(name)])

    # Generate the pdf
    if not os.path.exists('build/pdf'):
        os.makedirs('build/pdf')

    options = {
        'margin-top': '0.0',
        'margin-right': '0.0',
        'margin-bottom': '0.0',
        'margin-left': '0.0',
        'encoding': "UTF-8",
        'page-size': 'Letter'
    }
    pdfkit.from_file(html, './build/pdf/{}.pdf'.format(name), options=options)
コード例 #4
0
def save_pdf(htmls, file_name):
    '''
    所有的HTML文件保存为PDF文件
    :param htmls:HTML文件列表
    :param file_name:PDF文件名字
    :return:
    '''
    options = {
        'page-size': 'Letter',
        'margin-top': '0.75in',
        'margin-right': '0.75in',
        'margin-bottom': '0.75in',
        'margin-left': '0.75in',
        'encoding': "UTF-8",
        'custom-header': [
            ('Accept-Encoding', 'gzip')
        ],
        'cookie': [
            ('cookie-name1', 'cookie-value1'),
            ('cookie-name2', 'cookie-value2'),
        ],
        'outline-depth': 10,
    }
    pdfkit.from_file(htmls, file_name)
    print(u'合成完毕')
コード例 #5
0
ファイル: get_zhihu.py プロジェクト: crossin/snippet
def to_pdf():
    import pdfkit
    print('exporting PDF...')
    htmls = []
    for root, dirs, files in os.walk('.'):
        htmls += [name for name in files if name.endswith(".html")]
    pdfkit.from_file(sorted(htmls), author + '.pdf')
コード例 #6
0
    def render_to_pdf(self, temp_file):
        tempname = tempfile.mkdtemp()
        temp_out_file_html = self.generate_temp_file(tempname, suffix='html')
        temp_out_file_pdf = self.generate_temp_file(tempname, suffix='pdf')

        ofile = ooxml.read_from_file(temp_file)
        html = """<html style="height: 100%">
            <head>
                <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
                <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
            </head>
            <body>
            """

        html += unicode(serialize.serialize(ofile.document), 'utf-8')
        html += "</body></html>"

        with codecs.open(temp_out_file_html, 'w', 'utf-8') as f:
            f.write(html)

        pdfkit.from_file(temp_out_file_html, temp_out_file_pdf)

        os.remove(temp_out_file_html)

        return temp_out_file_pdf
コード例 #7
0
def html2pd(filename):
	

# 	print """
# 	---------------------------------------------------------

# """+filename+"""
# 	--------------------------------------------------------

# 	"""
	fileList = os.listdir(os.getcwd())
	cssList = []
	for i in fileList: 
		if '.css' in i: 
			cssList.append(i)
		else: 
			pass

	options = {
	    'page-size': 'A4',
	    'margin-top': '1.00in',
	    'margin-right': '0.75in',
	    'margin-bottom': '1.00in',
	    'margin-left': '0.75in',
	    'encoding': "UTF-8",
	    'no-outline': None,
	    'quiet': ''
	}
	config = pdfkit.configuration(wkhtmltopdf='C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe')
	for i in cssList: 
		pdfkit.from_file(filename,i.split('.')[0]+'-'+filename.replace('.html','') + '.pdf',configuration=config, options=options, css = i)
コード例 #8
0
ファイル: crawler.py プロジェクト: zqy1/crawler_html2pdf
    def run(self):
        start = time.time()
        options = {
            'page-size': 'Letter',
            'margin-top': '0.75in',
            'margin-right': '0.75in',
            'margin-bottom': '0.75in',
            'margin-left': '0.75in',
            'encoding': "UTF-8",
            'custom-header': [
                ('Accept-Encoding', 'gzip')
            ],
            'cookie': [
                ('cookie-name1', 'cookie-value1'),
                ('cookie-name2', 'cookie-value2'),
            ],
            'outline-depth': 10,
        }
        htmls = []
        for index, url in enumerate(self.parse_menu(self.crawl(self.start_url))):
            html = self.parse_body(self.crawl(url))
            f_name = ".".join([str(index), "html"])
            with open(f_name, 'wb') as f:
                f.write(html)
            htmls.append(f_name)

        pdfkit.from_file(htmls, self.name + ".pdf", options=options)
        for html in htmls:
            os.remove(html)
        total_time = time.time() - start
        print(u"总共耗时:%f 秒" % total_time)
コード例 #9
0
def getorderspdf( url ):
    order = dbclasses.dbobj.objects[ "order" ]()
    order.find( id = url )
    sql = """
    SELECT * from order_goods where id = %(id)s
    order by count
    """
    db = dbclasses.dbworker.getcon()
    cursor = db.cursor()
    ds = { "id" : order.id }
    cursor.execute( sql, ds )
    rows = cm.fetch_to_row_dict( cursor )
    totalsum = 0
    vatsum = 0
    for e in rows:
        if e[ "vat" ] > 0:
            vatsum += round( e[ "sum" ] * 18 / 118, 2 )
        totalsum += e[ "sum" ]
    def intformat( ones ):
        return "{:10,.2f}".format( ones ).replace( ",", " ").replace( ".", "," )
    _templ_res = cm.read_file_to_str("docforms//order.form")
    res = pystache.render(_templ_res, { "order" : order.__dict__ , "el" : rows, "totalsum" : intformat( totalsum ) , "vatsum" : intformat( vatsum ), "length" : len(rows) })
    f = open( "tmp.html", "w", encoding = "utf-8" )
    f.write( res )
    pdfkit.from_file( 'tmp.html', "out.pdf" )
    return "out.pdf"
コード例 #10
0
    def _make_pdf_from_html(self):


        html_dir = os.path.join(self.output_dir, 'html', '{}'.format(self.year))
        pdf_dir = os.path.join(self.output_dir, 'pdf', '{}'.format(self.year))
        os.makedirs(pdf_dir, exist_ok=True)

        basename = '{}-{:02d}'.format(self.year, self.month)

        html_file = os.path.join(html_dir, basename + '.htm')
        pdf_file = os.path.join(pdf_dir, basename + '.pdf')

        options = {
            'page-size': 'A4',
            'orientation': 'Landscape',
            'margin-top': '0.7in',
            'margin-right': '0.75in',
            'margin-bottom': '0.7in',
            'margin-left': '0.75in',
            'encoding': 'UTF-8',
        }

        print()
        print('Creating {}'.format(pdf_file))
        pdfkit.from_file(html_file, pdf_file, options=options)
コード例 #11
0
ファイル: liaoxuefeng_pdf.py プロジェクト: sixixi007/crawler
def save_pdf(htmls, file_name):

    options = {

        'page-size': 'Letter',

        'margin-top': '0.75in',

        'margin-right': '0.75in',

        'margin-bottom': '0.75in',

        'margin-left': '0.75in',

        'encoding': "UTF-8",

        'custom-header': [

            ('Accept-Encoding', 'gzip')

        ],

        'cookie': [

            ('cookie-name1', 'cookie-value1'),

            ('cookie-name2', 'cookie-value2'),

        ],

        'outline-depth': 10,

    }

    pdfkit.from_file(htmls, file_name, options=options)
コード例 #12
0
ファイル: content.py プロジェクト: cmacmackin/scribbler
 def make_pdf(self):
     """
     Produces a PDF version of the content from its HTML version, if
     it requires updating or does not already exist.
     """
     src = os.path.join(self.notebook.location, self.html_path)
     dest = os.path.join(self.notebook.location, self._pdf_path())
     pdfkit.from_file(src, dest, options=self.notebook.pdf_settings)
コード例 #13
0
 def pdf(movies):
     """
     This method will use pdfkit to create pdf files
     :param movies:
     :return:
     """
     ReportGen.generate_report(movies)
     pdfkit.from_file('output.txt', 'output.pdf')
コード例 #14
0
ファイル: Extractor.py プロジェクト: samkit-jain/Textractor
def from_file(location):
    clear_screen()

    if location[-5:] != '.html':
        print("Extension of the file should be .html   -_-")
    else:
        pdfkit.from_file(location, 'output.pdf')
        
        print convert_pdf_to_txt('output.pdf')
コード例 #15
0
def save_file_and_print(customer_template_text, temp_html_path, temp_pdf_file_path):
    f = open(temp_html_path, 'wb')
    f.write(customer_template_text)
    f.close()
    try:
        a = subprocess.Popen(['wkhtmltopdf.exe', temp_html_path, temp_pdf_file_path], subprocess.PIPE)
        a.communicate()
    except:
        pdfkit.from_file(temp_html_path, temp_pdf_file_path)
コード例 #16
0
ファイル: apple2.py プロジェクト: xyzgentoo/printApplePG
def output_pdf(file_name_prefix, source_url):
    # for Apple doc url, remove the part after #
    target_url = get_target_url(source_url)
    print target_url

    # load url into html text strings
    html = requests.get(target_url)

    # PG 样式2 -
    # 另一个系列的Programming guides
    # 例如: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/index.html
    # https://cdn.rawgit.com/xyzgentoo/printApplePG/master/print-style-1.5.1.css
    # https://cdn.rawgit.com/xyzgentoo/printApplePG/master/print-feedback-1.5.1.css
    updated_html_text = re.sub(r'(<link rel=\"stylesheet\" type=\"text/css\" href=\")(.+style-1.5.1.css)(\" />)',
                               r'\1https://cdn.rawgit.com/xyzgentoo/printApplePG/master/print-style-1.5.1.css\3',
                               html.text)
    updated_html_text = re.sub(r'(<link rel=\"stylesheet\" type=\"text/css\" href=\")(.+feedback-1.5.1.css)(\" />)',
                               r'\1https://cdn.rawgit.com/xyzgentoo/printApplePG/master/print-feedback-1.5.1.css\3',
                               updated_html_text)

    ## replace img src=".. with
    # img src="https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d
    res_prefix_url = get_prefix_url(target_url)

    # 替换img的相对路径
    updated_html_text = re.sub(r'(<img src=\"../)(\w+)', r'<img src="' + res_prefix_url + r'\2', updated_html_text)

    # Note: 替换img没有../的相对路径
    res_prefix_url2 = get_prefix_url2(target_url)
    updated_html_text = re.sub(r'(<img src=\")(\w+)', r'<img src="' + res_prefix_url2 + r'\2', updated_html_text)

    # 注意 那几个js最好不要替换,要不里面也会报出找不到content的问题,pdfkit执行的时候就会报错了

    items = target_url.split('/')
    output_pdf_name = file_name_prefix + '_' + items[len(items) - 1] + '.pdf'

    # use pdfkit to generate the pdf - 这里修改encoding是为了避免显示奇怪的字符
    # TODO python encoding这块还不是特别懂...
    updated_html_text = updated_html_text.encode('latin-1')
    # print updated_html_text

    # 这样用html文件中转一下,可以正确处理encoding的问题,如果使用pdfkit.from_string()也不能输出updatedHtml,估计是pdfkit内部错误
    temp_html_file_name = "temp.html"
    with codecs.open(temp_html_file_name, "w") as f:
        f.write(updated_html_text)

    try:
        # 从html文件生成pdf
        pdfkit.from_file(temp_html_file_name, output_pdf_name)
    except IOError as err:
        # Note: 有js资源找不到的话, 这里会抛出IOError
        print "*** Well, IOError hits: " + str(err)

    # clean up temp file
    os.remove(temp_html_file_name)
    pass
コード例 #17
0
def response_pdf(request,html,filename):
    response = request.response
    with tempinput(html) as tempfilename:
        with tempinput("") as output_file:
            wk = pdfkit.from_file(tempfilename, output_file) #,dpi="300",screen_resolution=[1280, 1024])
            response.body_file = pdfkit.from_file('test.html', False)
            response.content_type = 'application/pdf'
            filename = filename.replace(" ","_")
            filename = pl_to_ascii(filename)
            filename = ''.join(c for c in filename if c in valid_chars).strip(".")
            response.headerlist.append(("Content-Disposition", "attachment; filename='"+str(filename)+".pdf'"))
            return response
コード例 #18
0
ファイル: client.py プロジェクト: chaipokoi/Calk
def layer_generate_page(id):

    source = "./../data/layer/"+id+".html"
    result = "./static/tmp/layer/"+id+".pdf"

    options = {'page-size': 'Letter','margin-top': '0.75in','margin-right': '0.75in','margin-bottom': '0.75in','margin-left': '0.75in','encoding': "UTF-8"}

    try:
        pdfkit.from_file(source, result, options=options)
        return {"state":"success", "link": result[1:]}
    except error:
        return {"state": "Une erreur est survenue, veuillez contacter l'administrateur."}
コード例 #19
0
def generarRremito(data):

    """
        Generar el remito correspondiente, para ser impresa
        :param data Diccionario que contiene informacion asociada con el comprobante:

        Estructura del diccionario

        numero = Contiene el numero del remito
        fecha = Contiene fecha del remito
        datosCliente = Contiene un diccionario con los datos del cliente
                        El mismo contiene: nombre, apellido, telefono, direccion
        detalles = Contiene el arreglo con los detalles del remito

    """

    archivo = open("Comprobantes/remito.html", "r")
    contenido = archivo.read()
    archivo.close()

    body = ""
    total = 0

    for dato in data["detalles"]:
        producto = dato[0]
        cantidad = dato[1]
        cadena = """<tr>

            <td><strong>{producto}</strong></td>
            <td class="text-right">{cantidad}</td>
          </tr>""".format(
            producto=producto, cantidad=cantidad
        )
        body += cadena

    contenido_nuevo = contenido.format(
        numero=data["numero"],
        fecha=data["fecha"].strftime("%d/%m/%y"),
        nombre=data["datosCliente"]["nombre"],
        apellido=data["datosCliente"]["apellido"],
        telefono=data["datosCliente"]["telefono"],
        direccion=data["datosCliente"]["direccion"],
        contenido=body,
        total=total,
    )

    archivo = open("Comprobantes/nota.html", "w")
    archivo.write(contenido_nuevo)
    archivo.close()

    pdfkit.from_file("Comprobantes/nota.html", "temp_remito.pdf")
    os.system("evince temp_remito.pdf &")
コード例 #20
0
ファイル: apple.py プロジェクト: xyzgentoo/printApplePG
def output_pdf(file_name_prefix, source_url):
    # for Apple doc url, remove the part after #
    target_url = get_target_url(source_url)
    print target_url

    # load url into html text strings
    html = requests.get(target_url)

    # PG 样式1 -
    # 替换apple css为我自己修改后的css,为了输出print friendly样式的页面
    # <link rel="stylesheet" type="text/css" href="../../../../../Resources/1163/CSS/screen.css">
    updated_html_text = re.sub(r'(<link rel=\"stylesheet\" type=\"text/css\" href=\")(.+screen.css)(\">)',
                               r'\1https://cdn.rawgit.com/xyzgentoo/printApplePG/master/print.css\3', html.text)
    updated_html_text = re.sub(r'(<link rel=\"stylesheet\" type=\"text/css\" href=\")(.+feedback.css)(\">)',
                               r'\1https://cdn.rawgit.com/xyzgentoo/printApplePG/master/feedback1.css\3',
                               updated_html_text)

    # 先替换相对路径中没有..的img src, 例如: <img src="Art/facets_of_accessibility_2x.png"
    res_upper_one_level_prefix_url = get_upper_prefix_url(target_url, 1)
    updated_html_text = re.sub(r'(<img src=\")(\w+)',
                               r'<img src="' + res_upper_one_level_prefix_url + r'\2',
                               updated_html_text)

    # 再替换../这样的路径, 例如: <img src="../Art/test_2x.png"
    res_upper_two_levels_prefix_url = get_upper_prefix_url(target_url, 2)

    # 替换img的相对路径
    updated_html_text = re.sub(r'(<img src=\"../)(\w+)',
                               r'<img src="' + res_upper_two_levels_prefix_url + r'\2',
                               updated_html_text)

    # 注意 那几个js最好不要替换,要不里面也会报出找不到content的问题,pdfkit执行的时候就会报错了

    items = target_url.split('/')
    output_pdf_name = file_name_prefix + '_' + items[len(items) - 1] + '.pdf'

    # use pdfkit to generate the pdf - 这里修改encoding是为了避免显示奇怪的字符
    # TODO python encoding这块还不是特别懂...
    updated_html_text = updated_html_text.encode('latin-1')
    # print updated_html_text

    # 这样用html文件中转一下,可以正确处理encoding的问题,如果使用pdfkit.from_string()也不能输出updatedHtml,估计是pdfkit内部错误
    temp_html_file_name = "temp.html"
    with codecs.open(temp_html_file_name, "w") as f:
        f.write(updated_html_text)

    # 从html文件生成pdf
    pdfkit.from_file(temp_html_file_name, output_pdf_name)

    # clean up temp file
    os.remove(temp_html_file_name)
    pass
コード例 #21
0
def cetakCDMPro(strKanwil):

	from pyvirtualdisplay import Display
	from selenium import webdriver

	display = Display(visible=0, size=(800, 600))
	display.start()

	# now Firefox run in a virtual display. 
	# you will not see the browser.
	browser = webdriver.Firefox()

	alamatURL = 'http://172.18.65.42/monitorcdm/'

	browser.get(alamatURL)

	browser.title
	print "logging in... "
	browser.find_elements_by_css_selector("input[type='radio'][value='GUEST']")[0].click()
	browser.find_element_by_class_name('tbutton').click()
	browser.get(alamatURL)

	print "getting in... "
	browser.get('http://172.18.65.42/monitorcdm/?_module_='+strKanwil)
	strHTML = browser.page_source

	browser.quit()
	display.stop()
	#------------------------------------------------------------------------------------


        arrTable, strStyle = analyzeHTML(strHTML)
	numRows, numRowsHead, numCols, table = getTableDimension(arrTable)

	strNamaFile = "MONITORING CDM " + strRegionName + " -" + time.strftime("%Y%m%d") + ".html"
	strNamaFilePDF = "cdmpro-" + time.strftime("%Y%m%d-%H") + ".pdf"

	dTabel = '<h1>Monitoring CDM  ' + strRegionName + ' - ' + time.strftime("(%d.%m.%Y - %H:%M)")+ "</h1>" +str(table)
	
	strHTML = '<HTML><HEAD><TITLE>Monitoring CDM  ' + strRegionName + ' </TITLE><META HTTP-EQUIV="REFRESH" CONTENT="3600">'+ strStyle +'</HEAD><body>' + dTabel

	strNamaFile = prepareDirectory('OUTPUT', 'CDM') + strNamaFile
	strNamaFilePDF = prepareDirectory('OUTPUT', 'CDM') + strNamaFilePDF

	options = {'page-size': 'A2', 'orientation':'landscape'}

        fileCreate(strNamaFile, strHTML)
	pdfkit.from_file(strNamaFile, strNamaFilePDF, options)



	return strNamaFilePDF
コード例 #22
0
def danaKanca(strBranchCode):

	strBranchCode = str(int(strBranchCode))


	from pyvirtualdisplay import Display
	from selenium import webdriver

	display = Display(visible=0, size=(800, 600))
	display.start()

	# now Firefox run in a virtual display. 
	# you will not see the browser.
	browser = webdriver.Firefox()

	alamatURL = 'http://172.18.41.101/DashboardSimpanan/'

	browser.get(alamatURL)

	print browser.title

	print "getting in... "
	alamatURL ="http://172.18.41.101/DashboardSimpanan/index.php/c_RptMonitoringDPK/getUkerSegmentByBranch/"
	browser.get(alamatURL+strBranchCode)
	strHTML = browser.page_source

	browser.quit()
	display.stop()
	#------------------------------------------------------------------------------------


	arrTable, strStyle = analyzeHTML(strHTML)
	numRows, numRowsHead, numCols, table = getTableDimension(arrTable)

	strNamaFile = "MONITORING SIMPANAN " + strBranchCode + " -" + time.strftime("%Y%m%d") + ".html"

	strNamaFilePDF = "savingpro-" + time.strftime("%Y%m%d-") +strBranchCode+ ".pdf"

	dTabel = '<h1  style="color: #0000FF;">Monitoring SIMPANAN  ' + strBranchCode + ' - ' + time.strftime("(%d.%m.%Y - %H:%M)")+ "</h1>" +str(table)
	
	strHTML = '<HTML><HEAD><TITLE>Monitoring SIMPANAN  ' + strBranchCode + ' </TITLE><META HTTP-EQUIV="REFRESH" CONTENT="3600">'+ strStyle +'</HEAD><body>' + dTabel

	strNamaFile = prepareDirectory('OUTPUT', 'SAVING') + strNamaFile
	strNamaFilePDF = prepareDirectory('OUTPUT', 'SAVING') + strNamaFilePDF

	options = {'page-size': 'A2', 'orientation':'landscape'}

	fileCreate(strNamaFile, strHTML)
	pdfkit.from_file(strNamaFile, strNamaFilePDF, options)

	return strNamaFilePDF
コード例 #23
0
ファイル: main.py プロジェクト: caegen/basicMailPrinter
def print_order(message):
    print "printing"
    html_file = open("print.html", "w")
    html_file.write(message)
    html_file.close()
    pdfkit.from_file("print.html", "print.pdf")
    win32api.ShellExecute(
      0,
      "print",
      "print.pdf",
      '/p /h:"%s"' % win32print.GetDefaultPrinter(),
      ".",
      0
    )
コード例 #24
0
def html_files_to_pdf(html_files, output_file):
    options = {
        'page-size': 'A4',
        'margin-top': '20mm',
        'margin-right': '20mm',
        'margin-bottom': '20mm',
        'margin-left': '20mm',
        'encoding': "UTF-8",
        'grayscale': None,
        'outline-depth':3,
        # 'footer-center':'[page]',
        'footer-line': None,
    }
    pdfkit.from_file(html_files, output_file, options=options, )
コード例 #25
0
ファイル: monografia.py プロジェクト: desenv-1dl/monografia
 def convertHtmlPdf(self, pathHtml, pontoId):
     opt = {
         'page-size': 'A4',
         'margin-top': '0.5cm',
         'margin-right': '0.0cm',
         'margin-bottom': '5.3cm',
         'margin-left': '2cm',
         'encoding': "UTF-8",
         'no-outline': None
     } 
     try:
         pathPdf = os.path.join(self.project, 'pdf', str(pontoId)+'.pdf')
         pdfkit.from_file(pathHtml, pathPdf, options=opt)
     except:
         pass
コード例 #26
0
ファイル: notebook.py プロジェクト: cmacmackin/scribbler
 def build(self, debug=False):
     """
     Run Pelican to produce the HTML for this notebook. Then produce
     the PDF pages. Passes `--debug` flag to Pelican if DEBUG is true.
     """
     self.make_pelicanconf()
     content = os.path.join(self.location, self.CONTENT_DIR)
     if not os.path.isdir(content):
         os.mkdir(content)
         os.symlink(os.path.join(self.location, self.NOTE_DIR), 
                    os.path.join(content, self.NOTE_DIR))
         os.symlink(os.path.join(self.location, self.APPE_DIR),
                    os.path.join(content, self.APPE_DIR))
         os.symlink(os.path.join(self.location, self.STATIC_DIR),
                     os.path.join(content, self.STATIC_DIR))
     print('Producing HTML files...')
     call = ['pelican','-s',os.path.join(self.location,self.PELICANCONF_FILE)]
     if debug:
         call.append('--debug')
     subprocess.call(call)
     #~ self.del_pelicanconf()
     self.update()
     #~ shutil.rmtree(content)
     print('Producing PDF files...')
     if not os.path.isdir(os.path.join(self.location, self.PDF_DIR)):
         os.mkdir(os.path.join(self.location, self.PDF_DIR))
     master = PdfFileMerger(strict=False)
     master.addMetadata({u'/Title': self.settings['notebook name'],
                         u'/Author': self.settings['author']})
     src = os.path.join(self.location, self.HTML_DIR, 'index.html')
     dest = os.path.join(self.location, self.PDF_DIR, 'titlepage.pdf')
     pdfkit.from_file(src, dest, options=self.pdf_settings)
     master.append(dest)
     for note in sorted(self.notes.values(), key=lambda n: n.slug):
         if note.pdf_date < note.src_date:
             note.make_pdf()
             note.update()
         master.append(os.path.join(self.location, note.pdf_path),
                       note.date + ': ' + note.name)
     for appe in sorted(self.appendices.values(), key=lambda a: a.slug):
         if appe.pdf_date < appe.src_date:
             appe.make_pdf()
             appe.update()
         master.append(os.path.join(self.location, appe.pdf_path),
                       'Appendix: ' + appe.name)
     master.write(os.path.join(self.location, self.PDF_DIR, self.MASTER_PDF))
     print('Done.')
     self.update()
コード例 #27
0
ファイル: main.py プロジェクト: jspeis/NewsButler
def grab_article(url):
    origUrl = url
    # -- Append parameter for print friendly mode
    url = url[: url.find("?")] + "?pagewanted=print"
    # -- Must set Referer or we won't get print friendly page
    headers = {"Referer": origUrl}
    print "Sending HTTP req..."
    page = requests.get(url, headers=headers)
    html = page.content
    tmpFile = open("tmp.html", "w")
    tmpFile.write(html)
    tmpFile.close()
    print "Making pdf..."
    pdfkit.from_file("tmp.html", "tmp.pdf")
    print "Printing..."
    os.system("lpr tmp.pdf")  # -- uses default printer
コード例 #28
0
ファイル: app.py プロジェクト: ausmed/wkhtmltopdf-flask-aas
def handle_request(config):
    # We are getting the url to generate from a form parameter
    options = {}
    options = request.values.getlist('options', type=float)
    print(options)

    # Converting post options group to dictionary
    listname = 'options'
    options = dict()
    for key, value in request.form.items():
        if key[:len(listname)] == listname:
            options[key[len(listname)+1:-1]] = value

    if ('url' in request.form):
        print("URL provided: " + request.form['url'])
        pdf = pdfkit.from_url(str(request.form['url']), output_path=False, configuration=config, options=options)

    if ('html' in request.form):
        print("Html provided")
        pdf = pdfkit.from_string(str(request.form['html']), output_path=False, configuration=config, options=options)

    # If we are receiving the html contents from a uploaded file
    elif ('content' in request.files):
        print("File provided: " + str(request.files['content']))
        f = request.files['content']
        f.save(tmpfolder + secure_filename(f.filename))

        pdf = pdfkit.from_file(tmpfolder + secure_filename(f.filename), output_path=False, configuration=config, options=options)

    return pdf
コード例 #29
0
    def generatePDF(self):
        # Involves 3 steps
        # 1. Validating the data
        try:
        	self.validateForm()
        except Exception as error:
        	self.TextArea.insert(tk.END, str(error))
        	self.TextArea.see(tk.END)
        	return

        # 2. Structuring the equivalent HTML and stylizing it to look like a real assignmnent
        
        # 3. Converting it to pdf using PDFkit

        config = pdfkit.configuration(wkhtmltopdf=os.getcwd()[:-6]+"/Dependencies/wkhtmltopdf")
        pdfkit.from_file('try3.html','out1.pdf',configuration=config)
コード例 #30
0
def generarNotaCredito(data):
    """
        Genera la Nota de Credito correspondiente
        para ser impresa.
        :return:
    """

    archivo = open("Comprobantes/nota_credito.html", "r")
    contenido = archivo.read()
    archivo.close()

    body = ""
    total = 0

    for dato in data["detalles"]:
        producto = dato[0]
        cantidad = dato[1]
        descuento = dato[2] * 100
        importe = "%.2f" % dato[3]
        total += float(importe)
        cadena = """<tr>

            <td><strong>{producto}</strong></td>
            <td class="text-right">{cantidad}</td>
            <td class="text-right">{descuento}</td>
            <td class="text-right">{importe}</td>
          </tr>""".format(
            producto=producto, cantidad=cantidad, descuento=descuento, importe=importe
        )
        body += cadena

    contenido_nuevo = contenido.format(
        numero=data["numero"],
        fecha=data["fecha"].strftime("%d/%m/%y"),
        nombre="----",
        direccion="----",
        telefono="----",
        contenido=body,
        total=total,
    )

    archivo = open("Comprobantes/nota.html", "w")
    archivo.write(contenido_nuevo)
    archivo.close()

    pdfkit.from_file("Comprobantes/nota.html", "nota.pdf")
    os.system("evince nota.pdf &")
コード例 #31
0
ファイル: pdf_convertor.py プロジェクト: LouisLu78/my_module
def html_to_pdf(html, pdf_file):
    pdfkit.from_file(html, pdf_file, configuration=config)
    print('done')
コード例 #32
0
ファイル: xa.py プロジェクト: quattie528/pylibq
def txt2a5pdf(txt, ex):
    opt = {'page-size': 'A5'}
    pdfkit.from_file(txt, ex, opt)
コード例 #33
0
}
os.makedirs(os.path.join(output, "Positive_vs_Negative"), exist_ok=True)

legend = ["Positive", "Negative"]
kind = ['positive', 'negative']

html_name = os.path.join(output, legend[0] + "_vs_" + legend[1] + ".html")
clear_html(html_name)
add_str_html(html_name, '<!DOCTYPE html>')
add_str_html(html_name, '<html>')
add_str_html(html_name, '<body>')
add_str_html(
    html_name,
    '<p style="font-size:40px;"><b> %s, average Theta 4-8 Hz after feedback presentation in 28 participants after training </b></p>'
    % (legend[0] + "_vs_" + legend[1]))
add_str_html(
    html_name,
    '<p style="font-size:40px;"><b> P_val < 0.05 marked (or saved from cutting) </b></p>'
)
add_str_html(html_name, '<table>')
for topo in topomaps:
    add_str_html(html_name, "<tr>")
    add_pic_html(html_name,
                 os.path.join(legend[0] + "_vs_" + legend[1], topo + ".png"))
add_str_html(html_name, "</tr>")
add_str_html(html_name, '</body>')
add_str_html(html_name, '</html>')
pdf_file = html_name.replace("html", "pdf")
pdfkit.from_file(html_name, pdf_file, configuration=config, options=options)
print('Done')
コード例 #34
0
def main():
    parser = ArgumentParser()
    parser.add_argument("-f",
                        "--file",
                        dest="testplan_list",
                        required=True,
                        nargs="+",
                        help="Test plan file to be used")
    parser.add_argument("-r",
                        "--repositories",
                        dest="repository_path",
                        default="repositories",
                        help="Test plan file to be used")
    parser.add_argument("-o",
                        "--output",
                        dest="output",
                        default="output",
                        help="Destination directory for generated files")
    parser.add_argument(
        "-i",
        "--ignore-clone",
        dest="ignore_clone",
        action="store_true",
        default=False,
        help="Ignore cloning repositories and use previously cloned")
    parser.add_argument(
        "-s",
        "--single-file-output",
        dest="single_output",
        action="store_true",
        default=False,
        help="""Render test plan into single HTML file. This option ignores
                        any metadata that is available in test cases""")
    parser.add_argument(
        "-c",
        "--csv",
        dest="csv_name",
        required=False,
        help=
        "Name of CSV to store overall list of requirements and test. If name is absent, the file will not be generated"
    )
    parser.add_argument(
        "--test-template-name",
        default="test.html",
        help="Name of the template used for rendering individual tests")
    parser.add_argument(
        "--testplan-template-name",
        default="testplan.html",
        help="Name of the template used for rendering testsplans")
    parser.add_argument(
        "--templates-directory",
        default=None,
        help="Directory where the templates are located (absolute path)")
    parser.add_argument(
        "--pdf",
        default=None,
        help="Path to the output pdf file. Only works if output generates HTML"
    )

    _mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
    yaml.add_representer(PrependOrderedDict, dict_representer)
    yaml.add_constructor(_mapping_tag, dict_constructor)

    args = parser.parse_args()
    if not os.path.exists(os.path.abspath(args.output)):
        os.makedirs(os.path.abspath(args.output), mode=0o755)
    for testplan in args.testplan_list:
        if os.path.exists(testplan) and os.path.isfile(testplan):
            testplan_file = open(testplan, "r")
            tp_obj = yaml.load(testplan_file.read(), Loader=yaml.FullLoader)
            repo_list = repository_list(tp_obj)
            repositories = {}
            for repo in repo_list:
                repo_url, repo_path = clone_repository(repo,
                                                       args.repository_path,
                                                       args.ignore_clone)
                repositories.update({repo_url: repo_path})
            # ToDo: check test plan structure

            tp_version = tp_obj['metadata']['format']
            if tp_version == "Linaro Test Plan v1":
                for requirement in tp_obj['requirements']:
                    check_coverage(requirement, repositories, args)
            if tp_version == "Linaro Test Plan v2":
                if 'manual' in tp_obj['tests'].keys(
                ) and tp_obj['tests']['manual'] is not None:
                    for test in tp_obj['tests']['manual']:
                        test_exists(test, repositories, args)
                if 'automated' in tp_obj['tests'].keys(
                ) and tp_obj['tests']['automated'] is not None:
                    for test in tp_obj['tests']['automated']:
                        test_exists(test, repositories, args)
            # same filename extension as the template
            tp_name = tp_obj['metadata']['name'] + os.path.splitext(
                args.testplan_template_name)[1]
            tp_file_name = os.path.join(os.path.abspath(args.output), tp_name)
            render(tp_obj,
                   templates_dir=args.templates_directory,
                   template=args.testplan_template_name,
                   name=tp_file_name)
            testplan_file.close()
            if args.pdf is not None:
                pdfkit.from_file(tp_file_name, args.pdf)
コード例 #35
0
ファイル: part1.py プロジェクト: jess-scientist/World-Bank
         df_idk.loc[df_idk['country_name'] == 'Lower middle income']['value'],
         label="Lower middle income")
plt.plot(df_idk.loc[df_idk['country_name'] == 'Low income']['date'],
         df_idk.loc[df_idk['country_name'] == 'Low income']['value'],
         label="Low income")
plt.axis([1990, 2015, 0, 100])
plt.legend(loc=4)
plt.title('Access to Improved Sanitation Facilities by Income Group')
plt.xlabel('Date (year)')
plt.ylabel('Access Percentage (%)')
fig.savefig('income.png')

# Save the info as a html file
myfile = open('income.html', 'w')
html_text = """<html><body><h1>Improved Sanitation Facilities (% of population with access)</h1>
                <p><img src="income.png"></p>
                <p><font size="+2">The figure above shows the evolution of access to improved sanitation facilties over time
                by income group. The overall trend shows that access to improved sanitation facilities increases
                over time over all income groups. The high income group did not change much over 25 years because
                it started at nearly 100%. But the middle income group increases in access at a faster rate than
                the low income group (+21% over 25 years for the middle income group vs. +15% for the low income
                group).</font>
                </p></body></html>"""
myfile.write(html_text)
myfile.close()

# Convert html to pdf
# Configured for my computer, change wkhtmltopdf path
config = pdfkit.configuration(wkhtmltopdf="/usr/local/bin/wkhtmltopdf")
pdfkit.from_file('income.html', 'part1.pdf', configuration=config)
コード例 #36
0
import pdfkit
options = {
    'page-size':
    'A4',
    'margin-top':
    '0.25in',
    'margin-right':
    '0.25in',
    'margin-bottom':
    '0.25in',
    'margin-left':
    '0.25in',
    'encoding':
    "UTF-8",
    'custom-header': [('Accept-Encoding', 'gzip')],
    'cookie': [
        ('cookie-name1', 'cookie-value1'),
        ('cookie-name2', 'cookie-value2'),
    ],
    'no-outline':
    None,
    "enable-local-file-access":
    None
}

pdfkit.from_file('first.html', '简历.pdf', options=options)
コード例 #37
0
import pdfkit

ns = range(1, 175)
problems = []

for n in ns:
    problems.append(f"problem_{n}.html")

# print(problems)

pdfkit.from_file(problems, "out.pdf")
コード例 #38
0
	def purchaseReport(self):
		queryPurchase = None
		print("----------------purchaseReport-----------\n")
		print(tabulate([["1","Date"],["2","Vendor"],["3","Back To Main Menu"]], headers=['Id', 'Menu']))
		purchaseIDvalue = input("Choose filter? ")
		try:
			if purchaseIDvalue.isdigit():
				filter = int(purchaseIDvalue)
				if filter == 1:
					stdt = input("enter start date (yyyy-mm-dd) : ")
					startdate = stdt
					if self.validateDate(startdate) is False:
						self.purchaseReport()
					enddt = input("enter end date (yyyy-mm-dd) : ")
					endDate = enddt
					if self.validateDate(endDate) is False:
						self.purchaseReport()
					queryPurchase ='select * from po_purchase where created_on between \'' + startdate + '\' and \'' + endDate + '\''
				elif filter == 2:
					print(tabulate([["1","Tata"],["2","Chakra Gold"],["3","Sunrise"],["4","Lipton"],["5","3 Roses"],["6","Society"],["6","Marvel"]], headers=['Id', 'Menu'])) 
					itemOption = input("Select an item  ")
					if itemOption.isdigit():
						queryPurchase = 'select * from po_purchase  WHERE vendors_item_id = '+itemOption
					else:
						print("Enter valid number")
						self.purchaseReport() 
				elif filter == 3:
					rId =  userRole
					if rId == 1:
						self.adminReport()
					else:	
						self.purchaseManager()
				else:
					print("Choose any filter")
					self.purchaseReport()

				result=pd.read_sql_query(queryPurchase, sql_engine) 
				#print(result)
				purchaseCount = len(result)
				if purchaseCount > 0:
	
					print('\n-----------------------------------------------------------------------------------------------------------------------------------------------------\n')
					print(tabulate(result, headers=['Purchase ID','Created By','Updated By','Order No','Total Amount','Payment Type','Created On','Updated On','PO Req ID','Vendors Item ID','Status']))
					#Converting CSV File
					result.to_csv("report.csv", index=False)
					#Converting Excel File 
					for csvfile in glob.glob(os.path.join('.', '*.csv')):
					    workbook = Workbook(csvfile[:-4] + '.xlsx')
					    worksheet = workbook.add_worksheet()
					    with open(csvfile, 'rt', encoding='utf8') as f:
					        reader = csv.reader(f)
					        for r, row in enumerate(reader):
					            for c, col in enumerate(row):
					                worksheet.write(r, c, col)
					    workbook.close() 
					#Converting PDF File        
					csv_file = 'report.csv'
					html_file = csv_file[:-3]+'html'
					pdf_file = csv_file[:-3]+'pdf'
					df = pd.read_csv(csv_file, sep=',')
					df.to_html(html_file)
					pdf.from_file(html_file, pdf_file)
					self.purchaseReport()
				else:
					print("No data found in selected filter")
					self.purchaseReport()
			else:
				print("Enter valid input number")
				self.purchaseReport()
		except Exception as e:
			print("Error: ----",e)
		finally:
			print("Purchase report input error")
			self.purchaseReport()
コード例 #39
0
	def userReport(self):
		queryUser = None
		print("-------------------userReport----------------------\n")
		print(tabulate([["1","Date"],["2","Consolidate"],["3","Back To Main Menu"]], headers=['Id', 'Menu']))
		userIDValue = input("which filter? ")

		try:
			if userIDValue.isdigit():
				filter = int(userIDValue)
				if filter == 1:
					stdt = input("enter start date (yyyy-mm-dd) : ")
					startdate = stdt
					if self.validateDate(startdate) is False:
						self.userReport()
					enddt = input("enter end date (yyyy-mm-dd) : ")
					endDate = enddt
					if self.validateDate(endDate) is False:
						self.userReport()
					itemOPS = userID
					queryUser ='******'' + startdate + '\' and \'' + endDate + '\'  and  created_by = '+str(itemOPS)
				elif filter == 2:
					#querySales = 'select * from so_header_details  WHERE created_by ='+str(itemOption) 
					itemOPS = userID
					# itemOPS = 1
					queryUser = '******'+str(itemOPS) 
				elif filter == 3:
					self.userMethod()
				else:
					self.userReport()

				result=pd.read_sql_query(queryUser, sql_engine) 
				totalcount = len(result)
				print("totalcount",totalcount)
				if totalcount > 0:
					
					print('\n------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------')
					print(tabulate(result, headers=['Header Details ID','Item ID','Quantity','Discount','Unit Price','Total Price','Created By','Created On','Updated By','Updated On','Header ID','Delete Date']))
					for index, row in result.iterrows():
						#print('|'+str(row['inv_item_id'])+'\t\t|'+row['item_name']+'\t\t|'+str(row['item_mrp_price'])+'\t\t|'+str(row['item_quantity'])+'\t\t|')
						print('|'+str(row['inv_item_id'])+'\t\t|'+str(row['quantity'])+'\t\t|'+str(row['discount'])+'\t\t|'+str(row['unit_price'])+'\t\t|'+'\t\t|'+str(row['total_price'])+'\t\t|'+'\t\t|'+str(row['created_by'])+'\t\t|'+str(row['created_on'])+'\t\t|')
						#print('|'+str(row['inv_item_id'])+'\t\t|'+str(row['quantity'])+'\t\t|'+str(row['discount'])+'\t\t|'+str(row['unit_price'])+'\t\t|'+str(row['total_price'])+'\t\t|'+row['created_by']+'\t\t'+row['created_on']+'\t\t|')
						print('\n-----------------------------------------------------------------\n')
						#Converting CSV File
						result.to_csv("report.csv", index=False)
						#Converting Excel File
						for csvfile in glob.glob(os.path.join('.', '*.csv')):
						    workbook = Workbook(csvfile[:-4] + '.xlsx')
						    worksheet = workbook.add_worksheet()
						    with open(csvfile, 'rt', encoding='utf8') as f:
						        reader = csv.reader(f)
						        for r, row in enumerate(reader):
						            for c, col in enumerate(row):
						                worksheet.write(r, c, col)
						    workbook.close() 
						#Converting PDF File        
						csv_file = 'report.csv'
						html_file = csv_file[:-3]+'html'
						pdf_file = csv_file[:-3]+'pdf'
						df = pd.read_csv(csv_file, sep=',')
						df.to_html(html_file)
						pdf.from_file(html_file, pdf_file)
						self.userReport()
				else:
					print("No data found in selected filter")
					# if userRole == 1:
					# 	self.adminReport()
					# else:
					self.userReport()
			else:
				print("")
				self.userReport()
		except Exception as e:
			print("Error:--------",e)
		finally:
			print("Invalid Syntax")
			self.userReport()
コード例 #40
0
	def inventoryReport(self):
		queryInventory = None
		print("------------------Inventory Report---------------\n")

		print(tabulate([["1","Date"],["2","Item"],["3","Discount"],["4","Price"],["5","Quantity"],["6","Back To Main Menu"]], headers=['Id', 'Menu'])) 
		inventType = input("Choose filter type?")
		try:
			if inventType.isdigit():
				filter = int(inventType)
				if filter == 1:
					stdt = input("enter start date (yyyy-mm-dd) : ")
					startdate = stdt
					if self.validateDate(startdate) is False:
						self.inventoryReport()
					enddt = input("enter end date (yyyy-mm-dd hh:mm:ss) : ")
					endDate = enddt
					if self.validateDate(endDate) is False:
						self.inventoryReport()
					queryInventory ='select * from inv_item where created_on between \'' + startdate + '\' and \'' + endDate + '\''
				elif filter ==2:
					print(tabulate([["1","3 Roses"],["2","AVT Tea"],["3","Brooke Bond Taaza"],["4","Lipton Tea"],["5","Marvel Tea"],["6","Pataka Tea"],["7","Society Tea"]], headers=['Id', 'Menu'])) 
					itemOption = input("Select an item  ")
					if itemOption.isdigit():
						queryInventory = 'select * from inv_item  WHERE inv_item_id ='+itemOption
					else:
						print("Enter valid number")	 
						self.inventoryReport()
				elif filter == 3:
					itemOption = input("Enter the discount price ")
					if itemOption.isdigit():
						queryInventory = 'select * from inv_item  WHERE item_max_discount <='+itemOption 
					else:
						print("Enter valid price")	 
						self.inventoryReport()
				elif filter == 4:
					itemOption = input("Enter the price")
					if itemOption.isdigit():
						queryInventory = 'select * from inv_item  WHERE item_mrp_price <='+itemOption
					else:
						print("Enter valid price")	 
						self.inventoryReport()
				elif filter == 5:
					itemOption = input("Enter the Quantity")
					if itemOption.isdigit():
						queryInventory = 'select * from inv_item  WHERE item_quantity <='+str(itemOption)
					else:
						print("Enter valid number")	 
						self.inventoryReport()
				elif filter == 6:
					rId =  userRole
					if rId == 1:
						self.adminReport()
					else:	
						self.inventryManager()
				else:
					print("Choose any filter")			
					self.inventoryReport()
				result=pd.read_sql_query(queryInventory, sql_engine) 
				inventryCount = len(result)
				if inventryCount > 0:
					# print(result)
					print('\n--------------------------------------------------------------------------------------------------------------------------------------\n')					
					print(tabulate(result, headers=['Item Id','Item Name','Item Description','Item MRP Price','Quantity','Item Status','Discount','Created By','Created On','Updated By','Updated On','Weight','Active','Delete Date']))
					#Converting CSV File
					result.to_csv("report.csv", index=False)
					#Converting Excel File
					for csvfile in glob.glob(os.path.join('.', '*.csv')):
					    workbook = Workbook(csvfile[:-4] + '.xlsx')
					    worksheet = workbook.add_worksheet()
					    with open(csvfile, 'rt', encoding='utf8') as f:
					        reader = csv.reader(f)
					        for r, row in enumerate(reader):
					            for c, col in enumerate(row):
					                worksheet.write(r, c, col)
					    workbook.close() 
					#Converting PDF File        
					csv_file = 'report.csv'
					html_file = csv_file[:-3]+'html'
					pdf_file = csv_file[:-3]+'pdf'
					df = pd.read_csv(csv_file, sep=',')
					df.to_html(html_file)
					pdf.from_file(html_file, pdf_file)
					self.inventoryReport()
				else:
					print("No data found in selected filter")
					self.inventoryReport()
			else:
				print("Enter valid input number")
				self.inventoryReport()
		except Exception as e:
			print("Error:----",e)
		
		finally:
			print('\n\tError : Input.',e)
			self.inventoryReport()
コード例 #41
0
	def salesReport(self):
		querySales=None
		print("-----------Sales Report--------------\n")
		print(tabulate([["1","Date"],["2","Item"],["3","Discount"],["4","Selling Price"],["5","Back To Main Menu"]], headers=['Id', 'Menu']))
		salesIDValue = input("Choose filter type? ")
		try:
			if salesIDValue.isdigit():
				filter = int(salesIDValue)
				if filter == 1:
					stdt = input("enter start date (yyyy-mm-dd) : ")
					startdate = stdt
					if self.validateDate(startdate) is False:
						self.salesReport()
					enddt = input("enter end date (yyyy-mm-dd ) : ")
					endDate = enddt
					if self.validateDate(endDate) is False:
						self.salesReport()
					querySales ='select * from so_header_details where created_on between \'' + startdate + '\' and \'' + endDate + '\''
				elif filter == 2:
					print(tabulate([["1","3 Roses"],["2","AVT Tea"],["3","Brooke Bond Taaza"],["4","Lipton Tea"],["5","Marvel Tea"],["6","Pataka Tea"],["7","Society Tea"]], headers=['Id', 'Menu'])) 
					itemOption = input("Select an item  ")
					if itemOption.isdigit():
						querySales = 'select * from so_header_details  WHERE inv_item_id ='+itemOption 
					else:
						print("Enter valid number")
						self.salesReport()	 	
				elif filter == 3:
					itemOption = input("Enter the discount price ")
					if itemOption.isdigit():
						querySales = 'select * from so_header_details  WHERE discount <='+itemOption 
					else:
						print("Enter valid price")
						self.salesReport()
				elif filter == 4:
					itemOption = input("Enter the total seeling price ")
					if itemOption.isdigit():
						querySales = 'select * from so_header_details  WHERE total_price <='+itemOption 
					else:
						print("Enter valid seeling price")
						self.salesReport()
				elif filter == 5:
					rId =  userRole
					if rId == 1:
						self.adminReport()
					else:	
						self.salesManager()
				else:
					print("Choose any filter")
					self.salesReport()
				#queryDate ='select * from inv_item where created_on between \'' + startdate + '\' and \'' + endDate + '\''
				# queryDate = 'select * from so_header_details  WHERE inv_item_id ='+str(itemOption) 
				result=pd.read_sql_query(querySales, sql_engine) 
				totalcount = len(result)
				print("totalcount",totalcount)
				if totalcount > 0:
					# print(result)
					print('\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n')
					print(tabulate(result, headers=['Header Details ID','Item ID','Quantity','Discount','Unit Price','Total Price','Created By','Created On','Updated By','Updated On','Header ID','Delete Date']))
					#Converting CSV File
					result.to_csv("report.csv", index=False)
					#Converting Excel File
					for csvfile in glob.glob(os.path.join('.', '*.csv')):
					    workbook = Workbook(csvfile[:-4] + '.xlsx')
					    worksheet = workbook.add_worksheet()
					    with open(csvfile, 'rt', encoding='utf8') as f:
					        reader = csv.reader(f)
					        for r, row in enumerate(reader):
					            for c, col in enumerate(row):
					                worksheet.write(r, c, col)
					    workbook.close() 
					#Converting PDF File        
					csv_file = 'report.csv'
					html_file = csv_file[:-3]+'html'
					pdf_file = csv_file[:-3]+'pdf'
					df = pd.read_csv(csv_file, sep=',')
					df.to_html(html_file)
					pdf.from_file(html_file, pdf_file)
					self.salesReport()
				else:
					print("No data found in selected filter")
					# if userRole == 1:
					# 	self.adminReport()
					# else:
					self.salesReport()
			else:
				print("Enter valid input number")
				self.salesReport()
		except Exception as e:
			print("Select valid data: ")
		finally:
			print("Input error")
			self.salesReport()
コード例 #42
0
def output_pdf(file_name_prefix, source_url):
    # for Apple doc url, remove the part after #
    target_url = get_target_url(source_url)
    print target_url

    # load url into html text strings
    html = requests.get(target_url)

    # PG 样式2 -
    # 另一个系列的Programming guides
    # 例如: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/index.html
    # https://cdn.rawgit.com/xyzgentoo/printApplePG/master/print-style-1.5.1.css
    # https://cdn.rawgit.com/xyzgentoo/printApplePG/master/print-feedback-1.5.1.css
    updated_html_text = re.sub(
        r'(<link rel=\"stylesheet\" type=\"text/css\" href=\")(.+style-1.5.1.css)(\" />)',
        r'\1https://cdn.rawgit.com/xyzgentoo/printApplePG/master/print-style-1.5.1.css\3',
        html.text)
    updated_html_text = re.sub(
        r'(<link rel=\"stylesheet\" type=\"text/css\" href=\")(.+feedback-1.5.1.css)(\" />)',
        r'\1https://cdn.rawgit.com/xyzgentoo/printApplePG/master/print-feedback-1.5.1.css\3',
        updated_html_text)

    ## replace img src=".. with
    # img src="https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d
    res_prefix_url = get_prefix_url(target_url)

    # 替换img的相对路径
    updated_html_text = re.sub(r'(<img src=\"../)(\w+)',
                               r'<img src="' + res_prefix_url + r'\2',
                               updated_html_text)

    # Note: 替换img没有../的相对路径
    res_prefix_url2 = get_prefix_url2(target_url)
    updated_html_text = re.sub(r'(<img src=\")(\w+)',
                               r'<img src="' + res_prefix_url2 + r'\2',
                               updated_html_text)

    # 注意 那几个js最好不要替换,要不里面也会报出找不到content的问题,pdfkit执行的时候就会报错了

    items = target_url.split('/')
    output_pdf_name = file_name_prefix + '_' + items[len(items) - 1] + '.pdf'

    # use pdfkit to generate the pdf - 这里修改encoding是为了避免显示奇怪的字符
    # TODO python encoding这块还不是特别懂...
    updated_html_text = updated_html_text.encode('latin-1')
    # print updated_html_text

    # 这样用html文件中转一下,可以正确处理encoding的问题,如果使用pdfkit.from_string()也不能输出updatedHtml,估计是pdfkit内部错误
    temp_html_file_name = "temp.html"
    with codecs.open(temp_html_file_name, "w") as f:
        f.write(updated_html_text)

    try:
        # 从html文件生成pdf
        pdfkit.from_file(temp_html_file_name, output_pdf_name)
    except IOError as err:
        # Note: 有js资源找不到的话, 这里会抛出IOError
        print "*** Well, IOError hits: " + str(err)

    # clean up temp file
    os.remove(temp_html_file_name)
    pass
コード例 #43
0
def create_invoice():
    invoice_template_html = 'invoice_template.html'
    invoice_pdf_name = 'invoice.pdf'
    encoding = 'utf-8'
    util_data_path = 'util/data/'

    seller = SellerInvoice(util_data_path + 'seller.txt')
    seller_dict = seller.read_file_seller()
    buyer = BuyerInvoice(util_data_path + 'buyer.txt')
    buyer_dict = buyer.read_file_buyer()
    header = HeaderInvoice(util_data_path + 'header.txt', cur_month, cur_year)
    header_dict = header.read_file_header()

    hours_worked = HoursWorkedInvoice(
        'util/hours_worked/hours_worked_2020.txt')
    hours_worked_dict = hours_worked.read_file_hours_worked()

    output_invoice_path = __set_output_invoice_path()
    number_hours_worked = __set_number_hours_worked(hours_worked_dict)

    details = DetailsInvoice(util_data_path + 'details.txt',
                             number_hours_worked, cur_month, cur_year)
    details_dict = details.read_file_header()

    html_template = """
    <!DOCTYPE html>
    <html lang="en">
      <head>
          <meta charset="utf-8">
          <title>Invoice</title>
          <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
          <link rel="stylesheet" href="util/template/style.css"/>
      </head>
      <body>
        <div id="container_top">
            <section id="top_details">
              <section>
                  <div class="column1">
                      <div>
                          <div class="invoice_title">""" + details_dict[
        'invoice_title'] + """</div>
                      </div>
                      <div>
                          <div class="seller_header">Sprzedawca</div>
                          <div class="seller_name">""" + seller_dict['name'] + """</div>
                          <div class="seller_nip">NIP: """ + seller_dict[
            'nip'] + """</div>
                          <div class="seller_street">""" + seller_dict[
                'street'] + """</div>
                          <div class="seller_city">""" + seller_dict['city'] + """</div>
                      </div>
                  </div>
                  <div class="column2">
                      <div>
                          <div class="place_of_issue">Miejsce wystawienia</div>
                          <div class="place_of_issue_city">""" + header_dict[
                    'city'] + """</div>
                          <div class="date_of_issue">Data wystawienia</div>
                          <div class="date_of_issue_details">""" + header_dict[
                        'create_date'] + """</div>
                          <div class="sell_date">Data sprzedaży</div>
                          <div class="sell_date_details">""" + header_dict[
                            'sell_date'] + """</div>
                      </div>
                      <div>
                          <div class="buyer_header">Nabywca</div>
                          <div class="buyer_name">""" + buyer_dict['name'] + """</div>
                          <div class="buyer_nip">NIP: """ + buyer_dict['nip'] + """</div>
                          <div class="buyer_street">""" + buyer_dict[
                                'street'] + """</div>
                          <div class="buyer_city">""" + buyer_dict['city'] + """</div>
                      </div>
                  </div>
            </section>
        </div>
        <div id="container_main_details">
            <section id="main_details">
                <div class="services">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Lp.</th>
                                <th>Nazwa towaru lub usługi</th>
                                <th>Jm.</th>
                                <th>Ilość</th>
                                <th>Cena netto</th>
                                <th>Wartość netto</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>""" + details_dict['lp'] + """</td>
                                <td>""" + details_dict['title'] + """</td>
                                <td>""" + details_dict['jm'] + """</td>
                                <td>""" + number_hours_worked + """</td>
                                <td>""" + details_dict['net_per_hour'] + """</td>
                                <td>""" + details_dict['net_all_price'] + """</td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td class="last">VAT</td>
                                <td class="last">""" + details_dict[
                                    'vat_percent'] + """</td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td class="last">Kwota VAT</td>
                                <td class="last">""" + details_dict[
                                        'vat_price'] + """</td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td class="last">Razem brutto</td>
                                <td class="last">""" + details_dict[
                                            'gross_all_price'] + """</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </section>
        </div>
        <div id="container_bottom">
            <section id="bottom_details">
                <div class="column3">
                    <div class="payment">Sposób płatności:</div>
                    <div class="account">Numer konta:</div>
                    <div class="total_price_digital">Do zapłaty:</div>
                    <div class="total_price_word">Kwota słownie:</div>
                </div>
                <div class="column4">
                    <div class="payment_details">""" + details_dict[
                                                'payment'] + """</div>
                    <div class="account_details">""" + details_dict[
                                                    'account'] + """</div>
                    <div class="total_price_digital_details">""" + details_dict[
                                                        'gross_all_price'] + """ PLN</div>
                    <div class="total_price_word_details">""" + details_dict[
                                                            'total_price_word'] + """</div>
                </div>
            </section>
        </div>
        <div id="signature">
            <div>
                <p>Wystawił:</p>
            </div>
            <div>
                <p>Odebrał:</p>
            </div>
        </div>
      </body>
    </html>

        """

    __remove_invoice_if_exist(invoice_template_html, invoice_pdf_name)
    __create_template_and_save_as_html(invoice_template_html, html_template,
                                       encoding)
    pdfkit.from_file(invoice_template_html,
                     output_invoice_path + '/' + invoice_pdf_name)
コード例 #44
0
ファイル: xa.py プロジェクト: quattie528/pylibq
def txts2pdf(txts, ex):
    pdfkit.from_file(x, ex)
コード例 #45
0
            if filename.endswith("md"):
                cmd = "grip \"{0}\" --export \"{1}\"".format(infile, outfile)
                # print (cmd)
                os.system(cmd)
                # add filename to TOC
                # print("TOC: {0} {1}",TOC,filename)
                appendTOC(TOC, 0, filename)

print("done converting .ipynb and .md to .html")

#create PDFs
# TODO: fix images - they don't show.
# TODO: Is wkhtmltopdf in the path?
# TODO: prompt to find file
path_wkthmltopdf = r'C:\Users\GBTC440001ur\djw\jupyterbook\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)

for root, directories, filenames in os.walk(path):
    for filename in filenames:
        name, ext = os.path.splitext(filename)
        infile = os.path.join(root, filename)
        print(infile)
        if ext == ".html":
            outfile = os.path.join(path, filename + ".pdf")
            print(outfile)
            pdfkit.from_file(infile, outfile, configuration=config)

print("done making PDFs")

# push to github
コード例 #46
0
    if i > 0 and i % pagesize == 0:
        html.write('<span class="pagebreak"></span>\n')

    html.write("<div>")
    html.write(blurb)
    for s in prettify(cluster):
        html.write("<li>%s</li>\n" % s)
    html.write("</ul></p>")
    html.write(
        "<p>login: <b><code>{}</code></b> <br>password: <b><code>{}</code></b></p>\n"
        .format(instance_login, instance_password))
    html.write(footer)
    html.write("</div>")
html.close()
"""
    html.write("<div>")
    html.write("<p>{}</p>".format(blurb))
    for s in prettify(cluster):
        html.write("<li>{}</li>".format(s))
    html.write("</ul></p>")
    html.write("<center>")
    html.write("<p>login: <b><code>{}</code></b> &nbsp&nbsp  password: <b><code>{}</code></b></p>\n".format(instance_login, instance_password))
    html.write("</center>")
    html.write(footer)
    html.write("</div>")
html.close()
"""

with open('ips.html') as f:
    pdfkit.from_file(f, 'ips.pdf')
コード例 #47
0
                volume = current_volume

            chapter_title = text_list[2].split(" : ")[-1]
            html_content += f'<h2 style="font-size: 2em; font-weight: bold;">Chapter {int(URL_NUM)-1} : {chapter_title}</h2>'

            # format as html <p> string
            for i in range(len(text_list)):
                if "* * *" in text_list[i]:
                    html_content += f'<p style="text-align: center">{text_list[i]}</p>\n'
                else:
                    html_content += f'<p>{text_list[i]}</p>\n'

            # append HTML file
            with open(f"{file_path}.html", 'a+') as htmlFile:
                htmlFile.write(html_content)
                htmlFile.write("\n")

            print(
                f"Volume: {volume} | Chapter: {int(URL_NUM)-1} : {chapter_title}"
            )

    # NO MORE CHAPTERS
    print(f"No more chapters available")
    html_content += '</body></html>'
    # append HTML file
    with open(f"{file_path}.html", 'a+') as htmlFile:
        htmlFile.write(html_content)

    pdfkit.from_file(input=f"{file_path}.html", output_path=f"{file_path}.pdf")
    # (html_content, f"{file_path}.pdf")
コード例 #48
0
__author__ = 'SGNET\gmarco'

import pdfkit

css = '/home/likewise-open/SGNET/gmarco/Desktop/informe_html/css/report.css'

pdfkit.from_file(
    '/home/likewise-open/SGNET/gmarco/Desktop/informe_html/results_report.html',
    '/home/likewise-open/SGNET/gmarco/Desktop/informe_html/results_report.pdf')
コード例 #49
0
import pdfkit

url = 'https://b2b.baidu.com/s?q=ppr&from=search'  # 一篇博客的url
confg = pdfkit.configuration(
    wkhtmltopdf='D:\Program Files\wkhtmltopdf\\bin\wkhtmltopdf.exe')
# 这里指定一下wkhtmltopdf的路径,这就是我为啥在前面让记住这个路径
# pdfkit.from_url(url, 'jmeter_下载文件.pdf', configuration=confg)
# from_url这个函数是从url里面获取内容
# 这有3个参数,第一个是url,第二个是文件名,第三个就是khtmltopdf的路径

pdfkit.from_file('C:/Users/39554/Desktop/【ppr】ppr价格_ppr批发_ppr厂家-百度爱采购.html',
                 'jmeter_下载文件2.pdf',
                 configuration=confg)
# from_file这个函数是从文件里面获取内容
# 这有3个参数,第一个是一个html文件,第二个是文生成的pdf的名字,第三个就是khtmltopdf的路径

# html = '''
# <div>
# <h1>title</h1>
# <p>content</p>
# </div>
# '''  # 这个html是我从一个页面上拷下来的一段,也可以

# pdfkit.from_string(html, 'jmeter_下载文件3.pdf',configuration=confg)
# from_file这个函数是从一个字符串里面获取内容
# 这有3个参数,第一个是一个字符串,第二个是文生成的pdf的名字,第三个就是khtmltopdf的路径
コード例 #50
0
printhtml.write(
    printtemplate.render(first=sections[0],
                         second=sections[2],
                         third=sections[1]))

printhtml.close()

emailhtml = open("email.html", "w")

emailhtml.write(
    emailtemplate.render(first=sections[0],
                         second=sections[2],
                         third=sections[1]))

emailhtml.close()

options = {
    'page-size': 'A4',
    'orientation': 'Landscape',
    'enable-local-file-access':
    None  # so that external css files can be used to style
}

pdfkit.from_file("print.html", "print.pdf", options=options)

#NOTES
#deactive a pipenv environment by typing deactivate
#wkhtmltopdf.org needs to be installed for script to work (or you can save to pdf from html)
#start up pipenv by running pipenv shell
#za to toggle folds in vim, ctrl-shift to move between cmd tabs, :b to move between vim buffers
コード例 #51
0
ファイル: rtd-single.py プロジェクト: zingmars/kumo-ripper
def htmlToPDF():
    pdfkit.from_file(htmlFileName, pdfFileName)
コード例 #52
0
ファイル: csv2pdf.py プロジェクト: MJ-Mohith/cerner_2-5_2019
# cerner_2^5_2019

import pandas as pd
import pdfkit as pdf

csv_file = 'test.csv'
html_file = csv_file[:-3] + 'html'
pdf_file = csv_file[:-3] + 'pdf'

df = pd.read_csv(csv_file, sep=',')
df.to_html(html_file)
pdf.from_file(html_file, pdf_file)
コード例 #53
0
from flask import Flask, render_template, make_response, redirect, url_for, request
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField
from wtforms.validators import InputRequired, Length
import pdfkit

"""
config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe')
pdfkit.from_file('templates/report.html', 'out-test.pdf', configuration=config)
"""

app = Flask(__name__)
app.secret_key='hello'   # secret key used for encrypt and decrypt server data


Bootstrap(app)

class reportForm(FlaskForm):
    name = StringField('Name', validators=[InputRequired(), Length(min=5, max=15)])
    location = StringField('Location', validators=[InputRequired(), Length(min=2, max=30)])
    amount_fined = IntegerField('Amount Fined', validators=[InputRequired(), Length(min=1, max=5)])


@app.route('/', methods=["POST", "GET"]) #http://127.0.0.1:5000/name/location
#def pdf_template(name, location, amount_fined):
def pdf_template():
    # let each final pdf be named with the string of the first name together withe license number
    
    path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
    # Pass the options to format the pdf
コード例 #54
0
ファイル: ex01.py プロジェクト: NLPDev/PDF
import pdfkit

pdfkit.from_file("canvas.html", "out.pdf")
pdfkit.from_url("https://demo.waiver.dizio.app/kapowsin/pages/page1.html", "out.pdf")
コード例 #55
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/1/10 15:22
# @Author  : lingxiangxiang
# @File    : demon1.py

import pdfkit
pdfkit.from_url('http://google.com', 'out1.pdf')
pdfkit.from_file("test.html", "out2.pdf")
pdfkit.from_string("hello ajing", "out3.pdf")
コード例 #56
0
 def convert_html_file_to_pdf(self, html_file_path, output_file_path, options=None, toc=None, cover=None, css=None,
                              configuration=None, cover_first=False):
     try:
         pdfkit.from_file(html_file_path, output_file_path, configuration=self.config)
     except Exception as e:
         print(e)
コード例 #57
0
 def download_webpage(self):
     pdfkit.from_file('timetable.html','out.pdf'))
コード例 #58
0
def generate():
    global DojoURL
    global TestID
    global TestName
    global FindingsCount
    global Product
    global OutputFile
    global Template
    global JIRA
    global PDF
    global Config
    global ID

    user = User.query.filter_by(id=current_user.id).first()
    api_key = user.api_key
    DojoURL = user.dojo_url

    letters = string.ascii_lowercase

    ID = (datetime.datetime.now().strftime("%m-%d-%y-%I-%M") + '-' +
          (''.join(random.choice(letters) for i in range(10))))

    os.mkdir(('reports/' + ID))

    TestID = request.form['testid']
    if 'jira' in request.form:
        JIRA = True
    else:
        JIRA = False
    if 'pdf' in request.form:
        PDF = True
    else:
        PDF = False
    OutputFile = request.form['filename']
    Template = request.form['template']
    if request.files['template_config'].filename == '':
        Config = ''
    else:
        f = request.files['template_config']
        f.save(f'reports/{ID}/{secure_filename(f.filename)}')
        Config = ('reports/' + ID + '/' + f.filename)

    TestName = test.by_id(DojoURL, api_key, TestID)['title']

    FindingsCount = findings.finding_count(DojoURL, api_key, TestID)

    Engagement = test.by_id(DojoURL, api_key, TestID)['engagement']

    Product = product.by_id(
        DojoURL, api_key,
        engagement.by_id(DojoURL, api_key, Engagement)['product'])

    ProductType = product.product_type(DojoURL, api_key, Product['prod_type'])

    Findings = findings.by_test_id(DojoURL, api_key, TestID)

    Endpoints = {}

    for finding in Findings['results']:
        keys = []
        for x in range(0, len(finding['endpoints'])):
            keys.append(finding['endpoints'][x])

        for key in keys:
            endpoint_details = endpoints.by_id(DojoURL, api_key, key)
            endpoint = endpoint_details['protocol'] + '://' + endpoint_details[
                'host'] + endpoint_details['path']
            Endpoints.update({str(key): endpoint})

    JiraTickets = []

    if JIRA == True:
        for x in Findings['results']:
            try:
                JiraTickets.append(
                    jira.by_finding_id(DojoURL, api_key,
                                       x['id'])['results'][0]['jira_key'])
            except:
                JiraTickets.append('No Ticket Available')
    else:
        pass

    env = Environment(loader=FileSystemLoader('../templates'))
    template = env.get_template(Template)

    if JIRA == True:
        output = template.render(engagement=engagement.by_id(
            DojoURL, api_key, Engagement),
                                 product=Product,
                                 product_type=ProductType,
                                 test=test.by_id(DojoURL, api_key, TestID),
                                 findings=Findings,
                                 endpoints=Endpoints,
                                 jira=JiraTickets)
    else:
        output = template.render(engagement=engagement.by_id(
            DojoURL, api_key, Engagement),
                                 product=Product,
                                 product_type=ProductType,
                                 test=test.by_id(DojoURL, api_key, TestID),
                                 findings=Findings,
                                 endpoints=Endpoints)

    if PDF == True:

        options = options = {'quiet': ''}

        with open(('reports/' + ID + '/' + OutputFile + '.html'), 'w') as file:
            file.write(output)
            file.close()

        if Config != '':
            temp_config.template_config(
                ('reports/' + ID + '/' + OutputFile + '.html'), Config)
            with open(Config, 'r') as config_file:
                contents = json.load(config_file)
                config_file.close()

            if contents['pdf']:
                options = contents['pdf']
            else:
                pass
        else:
            pass

        pdfkit.from_file(('reports/' + ID + '/' + OutputFile + '.html'),
                         ('reports/' + ID + '/' + OutputFile + '.pdf'),
                         options=options)

    else:

        with open(('reports/' + ID + '/' + OutputFile + '.html'), 'w') as file:
            file.write(output)
            file.close()

        if len(Config) != 0:
            temp_config.template_config(
                ('reports/' + ID + '/' + OutputFile + '.html'), Config)
        else:
            pass

    return redirect(url_for('report', ReportName=OutputFile))
コード例 #59
0
    def PrintReportBill(self, e):
        CountSales = self.tableSales.rowCount()
        if CountSales != 0:
            self.setEnabled(False)
            self.labPrint.setEnabled(False)
            Time = self.labTimeAndDay.text()
            BillID = self.labBillID.text()
            NameUser = self.labNameSalse.text()
            NameSection = self.labNameSection.text()
            NameCus = self.labNameCus.text()
            CusID = self.labCusID.text()
            NumberItem = self.label_24.text()
            Toatal = self.labTotalAll.text()
            textReport = """
            <!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Sales</title>
	<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="css/bootstrap-rtl.min.css">
	<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

	<div class="container">
		<header class="header">
			<h2 class="titleMarket">شركة محمد عيسى</h2>
		</header>
			<div class="panel panel-primary">
				<div class="panel-heading" style="position: relative;">
					<table width="50%">
					  <col width="20">
  					 <col width="20">
  					 <col width="20">
  					 <col width="10">
						<tr>
							<td >عدد المنتجات : </td>
							<td class="td-color">[ {0} ]</td>
							<td >المبلغ الاجمالي :</td>
							<td class="td-color">[ {1} ]</td>
						</tr>
					</table>
					<span class="pull-left date-time">{2}</span>
					<div class="clear"></div>
				</div>
			</div>
		<div class="">

			<div class="pull-right" style="width: 49%">
				<div class="panel panel-primary">
				  <div class="panel-heading">معلومات الفاتوره</div>
				  <div class="panel-body">
					<table width="100%">
						<tr>
							<td >معرف الفاتوره :</td>
							<td>{3}</td>
						</tr>
						<tr>
							<td>اسم البائع :</td>
							<td>{4}</td>
						</tr>
						<tr>
							<td> القسم :</td>
							<td>{5}</td>
						</tr>
					</table>
				  </div>
				</div>
			</div>

			<div class="pull-left" style="width: 49%">
				<div class="panel panel-primary">
				  <div class="panel-heading">معلومات العميل</div>
				  <div class="panel-body">
					<table width="100%">
						<tr>
							<td >معرف العميل :</td>
							<td>{6}</td>
						</tr>
						<tr>
							<td>اسم العميل :</td>
							<td>{7}</td>
						</tr>

					</table>
				  </div>
				</div>
			</div>
		</div>
		<div class="clear"></div>
		<table class="table table-striped">
		  <thead>
		    <tr>
		      <th>#</th>
		      <th>معرف المنتج</th>
		      <th>اسم المنتج</th>
		      <th>الثمن</th>
		      <th>الكميه</th>
		      <th>الثمن الكلي</th>
		    </tr>
		  </thead>
		  <tbody>
            """.format(NumberItem, Toatal, Time, BillID, NameUser, NameSection,
                       CusID, NameCus)
            file = open('report/reportSales.html', 'w')
            file.write(textReport)
            file.close()
            reportSales = open('report/reportSales.html', 'a+')
            number = 1
            for i in range(CountSales):
                textNew = """
                	<tr>
                      <th scope="row">{0}</th>
                      <td>{1}</td>
                      <td>{2}</td>
                      <td>{3}</td>
                      <td>{4}</td>
                      <td>{5}</td>
                    </tr>
                """.format(number,
                           self.tableSales.item(i, 0).text(),
                           self.tableSales.item(i, 1).text(),
                           self.tableSales.item(i, 2).text(),
                           self.tableSales.item(i, 3).text(),
                           self.tableSales.item(i, 4).text())
                reportSales.write(textNew)
                number += 1
            reportSales.write("""
            		  </tbody>
                    </table>
                </div>
                <script src="js/jquery-3.2.1.min.js"></script>
                <script src="js/bootstrap.min.js"></script>
                <script src="js/main.js"></script>
            </body>
            </html>
            """)
            reportSales.close()

            saveReport = QFileDialog.getSaveFileNameAndFilter(
                self, 'حفظ التقرير'.decode(), 'ReportSales.pdf', '*.pdf')[0]
            if saveReport:
                config = pdfkit.configuration(
                    wkhtmltopdf=
                    r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
                convert = pdfkit.from_file('report/reportSales.html',
                                           str(saveReport),
                                           configuration=config)
                if convert:
                    QMessageBox.information(
                        self, 'حفظ الفاتوره'.decode(),
                        'تم حفظ الفاتوره في المسار \n [ {} ]'.decode().format(
                            saveReport))
            self.setEnabled(True)
            try:
                os.system("start " + str(saveReport))
            except:
                pass
            self.labAddSales.setEnabled(True)
            self.Cancel()
コード例 #60
0
#Download all emails and create a metafile
emails = g.mailbox('advantEdge Expense').mail(after=datetime(2018, 03, 31))
print str(len(emails)) + " emails found"
i = 0;
metaFile = open("emails/{}/html/files.txt".format(sessionName),"a") #store metadata
for email in emails[:]:
    email.fetch()
    file = open("emails/"+sessionName+"/html/"+str(i)+".html","w")
    file.write(email.html)
    file.close()
    meta = "{}, {}, emails/{}/html/{}.html, {}\n".format(email.fr, email.subject, sessionName, str(i), email.sent_at)
    print meta
    metaFile.write(meta)
    #print "Wrote " + str(i) +".html"
    #Convert email to pdf
    pdfkit.from_file("emails/"+sessionName+"/html/"+str(i)+".html", "emails/"+sessionName+"/pdf/"+str(i)+".pdf")
    ### JUST DO IT

    #Write Excel Data

    #If the email is from Uber, extract rideInfo
    if "uber" in email.fr:
        rideInfo = GetDetails(BeautifulSoup(email.html))
        #Write csv with pdf links & rideInfo where applicable
        
    i+=1
metaFile.close()

#create a tarball of the Download
#upload to s3 or something
#delete sessionName folder recursively