def test_custom_configuration(self): conf = pdfkit.configuration() self.assertEqual('pdfkit-', conf.meta_tag_prefix) conf = pdfkit.configuration(meta_tag_prefix='prefix-') self.assertEqual('prefix-', conf.meta_tag_prefix) with self.assertRaises(IOError): conf = pdfkit.configuration(wkhtmltopdf='wrongpath')
def __init__(self): path = os.environ.get('WKHTMLTOPDF_PATH', None) if path: config = pdfkit.configuration(wkhtmltopdf=path) else: config = pdfkit.configuration() self.config = config
def Mypdf(request): # filename = 'create.pdf' # pdf = wkhtmltopdf(template) # return HttpResponse(pdf) # config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/html2pdf') # pdfkit.from_string('template', 'salary1.pdf', configuration=config) logger = logging.getLogger('pdf') logger.info('pdf file') config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/html2pdf') composers = ComposersProfile.objects.all() for composer in composers: context = Context({'my_name': composer.first_name,'last_name':composer.last_name }) print context body = "<html>ggggggg</html>" template = Template("<table>My name is</table>{{ my_name }}{{ last_name }}") print template m = template.render(context) print m pdfkit.from_string(m, 'salary7.pdf', configuration=config) mail = EmailMultiAlternatives('Regarding Password Change','email_body','*****@*****.**',['*****@*****.**']) mail.attach_file('salary7.pdf') mail.send() logger.info('end') return HttpResponse('0')
def generate_pdf(request, site): reportPdfUrl = 'http://%s/report/view/%s' % (request.META['HTTP_HOST'],str(site.pk)) outputStream = BytesIO() reportPdfFile = '%s/download_%s.pdf' % (settings.DOWNLOAD_ROOT, site.pk) wkhtmltopdfBinLocationString = '/usr/local/bin/wkhtmltopdf' wkhtmltopdfBinLocationBytes = wkhtmltopdfBinLocationString.encode('utf-8') config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdfBinLocationBytes) pdfkit.from_url(reportPdfUrl, reportPdfFile, configuration=config, options={ 'javascript-delay': 1500, 'load-error-handling': 'ignore' }) new_pdf = PdfFileMerger() new_pdf.append('%s/download_%s.pdf' % (settings.DOWNLOAD_ROOT, site.pk)) # finally, return output new_pdf.write(outputStream) final = outputStream.getvalue() outputStream.close() os.remove(reportPdfFile) return final
def pdf_from_html(html, header_html=None, footer_html=None, wkhtmltopdf_options=None): """ Takes HTML and returns a PDF (as a buffer). For engines not supporting CSS Paged Media - meaning, here, wkhtmltopdf - the header_html and footer_html options allow you to pass appropriate HTML content to serve as the header/footer (rather than passing it within the main HTML). """ if processor == XHTML2PDF: memfile = io.BytesIO() xhtml2pdf.document.pisaDocument(html, memfile) # ... returns a document, but we don't use it, so we don't store it to # stop pychecker complaining # http://xhtml2pdf.appspot.com/static/pisa-en.html memfile.seek(0) return buffer(memfile.read()) # http://stackoverflow.com/questions/3310584 elif processor == WEASYPRINT: # http://ampad.de/blog/generating-pdfs-django/ return weasyprint.HTML(string=html).write_pdf() elif processor == PDFKIT: if _wkhtmltopdf_filename is None: config = None else: config = pdfkit.configuration(wkhtmltopdf=_wkhtmltopdf_filename) # Temporary files that a subprocess can read: # http://stackoverflow.com/questions/15169101 # wkhtmltopdf requires its HTML files to have ".html" extensions: # http://stackoverflow.com/questions/5776125 h_filename = None f_filename = None try: if header_html: if not wkhtmltopdf_options: wkhtmltopdf_options = {} h_fd, h_filename = tempfile.mkstemp(suffix='.html') os.write(h_fd, header_html) os.close(h_fd) wkhtmltopdf_options["header-html"] = h_filename if footer_html: if not wkhtmltopdf_options: wkhtmltopdf_options = {} f_fd, f_filename = tempfile.mkstemp(suffix='.html') os.write(f_fd, footer_html) os.close(f_fd) wkhtmltopdf_options["footer-html"] = f_filename kit = pdfkit.pdfkit.PDFKit(html, 'string', configuration=config, options=wkhtmltopdf_options) return kit.to_pdf(path=None) finally: if h_filename: os.remove(h_filename) if f_filename: os.remove(f_filename) else: raise AssertionError("Unknown PDF engine")
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)
def render_to_pdf(request, html, footer_file): wkhtmltopdfpath = request.config.get('wkhtmltopdfpath', r'c:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe') config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdfpath) return pdfkit.from_string(html, False, configuration=config, options={ 'footer-html': footer_file, 'margin-bottom': request.viewdata.dom.PDFBottomMargin, 'page-size': 'letter', 'disable-javascript': None, 'print-media-type': None, 'quiet': None, 'load-error-handling': 'ignore' })
def to_pdf(self,file_path=None,**options): """Converts the file to a pdf and saves it at file_path. If file_path is None, it will auto name the resulting file to self.path with pdf as the extension""" #todo: add toc and other options in wkhtmltopdf if file_path is None: file_path=change_extension(self.path,"pdf") config = pdfkit.configuration(wkhtmltopdf=WKHTML_PATH) pdfkit.from_string(str(self),file_path,configuration=config) return file_path
def async_pdf_report(self, report=None, template="None", filename='report.pdf', report_title=None, report_subtitle=None, report_info=None, context={}, uri=None): xsl_style_sheet = settings.DOJO_ROOT + "/static/dojo/xsl/pdf_toc.xsl" x = urlencode({'title': report_title, 'subtitle': report_subtitle, 'info': report_info}) cover = context['host'] + reverse( 'report_cover_page') + "?" + x config = pdfkit.configuration(wkhtmltopdf=settings.WKHTMLTOPDF_PATH) try: report.task_id = async_pdf_report.request.id report.save() bytes = render_to_string(template, context) itoc = context['include_table_of_contents'] if itoc: toc = {'xsl-style-sheet': xsl_style_sheet} else: toc = None pdf = pdfkit.from_string(bytes, False, configuration=config, cover=cover, toc=toc) if report.file.name: with open(report.file.path, 'w') as f: f.write(pdf) f.close() else: f = ContentFile(pdf) report.file.save(filename, f) report.status = 'success' report.done_datetime = datetime.now(tz=localtz) report.save() #email_requester(report, uri) except Exception as e: report.status = 'error' report.save() #email_requester(report, uri, error=e) raise e return True
def save_pdf_from_string(self,input,output,orientation='portrait'): options = { 'page-size':'A4', 'margin-top':'0cm', 'margin-right':'0cm', 'margin-bottom':'0cm', 'margin-left':'0cm', 'orientation':orientation, 'print-media-type':'', } config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf') pdfkit.from_string(input,output,options=options,configuration=config)
def test_order_invoice(): logger.info("test order invoice") tenant_id = g.user.tenant_id try: query = {'tenant_id': ObjectId(tenant_id), 'status': 'DELIVERED'} order = [x for x in mongo.db.order_collection.find(query).sort("created_at", -1)][0] config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf'.encode('utf-8')) html_text = render_template("email/order_invoice.html", order=order) output_filename = os.path.join(invoice_emails_folder, "Invoice-%s.pdf" % (order['order_no'])) pdfkit.from_string(html_text, output_filename, configuration=config) return send_file(output_filename, mimetype='application/pdf') except Exception as e: logger.exception(e) return "Error in generating PDF invoice"
def async_pdf_report(self, report=None, template="None", filename='report.pdf', report_title=None, report_subtitle=None, report_info=None, context={}, uri=None): xsl_style_sheet = settings.DOJO_ROOT + "/static/dojo/xsl/pdf_toc.xsl" x = urlencode({'title': report_title, 'subtitle': report_subtitle, 'info': report_info}) cover = context['host'] + reverse( 'report_cover_page') + "?" + x try: config = pdfkit.configuration(wkhtmltopdf=settings.WKHTMLTOPDF_PATH) report.task_id = async_pdf_report.request.id report.save() bytes = render_to_string(template, context) itoc = context['include_table_of_contents'] if itoc: toc = {'xsl-style-sheet': xsl_style_sheet} else: toc = None pdf = pdfkit.from_string(bytes, False, configuration=config, cover=cover, toc=toc) if report.file.name: with open(report.file.path, 'w') as f: f.write(pdf) f.close() else: f = ContentFile(pdf) report.file.save(filename, f) report.status = 'success' report.done_datetime = timezone.now() report.save() create_notification(event='report_created', title='Report created', description='The report "%s" is ready.' % report.name, url=uri, report=report, objowner=report.requester) except Exception as e: report.status = 'error' report.save() log_generic_alert("PDF Report", "Report Creation Failure", "Make sure WKHTMLTOPDF is installed. " + str(e)) return True
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)
def getPDFOfLinks(links): # links = [link for link in linkList for linkList in [getLinksFromSubscription(sub) for sub in subscriptions]] # flatten list of lists of links print links ''' i = 1 FILENAME = 'tempHtmlFile' fileNameStrings = [] import os currentPath = os.getcwd() for link in links: try: response = urllib2.urlopen(link) page_content = response.read() fname = currentPath+'/'+'getFeeds/'+FILENAME+str(i)+".html" with open(fname, 'w') as temp: temp.write(page_content) fileNameStrings.append(fname) i = i+1 except: pass # fileNameStrings = [FILENAME+str(ii+1) for ii in range(i)] ''' options = { 'load-error-handling': 'skip', 'load-media-error-handling': 'skip', 'disable-javascript':None } toc = { 'toc-header-text':"Table Of Contents" } config = pdfkit.configuration(wkhtmltopdf= "/app/bin/wkhtmltopdf") # outputpdf = pdfkit.from_file(fileNameStrings,"out.pdf",configuration = config) # outputPdf = pdfkit.from_file(fileNameStrings,False,configuration = config) outputPdf = pdfkit.from_url(links,False,configuration=config,toc=toc,options=options) return outputPdf
def process_html_pdf(config, step, localMergedFileName, localMergedFileNameOnly, subs): flavour = "pdfkit" try: if step["flavour"]=="weasyprint": flavour = "weasyprint" except KeyError: pass if flavour == "weasyprint": html_in = weasyprint.HTML(localMergedFileName+step["local_ext"]) doc = html_in.write_pdf(target = localMergedFileName+".pdf") else: path_wkthmltopdf = b'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) output_dir = localMergedFileName[:localMergedFileName.rfind(os.path.sep)] doc = pdfkit.from_file(localMergedFileName+step["local_ext"], localMergedFileName+".pdf", configuration=config) outcome = {"file":localMergedFileName+".pdf"} outcome["link"] = subs["site"]+"file/?name="+localMergedFileNameOnly+".pdf" return outcome
def handle(event, context): url = event.get('url', 'https://google.com') filename = event.get('filename', 'test.pdf') config = pdfkit.configuration(wkhtmltopdf='/opt/bin/wkhtmltopdf') pdf_content = pdfkit.from_url(url, False, configuration=config) client.put_object(ACL='public-read', Body=pdf_content, ContentType='application/pdf', Bucket=S3_BUCKET_NAME, Key='source/previews/' + filename) object_url = 'https://{0}.s3.amazonaws.com/{1}'.format( S3_BUCKET_NAME, filename) response = { 'statusCode': 200, 'body': object_url, 's3_bucket': S3_BUCKET_NAME } return response
def generate_pdf(request, template_path, context, file_name): html_template = get_template(template_path) rendered_html = html_template.render(request=request, context=context)#.encode(encoding="UTF-8") options = { 'page-size': 'Letter', 'margin-top': '0.25in', 'margin-right': '0.25in', 'margin-bottom': '0.25in', 'margin-left': '0.25in', 'encoding': "UTF-8", } #'no-outline': None css = '{0}/css/base.css'.format(settings.STATICFILES_DIRS[0]) pdf_name = "{0}/pdf/{1}.pdf".format(settings.STATICFILES_DIRS[0], file_name) config = configuration(wkhtmltopdf=bytes(settings.PATH_TO_WKHTMLTOPDF, 'utf-8')) from_string(rendered_html, pdf_name, options=options, css=css, configuration=config) pdf = open(pdf_name,mode='rb')#,encoding = "ISO-8859-1") response = HttpResponse(pdf.read(), content_type='application/pdf') # Generates the response as pdf response. response['Content-Disposition'] = 'attachment; filename={0}.pdf'.format(file_name) pdf.close() remove(pdf_name) # remove the locally created pdf file. return response
def pdfGeneration(html_out, grade, upid): path = r'/home/ec2-user/wkhtmltopdf' config = pdfkit.configuration(wkhtmltopdf=path) text = open('{}parent_report_{}.html'.format(grade, upid), 'w') text.write(html_out) text.close() options = { 'quiet': '', 'page-size': 'A4', #'margin-top': '1.0in', #'margin-bottom': '1.0in', #'margin-right': '0.5in', #'margin-left': '0.5in', 'encoding': "UTF-8", 'no-outline': None } pdfkit.from_file('{}parent_report_{}.html'.format(grade, upid), 'reports/Grade{}_{}_{}.pdf'.format(grade, month, upid), configuration=config, options=options) os.remove('{}parent_report_{}.html'.format(grade, upid))
def download(type): date = datetime.today().strftime('%d-%m-%y') members = db.query(Member).order_by(Member.name) guests = db.query(Guest).order_by(Guest.name) rendered_page = render_template("/lista_export.html", members=members, guests=guests) if type == "html": with open(f'lista_{date}.html', mode="w", encoding='utf-8') as html_file: html_file.write(rendered_page) return send_file(f"./lista_{date}.html", mimetype='text/html', attachment_filename=f'lista_{date}.html', as_attachment=True) if type == "pdf": path = r"bin/wkhtmltopdf" config = pdfkit.configuration(wkhtmltopdf=path) pdf = pdfkit.from_string(rendered_page, False, configuration=config) filename = f'lista_{date}.pdf' response = make_response(pdf) response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] = f'attachment; filename={filename}' return response
def export_pdf(self, content): try: html = f''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{title}</title> </head> <body> <h2 style="text-align: center;font-weight: 400;">{title}</h2> {content} </body> </html> ''' # windows 下需要配置此项 config = pdfkit.configuration(wkhtmltopdf='C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe') pdfkit.from_string(html, self.output_path + os.path.sep + f'{title}.pdf', configuration=config) except Exception as e: # 导出存在异常 print(e)
def generate_pdf(event, context): # Defaults key = 'deafult-filename.pdf' html = "<html><head></head><body><h1>It works! This is the default PDF.</h1></body></html>" # Decode json and set values for our pdf if 'body' in event: data = json.loads(event['body']) key = data['filename'] html = data['html'] # Set file path to save pdf on lambda first (temporary storage) filepath = '/tmp/{key}'.format(key=key) # Create PDF config = pdfkit.configuration(wkhtmltopdf="binary/wkhtmltopdf") pdfkit.from_string(html, filepath, configuration=config, options={}) # Upload to S3 Bucket r = client.put_object(ACL='public-read', Body=open(filepath, 'rb'), ContentType='application/pdf', Bucket=S3_BUCKET_NAME, Key=key) # Format the PDF URI object_url = "https://{0}.s3.amazonaws.com/{1}".format(S3_BUCKET_NAME, key) # Response with result response = { "headers": { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": True, }, "statusCode": 200, "body": object_url } return response
def generate_pdf(self, content): # 生成pdf页,并设置大小 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) path_wk = BASE_DIR + '\\w\\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wk) options = { 'encoding': "utf-8", 'page-height': '50mm', # 设置高 'page-width': '80mm', # 设置宽 'margin-top': '0mm', 'margin-right': '0mm', 'margin-bottom': '0mm', 'margin-left': '0mm' } pdfkit.from_string(content, "temp.pdf", options=options, configuration=config) #创建一个pdf文件合并对象 # pdfMerger = PdfFileMerger() # if (os.path.exists(BASE_DIR + "\\result.pdf")): # with open("result.pdf", 'rb') as fe1: # pdfMerger.append(fe1) # with open("temp.pdf", 'rb') as fe2: # pdfMerger.append(fe2) # with open("result.pdf", 'ab+') as fe3: # pdfMerger.write(fe3) pdfFileReader = PdfFileReader(open("temp.pdf", 'rb')) pdfFileWriter = PdfFileWriter() if (os.path.exists(BASE_DIR + "\\result.pdf")): pdfFileReader0 = PdfFileReader(open("result.pdf", 'rb')) for page in range(pdfFileReader0.getNumPages()): # 将每页添加到writer对象 pdfFileWriter.addPage(pdfFileReader0.getPage(page)) pageObj = pdfFileReader.getPage(0) pdfFileWriter.addPage(pageObj) pdfFileWriter.write(open("result.pdf", 'ab+'))
def save_pdf_from_htmlfile(): """ 把所有html文件转换成pdf文件 """ options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.45in', 'margin-bottom': '0.75in', 'margin-left': '0.45in', 'encoding': "UTF-8", 'custom-header': [('Accept-Encoding', 'gzip')], 'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'outline-depth': 10, } path_wk = "C:\\soft\\Python27\\wkhtmltopdf\\bin\\wkhtmltopdf.exe" config = pdfkit.configuration(wkhtmltopdf=path_wk) count = 0 for root, dir, filenames in os.walk(dir_save_html): for filename in filenames: filename = filename.decode('gb2312').encode('utf8') save_pdf_filename = dir_save_pdf + filename.rstrip( ".html") + ".pdf" html_name = root + filename pdfkit.from_file(html_name, save_pdf_filename, options=options, configuration=config) count += 1
def pass_testing(request): stime = datetime.now() template = loader.get_template('big_brother/pdf.html') pass_id = 17 try: car_pass = Car_passes.objects.get(id=pass_id) except Car_passes.DoesNotExist: car_pass = '******' context = { 'pass_id': car_pass.id, 'company_name': car_pass.company_id.org_name, 'brand': car_pass.car_id.brand, 'model': car_pass.car_id.model, 'license_plate': car_pass.car_id.license_plate, 'qr': qr_gen(BASE_URL, 17) } html = template.render(context, request) options = { 'page-size': 'A5', 'margin-top': '1cm', 'margin-right': '1cm', 'margin-bottom': '1cm', 'margin-left': '1cm', 'encoding': "UTF-8", 'zoom': 1.25, 'custom-header': [('Accept-Encoding', 'gzip')], 'no-outline': None } path_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf) pdf = pdfkit.from_string(html, 'out.pdf', options=options, configuration=config) with open('out.pdf', 'rb') as file_pdf: response = HttpResponse(file_pdf, content_type='application/pdf') response['Content-Disposition'] = 'filename="home_page.pdf"' time_delta = datetime.now() - stime print(f'Время генерации PDF = {time_delta}') return response
def CompleteSchedule(self): gfile = os.getcwd() + r'\HTML\Schedule.html' g = open(gfile, 'w') WritePreambleHTML(g, 1, Full=False, Leaguename=self.Leaguename, BCenter=self.BCenter, dates=self.dates, lanes=self.lanes) SchedDataNum = [ self.SchedulePrint(week, 'Num')[0] for week in range(1, self.weeklen + 1) ] SchedDataNam = [ self.SchedulePrint(week, 'Name')[0] for week in range(1, self.weeklen + 1) ] g.write('<h2 id="Schedule-by-id">Schedule by ID</h2>\n') WriteHTML(g, SchedDataNum, self.SchedNumP, cls='idtable') g.write('<h2 id="Schedule-by-name">Schedule by Name</h2>\n') WriteHTML(g, SchedDataNam, self.SchedNamP, cls='boldtable') g.write('</div>\n</div>\n</div>\n</body>\n</html>') g.close() # Configure the html to pdf software. config = pdfkit.configuration(wkhtmltopdf=bytes( r'C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe', 'utf-8')) path = r'C:\Users\Chris\Documents\League\Three Way\HTML\css\\' css = [path + 'skeletonpdf.css'] options = { 'margin-top': '0in', 'margin-right': '0in', 'margin-bottom': '0in', 'margin-left': '0in' } pdfkit.from_file(gfile, os.getcwd() + r'\HTML\Schedule.pdf', configuration=config, css=css, options=options)
def save_to_pdf(self,str_input,output,orientation,title='Sans Titre'): options = { 'page-size':'A4', 'margin-top':'0cm', 'margin-right':'0cm', 'margin-bottom':'0cm', 'margin-left':'0cm', 'orientation':orientation, 'print-media-type':'', 'title':title, } inclu_folder = CD_REPORT_DEF+"/static/lib/inclu/" css = [inclu_folder + 'style_zone_text.css', inclu_folder + 'global_style.css', inclu_folder + 'style_portrait.css'] str_input = str_input.replace("../inclu/jquery.js",inclu_folder+"jquery.js") str_input = str_input.replace("../inclu/etat_script.js",inclu_folder+"etat_script.js") config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf') pdf_result = pdfkit.from_string(str_input,output,options=options,css=css,configuration=config) return pdf_result
def make_pdf_from_url(url, name): """ PDFにしたいサイトのurlと保存したいファイル名を引数に持ってきて pathで指定された場所に保存 """ UPLOAD_DIR = os.path.dirname('/'.join( os.path.abspath(__file__).split('/') [0:-1])) + '/media/' # アップロードしたファイルを保存するディレクトリ options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8", 'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'no-outline': None, 'disable-javascript': None } make_date = upload_date(datetime.now().strftime('%Y%m%d')) path = os.path.join(UPLOAD_DIR + '/' + make_date, name + '.pdf') config_path = '/usr/local/bin/wkhtmltopdf' config = pdfkit.configuration(wkhtmltopdf=config_path) pdfkit.from_url(url, path, configuration=config, options=options) return path
def write_pdf(path, name): try: options = { "--margin-left": "3", #default is 10 = 14 mm "--margin-right": "3", #default is 10 "--margin-top": "3", #default is 10 42.9 "--margin-bottom": "3", "--orientation": "portrait" } input_ = os.path.join(path, name + '.html') if not os.path.exists(input_): raise Exception('''Report in html %s not present''' % input_) output_ = os.path.join(path, name + '.pdf') config = pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF) pdfkit.from_file(input_, output_, options=options, configuration=config) except Exception, e: raise Exception( '''Report in pdf for %s was not generated due to problems in the write_pdf function. Error: %s''' % (path, e))
def generate_pdf(title, content): pdfkit_config = pdfkit.configuration(wkhtmltopdf=settings.WKHTMLTOPDF_CMD) wk_options = { "page-size": "a4", "orientation": "landscape", "title": title, # In order to specify command-line options that are simple toggles # using this dict format, we give the option the value None "no-outline": None, "disable-javascript": None, "encoding": "UTF-8", "margin-left": "0.2cm", "margin-right": "0.2cm", "margin-top": "0.3cm", "margin-bottom": "0.3cm", "lowquality": None, } return pdfkit.from_string(content, False, options=wk_options, configuration=pdfkit_config )
def process_article(id, words_min, searchword, keywords, begin_time): url = "http://www.woshipm.com/pd/" + id + ".html" header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36' } try: request = urllib.request.Request(url, headers=header) response = urllib.request.urlopen(request).read() result = response.decode('utf-8', 'ignore').replace(u'\xa9', u'') except: print('error: page not found.') return soup = BeautifulSoup(result, features="html.parser") # 获取纯文本信息raw_txt # content = str(soup.find_all(class_="article--content grap")) # re_words = re.compile(u"[\u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b\u4e00-\u9fa5]+") # txt = re.findall(re_words, content) # raw_txt = "".join(txt) txt = soup.find(class_="article--content grap").find_all('p') raw_txt = "" for t in txt: raw_txt += t.text if len(raw_txt) >= words_min: # 判断文本长度 # 获取json信息 conti = form_json(id, soup, raw_txt, searchword, begin_time) if conti == False: return False calc_keywords(raw_txt, keywords) # 转换pdf print("Word count: ", len(raw_txt)) print("Downloading article #" + id + ' ' + url) # print("content:", raw_txt) path = searchword + "/" + id + '.pdf' config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf') pdfkit.from_url(url, path, configuration=config) # print(result) return True
def exportPDF_filter(self): """Exports the current Pandas Dataframe (after merges and modifications) as a PDF File""" dateTimeFormat = time.strftime( "%Y%m%d-%H%M%S") # Date and Time Format (YYYYMMDD-HHMMSS) config = pdf.configuration( wkhtmltopdf="wkhtmltopdf\\bin\\wkhtmltopdf.exe" ) # where the config file is located at try: if self.view.empty: raise ValueError("There is no search data!") else: self.view.to_html('exportPDF_filter.html') pdfFileName = 'tablePDF_filter-' + dateTimeFormat + ".pdf" # name file of the filter pdf file pdf.from_file( 'exportPDF_filter.html', pdfFileName, configuration=config) # convert html to filter pdf file os.remove('exportPDF_filter.html') # delete the html file mod.successGUI() # prompt file downloaded except Exception as e: mod.errorGUI(str(e))
def run(self): start = time.time() options = { 'page-size': 'Letter', 'image-dpi': 1500, '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.request(self.start_url))): log.info(url) html = self.parse_body(self.request(url)) f_name = ".".join([str(index), "html"]) with open(file + f_name, 'wb') as f: f.write(html) htmls.append(file + f_name) try: config = pdfkit.configuration( wkhtmltopdf=r"D:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe") pdfkit.from_file(htmls, self.name + ".pdf", options=options, configuration=config) except: log.error("生成错误", exc_info=True) for html in htmls: os.remove(html) total_time = time.time() - start print(u"总共耗时:%f 秒" % total_time)
def download_analytics(request): template = 'reports/report_analytics_summary.html' data_from = request.GET.get('from') data_to = request.GET.get('to') messages = [] successfull = True reports = Reports.objects.filter(data__today__range=[data_from, data_to]) data = { 'district_level': getDistrictLevel(reports), 'block_level': getBlockLevel(reports), 'cluster_level': getClusterLevel(reports), 'top_summary': getTopSummary(reports), 'by_user': getByReportType(reports) } html = render_to_string(template, {'data': data}) config = pdfkit.configuration() pdf = pdfkit.PDFKit(html, 'string', configuration=config).to_pdf() response = HttpResponse(pdf, content_type="application/pdf") response[ 'Content-Disposition'] = 'inline; filename=' + 'REPORTANALYTICS.pdf' return response
def generate_pdf(): path_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf) options = { 'page-size': 'A4', 'dpi': 400, "enable-local-file-access": "", "encoding": "UTF-8", "footer-right": "[page]" } more_stories_filename = "GoogleCovid-19MoreStories.html" numbers_filename = "GoogleCovid-19Numbers.html" search_loc_li = ['Pune', 'Kolkata', 'Bangalore'] for loc in search_loc_li: html_filename = 'GoogleCovid-19NewsLetter_' + loc + '.html' pdf_filename = 'COVID-19NewsLetter_' + loc + '.pdf' pdfkit.from_file( [html_filename, numbers_filename, more_stories_filename], pdf_filename, configuration=config, options=options) print('Completed execution of Covid-19 News PDF')
def pdf_gen(car_pass, request): # print('pdf_gen begin') # template = loader.get_template('big_brother/pdf.html') # context = {'pass_id': car_pass.id, # 'company_name': car_pass.company_id.org_name, # 'brand': car_pass.car_id.brand, # 'model': car_pass.car_id.model, # 'license_plate': car_pass.car_id.license_plate, # 'qr': qr_gen(BASE_URL, car_pass.id)} # html = template.render(context, request) # pdf = HTML(string=html).write_pdf() template = loader.get_template('big_brother/pdf.html') try: car_pass = Car_passes.objects.get(id=car_pass.id) except Car_passes.DoesNotExist: car_pass = '******' context = { 'pass_id': car_pass.id, 'company_name': car_pass.company_id.org_name, 'brand': car_pass.car_id.brand, 'model': car_pass.car_id.model, 'license_plate': car_pass.car_id.license_plate, 'qr': qr_gen(BASE_URL, car_pass.id) } html = template.render(context, request) options = { 'page-size': 'A5', 'margin-top': '1cm', 'margin-right': '1cm', 'margin-bottom': '1cm', 'margin-left': '1cm', 'encoding': "UTF-8", 'zoom': 1.25, 'custom-header': [('Accept-Encoding', 'gzip')], 'no-outline': None } path_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf) pdfkit.from_string(html, 'out.pdf', options=options, configuration=config)
def plot_templates(): print('\n Draw bar graph of the number of movies by year since 1900') imdb_df = pd.read_csv('data/imdb.csv', header=0, converters={ 'rating': float, 'num_votes': int, 'year': int }) imdb_df.drop(['title', 'rating', 'num_votes'], axis=1, inplace=True) gb = imdb_df.groupby(['year'])['year'].count() movies = gb.to_dict() draw_barplot(values=movies, svg_file='images/bar-template.html', title='Number of movies per year.', x_label='Year', y_label='Number of movies') path_pdf = 'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_pdf) pdfkit.from_file('images/bar-template.html', 'images/bar-template.pdf', configuration=config)
def render_to_pdf(request, html, footer_file): wkhtmltopdfpath = request.config.get( "wkhtmltopdfpath", r"c:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe" ) config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdfpath) if isinstance(html, bytes): html = html.decode("utf-8") return pdfkit.from_string( html, False, configuration=config, options={ "footer-html": footer_file, "margin-bottom": request.viewdata.dom.PDFBottomMargin, "page-size": "letter", "disable-javascript": None, "print-media-type": None, "quiet": None, "load-error-handling": "ignore", "load-media-error-handling": "ignore", }, )
def create_offset_page(output_file, pdf_maker): """ Create pdf files from plain text or HTML text. output_file : File path to the offset pdf file for both-side printout pdf_maker : Path to wkhtmltopdf.exe """ if (not exists(pdf_maker)): print("Invalid path to wkhtmltopdf.exe, please check") return print("Creating pages for both-sides printout adjustment ...") config = pdfkit.configuration(wkhtmltopdf=pdf_maker) contents = """.""" options = { 'page-size': 'A4', 'margin-top': '0.001', 'margin-left': '0.001', 'encoding': "UTF-8", } pdfkit.from_string(contents, output_file, configuration=config, options=options)
def decrypt(self): try: title, decrypted_html = decrypt_html(self.filename, self.password_edit.text()) except UnicodeDecodeError as e: show_message(e) return title = title.replace(' ', '_') output_path = self.output_directory.text() if self.pdf_check.isChecked(): new_file_name = f"{output_path}/{title}.pdf" print("filename : " + new_file_name) path_wkhtmltopdf = shutil.which('wkhtmltopdf') if not path_wkhtmltopdf: show_message( f"not found wkhtmltopdf.\ninstall wkhtmltopdf : https://wkhtmltopdf.org/downloads.html" ) return config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf) try: result = convert_pdf(decrypted_html, new_file_name, config=config) except IOError as e: show_message(e) return if result: print("pdf converted") self.show_converted_dialog('pdf') else: basename, ext = os.path.splitext(self.filename) new_file_name = f"{output_path}/{title}{ext}" convert_html(decrypted_html, new_file_name) self.show_converted_dialog('html')
class VoiceForm: config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf') sender_address = '*****@*****.**' sender_pass = '******' def __init__(self): print("") def generatePDF(self, form): path = './voiceforms/' + form['email'] + '.pdf' rendered = render_template('pdf_template.html', form=form) pdfkit.from_string(rendered, path, configuration=self.__class__.config) return path def sendEmail(self, reciever_address, attach_file_name): message = MIMEMultipart() message['From'] = self.__class__.sender_address message['To'] = reciever_address message['Subject'] = 'A copy of your voice form response.' mail_content = """ This is a copy of your response form generated by our App. """ message.attach(MIMEText(mail_content, 'plain')) attach_file = open(attach_file_name, 'rb') payload = MIMEBase('application', 'octate-stream') payload.set_payload((attach_file).read()) encoders.encode_base64(payload) payload.add_header('Content-Disposition', 'attachment; filename="%s.pdf"' % reciever_address) message.attach(payload) session = smtplib.SMTP('smtp.gmail.com', 587) session.starttls() session.login(self.__class__.sender_address, self.__class__.sender_pass) text = message.as_string() session.sendmail(self.__class__.sender_address, reciever_address, text) session.quit() print('Mail Sent')
def generate_receipts(self, command=False): if command: return "Generate Receipt" client = self.order.get_client() if client != 0: client = self.clients[client] else: client = False env = Environment(loader=FileSystemLoader('Templates')) template = env.get_template('jinja_receipt.html') output_from_parsed_template = template.render(order=self.order, owner=self.owner, client=client) path_wkthmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) pdfkit.from_string(output_from_parsed_template, "out.pdf", configuration=config, options={'quiet': ''})
def generatePDF(): if request.method == 'POST': if not is_input_json(request, ['idTransactions']): return jsonify({"msg": "Missing or bad JSON in request."}), 400 if not isinstance(request.json['idTransactions'], int): return jsonify({"msg": "Transaction id must be a number."}), 400 idTrans = request.json['idTransactions'] # sprawdzanie czy transakcja należy do konta zalogowanego użytkownika if not is_account_of_transaction(idTrans): return jsonify({"msg": "Access restricted."}), 400 infoTrans = get_info_about_transcation(idTrans, '') # generowanie PDF config = pdfkit.configuration( wkhtmltopdf='/opt/wkhtmltopdf/bin/wkhtmltopdf') rendered = render_template( 'pdf_template.html', idTransactions=idTrans, idAccounts=idAccount_to_account_number(infoTrans[0]), idAccountsOfRecipient=idAccount_to_account_number(infoTrans[1]), amountOfTransaction=infoTrans[2], date=infoTrans[3], old_balance=infoTrans[4], new_balance=infoTrans[5], message=infoTrans[6]) pdf = pdfkit.from_string(rendered, False, configuration=config) response = make_response(pdf) response.headers['Content-Type'] = 'application/pdf' response.headers[ 'Content-Disposition'] = 'inline; filename=receipt-' + str( idTrans) + '.pdf' return response
def convertNotesToPdf(notesList, fname): merger = PdfFileMerger() output = PdfFileWriter() for i in range(0, len(notesList), 3): html = _setupTable() for image, notes in notesList[i:i + 3 if i + 3 < len(notesList) else len(notesList)]: html += _addTableRow(image, notes) html += _finishTable() config = pdfkit.configuration( wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe') pdfBytes = pdfkit.from_string(html, False, configuration=config) pdfByteStream = io.BytesIO(pdfBytes) pfr = PdfFileReader(pdfByteStream) output.addPage(pfr.getPage(0)) outputStream = open(fname, "wb") output.write(outputStream) outputStream.close() print("Finished saving PDF")
def send_report(self): result = False reportName = 'I3 Assessment Report - %s.pdf' % self.group_name responses = [[r.question_1, r.question_2, r.question_3] for r in SurveyResponse.objects.filter(survey=self.id, submitted=True)] requesterName = "%s %s" % (self.requester.first_name, self.requester.last_name) if len(responses) >= MIN_RESPONSES: rating, score = get_rating(responses) for i in range(MAX_REPORT_ATTEMPTS): try: srMaker = SurveyReportMaker(responses, requesterName, rating) srMaker.make_plots() htmlReport = srMaker.make_html_page(os.path.join(os.getcwd(), "static/insight/img/innovation_company_logo.png")) pdf = srMaker.write_to_pdf(htmlReport, config=pdfkit.configuration(wkhtmltopdf="../.local/bin/wkhtmltox/bin/wkhtmltopdf")) text_content = render_to_string('main/email_report_body.html', {'name': self.requester.first_name}) message = EmailMessage(subject="Your I3™ Assessment Report from The Innovation Company", body=text_content, to=(self.requester.email,)) message.attach(reportName, pdf, 'application/pdf') message.send() # Send email to [email protected] notifying of report generation, including a copy message.subject = 'A report has been emailed to {} {}'.format(self.requester.first_name, self.requester.last_name) message.to = ['*****@*****.**'] message.from_email = '*****@*****.**' message.send() result = True break except Exception as e: logger.error("FAILED TO CREATE REPORT: %s" % e) if i >= MAX_REPORT_ATTEMPTS - 1: send_mail(subject="FAILED TO CREATE REPORT %s TIMES" % MAX_REPORT_ATTEMPTS, message="There was an issue trying to create a report:\n\n%s" % e, from_email='*****@*****.**', recipient_list=["*****@*****.**"]) else: sleep((i + 1) * 120) return result
def downloadpdf(): edu = education.query.filter_by(edu=current_user).all() exp = experience.query.filter_by(exp=current_user).all() pro = projects.query.filter_by(pro=current_user).all() usr = userdetails.query.filter_by(details=current_user).first() skillsadded = skills.query.filter_by(skill=current_user).all() achmade = achievements.query.filter_by(ach=current_user).all() image_file = url_for('static', filename='profiles/' + current_user.image_file) css = ["resume/static/resume.css", "resume/static/main.css"] rendered = render_template("resume.html", edu=edu, exp=exp, pro=pro, usr=usr, sk=skillsadded, achmade=achmade, image_file=image_file) config = pdfkit.configuration(wkhtmltopdf=path_to_wkhtmltopdf) options = { 'page-size': 'A4', 'dpi': 400, 'disable-smart-shrinking': '', 'enable-local-file-access': '' } pdf = pdfkit.from_string(rendered, False, css=css, configuration=config, options=options) response = make_response(pdf) response.headers["Content-Type"] = "application/pdf" response.headers[ "Content-Disposition"] = "attachment; filename=download.pdf" return response
def __init__(self, *, outputPath: str = './'): wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' self.config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf) self.options = { 'orientation': 'Portrait', # notice 'page-size': 'A4', 'margin-top': '1.0in', 'margin-right': '0.1in', 'margin-left': '0.1in', 'margin-bottom': '1.0in', 'encoding': 'UTF-8', 'no-outline': None, 'header-right': '[date] [time]', 'footer-center': ' [page]/[topage]', # '1/3' 2020-10-09 'enable-local-file-access': None, # orz ... } self.outputPath = pathlib.Path(outputPath) self.isReady = True if self.outputPath.exists() is False or self.outputPath.is_dir( ) is False: self.isReady = False logger.error('no outputPath %s' % (self.outputPath))
def conv_to_pdf(path, nome_pdf): # print(path) se2lib = BuiltIn().get_library_instance('Selenium2Library') # return se2lib._current_browser() # s = Selenium2Library.Selenium2Library() url = se2lib.get_location() print(url) options = { 'quiet': '', 'enable-local-file-access': None, 'encoding': 'UTF-8', 'load-error-handling': 'ignore', 'load-media-error-handling': 'ignore', } # pdfkit.from_url(path, nome_pdf) path_wkthmltopdf = b'C:\Program Files\wkhtmltopdf\\bin\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) # config = pdfkit.configuration(wkhtmltopdf=bytes(path_wkthmltopdf, 'utf8')) pdfkit.from_string(path, nome_pdf, configuration=config, options=options)
def CompleteSchedule(self): gfile = os.getcwd()+r'\HTML\Schedule.html' g = open(gfile, 'w') WritePreambleHTML(g, 1, Full=False, Leaguename=self.Leaguename, BCenter=self.BCenter, dates=self.dates, lanes=self.lanes) SchedDataNum = [self.SchedulePrint(week, 'Num')[0] for week in range(1, self.weeklen + 1)] SchedDataNam = [self.SchedulePrint(week, 'Name')[0] for week in range(1, self.weeklen + 1)] g.write('<h2 id="Schedule-by-id">Schedule by ID</h2>\n') WriteHTML(g, SchedDataNum, self.SchedNumP, cls='idtable') g.write('<h2 id="Schedule-by-name">Schedule by Name</h2>\n') WriteHTML(g, SchedDataNam, self.SchedNamP, cls='boldtable') g.write('</div>\n</div>\n</div>\n</body>\n</html>') g.close() # Configure the html to pdf software. config = pdfkit.configuration(wkhtmltopdf=bytes(r'C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe', 'utf-8')) path = r'C:\Users\Chris\Documents\League\Three Way\HTML\css\\' css = [path + 'skeletonpdf.css'] options = {'margin-top': '0in', 'margin-right': '0in', 'margin-bottom': '0in', 'margin-left': '0in'} pdfkit.from_file(gfile, os.getcwd()+r'\HTML\Schedule.pdf', configuration = config, css = css, options = options)
#!/usr/bin/env python3.4 # -*- coding: utf-8 -*- import cgi import pdfkit form = cgi.FieldStorage() content = form.getfirst('content', 'null') render_type = form.getfirst('renderType') config = pdfkit.configuration(wkhtmltopdf=bytes('/usr/bin/wkhtmltopdf', 'utf-8')) if render_type == 'string': pdfkit.from_string(content, 'export.pdf', configuration=config) elif render_type == 'url': pdfkit.from_url(content, 'export.pdf', configuration=config) print('Content-Type:', 'text/html', '\r\n') print('<a href="/export.pdf">export.pdf</a>')
def pdf(): config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf') doc = handle_request(config) return Response(doc, mimetype='application/pdf')
def download(): config = pdfkit.configuration(wkhtmltopdf=os.environ['WKHTMLTOPDF_PATH']) output_name = str(request.args.get('output_name')) url = str(urllib.unquote(request.args.get('url').decode('utf8'))) pdf = pdfkit.from_url(url, output_name, configuration=config) return send_file(output_name, as_attachment=True, mimetype='application/pdf')
def callservice(conn, schemaname, servicename, querystring): try: t1 = datetime.datetime.now() # log the request - not enabled at the moment because of permission issues # logging.basicConfig(filename='/srv/www/dopa-services/cgi-bin/logs/REST_Services_Log.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s',) # logging.info("REST REQUEST: " + web.ctx.home + web.ctx.path + web.ctx.query) # PARSE THE STANDARD OPTIONAL INPUT PARAMETERS # get the input parameters params = getQueryStringParams(querystring) # the unquoting is to handle encoded parameters (like from extJS - 1,2,3 as a parameter becomes 1%2C2%2C3 # get the standard optional parameters from the url format = params.setdefault('format', 'json') fields = params.setdefault('fields', '').split(",") # fields will be passed as an array, e.g. iucn_species_id,wdpa_id includemetadata = params.setdefault('includemetadata', 'true') metadataName = params.setdefault('metadataname', 'metadata') rootName = params.setdefault('rootname', 'records') parseparams = params.setdefault('parseparams', 'true') sortField = params.setdefault('sortfield', '') decimalPlaceLimit = params.setdefault('dplimit', '2') isHadoop = ('true' if (servicename[-2:] == '_h') else 'false') # if the service is a call to a hadoop method then set a flag # remove the standard optional parameters from the dictionary so we are left with just the parameters required for the function del (params['format'], params['fields'], params['includemetadata'], params['parseparams'], params['metadataname'], params['rootname'], params['sortfield'], params['dplimit']) if 'callback' in params.keys(): del(params['callback']) # check if the service name is valid if not (isValidServiceName(servicename)): raise RESTServicesError('Invalid servicename') # authorise with ecas if needed # if requiresAuthentication(servicename): # if isAuthenticated() == False: # web.ctx.status = '401 Unauthorized' # web.header("Content-Type", "text/html") # return "<html><head></html><body><h1>Authentication required</h1></body></html>" # if it is a Hadoop query then we need to run if first before we actually use the values to get the data from postgresql if (isHadoop.lower() == 'true'): hadoopData = runHadoopQuery(conn, servicename, params) if hadoopData == '[]': hadoopData = '[-1]' servicename = "_" + servicename # now call the postgresql function params.clear() params['species_ids'] = str(hadoopData)[1:-1]; # PARSE AND CONVERT THE DATA TYPES OF THE OTHER INPUT PARAMETERS # get all the parameters for the function from postgresql conn.cur.callproc('utils.dopa_rest_getparams', [servicename]) # get the function parameters as a string and split this into a list, e.g. wdpa_id integer, presence_id integer[] --> ['wdpa_id integer', ' presence_id integer[]'] functionparams = conn.cur.fetchone() hasparams = True if functionparams[0] else False if hasparams: functionparams = functionparams[0].split(',') # get the names of the function parameters which are array types arrayparamnames = [p.strip().split(" ")[0] for p in functionparams if '[' in p] # convert the array values into lists for key in params.keys(): if key in arrayparamnames: strlist = params[key].split(",") isnum = isNumeric(strlist[0]) if isnum: params[key] = [int(s) for s in strlist] else: params[key] = strlist # get the full list of function parameter names functionparamnames = [p.strip().split(" ")[0] for p in functionparams] # check that all parameters are correct invalidparamnames = [n for n in params.keys() if n not in functionparamnames] if invalidparamnames and parseparams == 'true': raise RESTServicesError('Invalid parameters: ' + ",".join(invalidparamnames)) # put the input parameters in the right order params = OrderedDict([(n, params[n]) for n in functionparamnames if n in params.keys()]) # GET THE SORT CLAUSE if sortField != "": sortClause = ' ORDER BY "' + sortField + '"' else: sortClause = "" # GET THE FIELDS CLAUSE if fields != ['']: fieldsClause = ",".join(fields) else: fieldsClause = "*" # RUN THE QUERY if hasparams : sql = "SELECT " + fieldsClause + " from " + schemaname + "." + servicename + "(" + ",".join([n + ":=%(" + n + ")s" for n in params]) + ")" + sortClause + ";" # run the query using named parameters conn.cur.execute(sql, params) else: sql = "SELECT * from " + schemaname + "." + servicename + "()" + sortClause + ";" conn.cur.execute(sql) rows = conn.cur.fetchall() # PROCESS THE ROWS AND WRITE THEM BACK TO THE CLIENT conn.cur.close() t2 = datetime.datetime.now() # METADATA SECTION OF RESPONSE allfields = [d.name for d in conn.cur.description] if (fields == ['']): fields = allfields fieldcount = len(fields) fieldsdict = [dict([("name", d.name), ("type", gettypefromtypecode(d.type_code))]) for d in conn.cur.description if (d.name in fields)] if len(fieldsdict) != len(fields): raise RESTServicesError('Invalid output fields') metadatadict = OrderedDict([("duration", str(t2 - t1)), ("error", None), ("idProperty", conn.cur.description[0].name), ("successProperty", 'success'), ("totalProperty", 'recordCount'), ("success", True), ("recordCount", int(conn.cur.rowcount)), ("root", rootName), ("fields", fieldsdict)]) # RECORDS SECTION OF THE RESPONSE # parse the float values and set the correct number of decimal places according to the decimalPlaceLimit variable - dont include lat/long fields as these must have more decimal places floatColumns = [i for i, d in enumerate(fieldsdict) if d['type'] == 'float' and d['name'] not in ['lat', 'lng']] if len(floatColumns) > 0: for floatColumn in floatColumns: for row in rows: if type(row[floatColumn]) != NoneType: # check that the data is not null row[floatColumn] = round(row[floatColumn], int(decimalPlaceLimit)) # return the data colsRequired = [allfields.index(field) for field in fields] if format in ['json', 'array']: if format == 'json': recordsdict = [OrderedDict([(allfields[col], row[col]) for col in range(fieldcount) if (col in colsRequired)]) for row in rows] else: recordsdict = [[row[col] for col in range(fieldcount) if (col in colsRequired)] for row in rows] json.encoder.FLOAT_REPR = lambda f: ("%.14g" % f) # this specifies how many decimal places are returned in the json with float values - currently set to 14 - good enough for returning lat/long coordinates if (includemetadata.lower() == 'true'): responsejson = json.dumps(dict([(metadataName, metadatadict), (rootName, recordsdict)]), indent=1, cls=CustomJSONEncoder) else: responsejson = json.dumps(dict([(rootName, recordsdict)]), indent=1, cls=CustomJSONEncoder) return getJsonResponse(responsejson) elif format in ['xml', 'xmlverbose']: root = etree.Element('results') recordsnode = etree.Element(rootName) recordsdicts = [OrderedDict([(allfields[col], str(row[col]).decode('utf-8')) for col in range(fieldcount) if (col in colsRequired) and str(row[col]) != 'None']) for row in rows ] # if format == 'xml': recordselements = [etree.Element('record', element) for element in recordsdicts] for recordelement in recordselements: recordsnode.append(recordelement) else: for recordelement in recordsdicts: record = etree.Element('record') for (n, v) in recordelement.items(): el = etree.Element(n) el.text = v record.append(el) recordsnode.append(record) root.append(recordsnode) web.header("Content-Type", "text/xml") # web.header("Content-Type", "application/Excel") # doesnt work! # web.header("Content-Disposition", "attachment; filename=test.xml") return etree.tostring(root) elif format == 'sms': _twilio = twilio() client = TwilioRestClient(_twilio.twilio_account_sid, _twilio.twilio_auth_token) # use the twilio api account bodystr = 'Hi Andrew - test species data: ' bodystr = bodystr + str(rows[0])[:160 - len(bodystr)] message = client.sms.messages.create(to="+393668084920", from_="+19712647662", body=bodystr) # my mobile return message elif format == 'email': _amazon_ses = amazon_ses() amazonSes = AmazonSES(_amazon_ses.AccessKeyID, _amazon_ses.SecretAccessKey) # use the amazon simple email service api account message = EmailMessage() message.subject = 'JRC REST Services Information Request' message.bodyHtml = getResultsAsHTML(rows, fieldcount, colsRequired, metadatadict) result = amazonSes.sendEmail('*****@*****.**', '*****@*****.**', message) # to me return result elif format == 'html': htmlData = getResultsAsHTML(rows, fieldcount, colsRequired, metadatadict) web.header("Content-Type", "text/html") return "<html><head></head><body>" + htmlData + "</body></html>" elif format == 'csv': data = [[row[col] for col in range(fieldcount) if (col in colsRequired)] for row in rows] colnames = ",".join([f["name"] for f in metadatadict["fields"]]) + "\n" output = colnames + "\n".join([p for p in [",".join(h) for h in [[getStringValue(col) for col in row] for row in data]]]) filename = "dataDownload.csv" #hardcoded for now f = open(r'/tmp/' + filename, 'wb') f.write(output) f.close() web.header("Content-Type", "text/plain") web.header("Content-Disposition", "attachment; filename=%s" % filename) return output elif format == 'pdf': config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf') web.header("Content-Type", "application/pdf") htmlData = getResultsAsHTML(rows, fieldcount, colsRequired, metadatadict) return pdfkit.from_string(htmlData.decode('utf8'), False, configuration=config, options={'quiet': '', 'encoding': "UTF-8"}) else: raise RESTServicesError('Invalid response format: ' + format) except (RESTServicesError, DataError, ProgrammingError, exceptions.TypeError, IndexError, IntegrityError, AmazonError, OperationalError) as e: # web.webapi.internalerror() #returns a internal server error 500 t2 = datetime.datetime.now() msg = "There was an error sending the email. Make sure that the email address has been verified in Amazon Simple Email Services" if type(e) == AmazonError else e.message logging.error(msg + "\n") if type(e) == ProgrammingError: if ("column" in e.message) & ("does not exist" in e.message) & (sortField != ""): msg = "Invalid sortfield parameter: " + sortField return returnError(metadataName, rootName, t2 - t1, msg)
import StringIO from django import http from django.conf import settings from django.views.generic import View from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import TemplateDoesNotExist from django.views.generic.base import TemplateResponseMixin import pdfkit settings.configure() #: I use this during sphinx document generation path_wkthmltopdf = getattr( settings, "WKTHMLTOPDF_PATH", "/usr/local/bin/wkhtmltox/bin/wkhtmltopdf") config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) class GeneratePDF: """PDF generator""" data = [] pdf_options = {"quiet": ""} connection = None pdf = None filename = None def __init__(self, template="account_statement.html"): self.template = get_template("sendpdf/docs/{}".format(template)) def _make_pdf(self, ctxt, filename="page"): self.filename = filename
def async_custom_pdf_report(self, report=None, template="None", filename='report.pdf', host=None, user=None, uri=None, finding_notes=False, finding_images=False): config = pdfkit.configuration(wkhtmltopdf=settings.WKHTMLTOPDF_PATH) selected_widgets = report_widget_factory(json_data=report.options, request=None, user=user, finding_notes=finding_notes, finding_images=finding_images, host=host) widgets = selected_widgets.values() temp = None try: report.task_id = async_custom_pdf_report.request.id report.save() toc = None toc_depth = 4 if 'table-of-contents' in selected_widgets: xsl_style_sheet_tempalte = "dojo/pdf_toc.xsl" temp = tempfile.NamedTemporaryFile() toc_settings = selected_widgets['table-of-contents'] toc_depth = toc_settings.depth toc_bytes = render_to_string(xsl_style_sheet_tempalte, {'widgets': widgets, 'depth': toc_depth, 'title': toc_settings.title}) temp.write(toc_bytes) temp.seek(0) toc = {'toc-header-text': toc_settings.title, 'xsl-style-sheet': temp.name} cover = None if 'cover-page' in selected_widgets: cp = selected_widgets['cover-page'] x = urlencode({'title': cp.title, 'subtitle': cp.sub_heading, 'info': cp.meta_info}) cover = host + reverse( 'report_cover_page') + "?" + x bytes = render_to_string(template, {'widgets': widgets, 'toc_depth': toc_depth, 'host': host, 'report_name': report.name}) pdf = pdfkit.from_string(bytes, False, configuration=config, cover=cover, toc=toc, ) if report.file.name: with open(report.file.path, 'w') as f: f.write(pdf) f.close() else: f = ContentFile(pdf) report.file.save(filename, f) report.status = 'success' report.done_datetime = datetime.now(tz=localtz) report.save() # email_requester(report, uri) except Exception as e: report.status = 'error' report.save() # email_requester(report, uri, error=e) raise e finally: if temp is not None: # deleting temp xsl file temp.close() return True
def HTMLStatistics(DB, League): path = r"C:\Users\Chris\Documents\League\Three Way\HTML\css\\" for P in DB.Players: # Get the player's first name (assume unique for now) F = "_".join(P.Name.title().split()) hfile = os.getcwd() + "/HTML/Stats_{0}.html".format(F) h = open(hfile, "w") WritePreambleHTML( h, F, Full=False, Script=False, Leaguename=League.Leaguename, BCenter=League.BCenter, dates=League.dates, lanes=League.lanes, header=False, ) Span = [2] * 9 Span.append(3) # Span.extend([3,3]) Head = list(range(1, 11)) # Head.append('Total') LastDate = "" # Extract dates for table of contents Dates = [] for G in P.Games: if G.Meta[2].date() in Dates: continue Dates.append(G.Meta[2].date()) # Add navigation to the page. h.write( '<div class="container">\n<div class="rTable">\n<div class="rTableRow">\n<div class="rTableCell" width = "50%">\n' ) h.write("<h4>Pin Position Game Stats for {0}</h4>\n".format(P.Name.title())) h.write( "Orange background denotes open frames, Red background denotes splits. Pin position details for each game can be found by clicking on the frame scores. These results will be progressively improved over the season." ) h.write('</div>\n<div class="rTableCell" width = "50%">\n') h.write("<h4>On this page</h4>\n<ol>\n") h.write('<li><a href="#Comparison">Detailed League Statistics</a></li>\n') h.write('<li><a href="#Common">Spare Effectiveness by Combination Left</a></li>\n') for Date in Dates: h.write( '<li><a href="#{0}">{1}{0}</a></li>\n'.format( custom_strftime("{S} of %B, %Y", Date), "Series bowled on " ) ) h.write("</ol>\n") h.write("</div>\n</div>\n</div>\n</div>\n") # Section comparing bowler to others Head_Comp = [ "Name", "Games", "200 Games", "Average", "High Game", "Spare %", "Strike %", "Open %", "Split %", "Splits Converted %", "Single Pins Missed %", "Error %", ] Text = [] for Pl in DB.Players: Text.append(Pl.SummaryStats(1)) Text.sort(key=lambda key: -key[3]) h.write('<div class="container">\n') h.write('<h2 id="Comparison">Detailed League Statistics</h2>\n') Comp = { "Names": Head_Comp, "TParams": ["l"] * len(Head_Comp), "HeadFormatB": ["{\\tiny{\\bf "] * len(Head_Comp), "HeadFormatE": ["}}"] * len(Head_Comp), "Size": -1, "Guide": True, "TwoColumn": False, } WriteHTML(h, Text, Comp, cls="standtable") h.write("</div>\n") # Spare effectiveness by combinations P.MostCommonLeaves() Pairs = sorted(P.Left.items(), key=lambda x: -x[1]) count = 0 Cols = 5 h.write('<div class="container">\n') h.write('<h2 id="Common">Spare Effectiveness by Combination Left</h2>\n') h.write('<table class="sparetable" border="1">\n') h.write("<tbody>\n") h.write("<tr>\n") for (key, value) in Pairs: if count == Cols: h.write("</tr>\n</tbody>\n</table>\n") h.write('<table class="sparetable" border="1">\n<tbody>\n<tr>\n') count = 0 h.write("<td>\n<center>\n") h.write( '<p><img width = "100%" alt="" src="data:image/svg+xml;base64,' + Spare_Effectiveness(key, P) + '" /></p>' ) # Spare_Effectiveness(key, P, debug = True) h.write("</center>\n</td>\n") count += 1 svg_text = '<svg xmlns="http://www.w3.org/2000/svg" width="2500" height="2500" viewBox="0 0 8 8">' svg_text += '<rect width="8" height="8" style="fill:rgb(255,255,255);stroke:rgb(255,255,255)" /></svg>' encoded_string = b64encode(svg_text.encode("utf-8")) b64 = encoded_string.decode("utf-8") for x in range(count, 5): h.write('<td> <p><img width = "100%" alt="" src="data:image/svg+xml;base64,' + b64 + '" /></p></td>') # h.write('<td> <p><img width = "100%" alt="" /></p> </td>\n') h.write("</tbody>\n</table>\n") h.write("</div>\n") # Section outputting frame-by-frame for G in P.Games: if G.Meta[2].date() != LastDate: if LastDate != "": h.write("</tbody>\n</table>\n</div>\n") h.write('<div class="container">\n') h.write( '<h2 id="{0}">Frame-by-frame {0}</h2>'.format(custom_strftime("{S} of %B, %Y", G.Meta[2].date())) ) h.write('<table class="frametable" border="1" id="report">\n<thead>\n') for i, j in zip(Span, Head): h.write('<th colspan = "{0}"><center>{1}</center></th>\n'.format(i, j)) h.write("</thead>\n<tbody>") h.write("<tr>\n") LastDate = G.Meta[2].date() else: h.write('<table class="frametable" border="1" id="report">\n<thead>\n') for i, j in zip(Span, Head): h.write('<th colspan = "{0}"><center>{1}</center></th>\n'.format(i, j)) h.write("</thead>\n<tbody>") h.write("<tr>\n") # style="background-color: rgba(255,0,0,0.5) for i, j in enumerate(G.NormalScore): # Correction for 10th frames... if i < 19 and i // 2 < len(G.SplitFrames) and G.SplitFrames[i // 2] and i % 2 == 0: h.write('<td style="background-color: rgba(255,0,0,0.5)">{0}</td>\n'.format(j)) elif i == 19 and G.NormalScore[-3] == "X" and len(G.SplitFrames) == 11 and G.SplitFrames[-1] == 1: h.write('<td style="background-color: rgba(255,0,0,0.5)">{0}</td>\n'.format(j)) elif i == 20 and G.NormalScore[-2] == "X" and len(G.SplitFrames) == 12 and G.SplitFrames[-1] == 1: h.write('<td style="background-color: rgba(255,0,0,0.5)">{0}</td>\n'.format(j)) elif i < 19 and i % 2 and j not in ("/", "X"): # Highlight open frames. h.write('<td style="background-color: rgba(255,165,0,0.5)">{0}</td>\n'.format(j)) elif i == 19 and G.NormalScore[-1] == "": h.write('<td style="background-color: rgba(255,165,0,0.5)">{0}</td>\n'.format(j)) elif i == 20 and G.NormalScore[-2] not in ("/", "X") and j not in ("/"): h.write('<td style="background-color: rgba(255,165,0,0.5)">{0}</td>\n'.format(j)) else: h.write("<td>{0}</td>\n".format(j)) h.write("</tr>\n") h.write("<tr>\n") for i, j in zip(G.FSTest, Span): h.write('<td colspan = "{1}"><center>{0}</center></td>\n'.format(i, j)) h.write("</tr>\n") h.write("<tr>\n") for Frame in range(1, 11): if Frame == 10: h.write('<td colspan = "3"><center>\n') else: h.write('<td colspan = "2"><center>\n') h.write( '<p><img width = "100%" alt="" src="data:image/svg+xml;base64,' + Pin_Position_Frame(Frame, G) + '" /></p>' ) h.write("</center></td>") h.write("</tr>\n</tbody>\n</table>\n") h.write("</tbody>\n</table>\n</div>\n") h.write("</body>\n</html>") h.close() options = { "margin-top": "0.5in", "margin-right": "0in", "margin-bottom": "0.2in", "margin-left": "0in", "header-html": r"C:\Users\Chris\Documents\League\Three Way\HTML\testhead.html", } config = pdfkit.configuration(wkhtmltopdf=bytes(r"C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe", "utf-8")) css = [path + "skeletonpdfv2.css"] pdfkit.from_file( hfile, os.getcwd() + r"\HTML\Stats_{0}.pdf".format(F), configuration=config, css=css, options=options )
def pdf_generate(): path = os.path.abspath("bin/wkhtmltopdf-pack") config = pdfkit.configuration(wkhtmltopdf=path) solicitud = request.form['solicitud'] real_solicitud = request.form['solicitud'] fecha1 = request.form['desde'] fecha2 = request.form['hasta'] print(fecha1) print(fecha2) con = mysql.connect() cursor = con.cursor() if solicitud == "Solicitudes Despachadas": tipo_fecha = request.form['tipo_fecha'] if tipo_fecha == 'Dia': cursor.execute("SELECT * FROM view_solicitudes WHERE estatus!=%s AND fechaCompra=%s ", ("POR PROCESAR", fecha1) ) else: cursor.execute("SELECT * FROM view_solicitudes WHERE estatus!=%s AND fechaCompra BETWEEN %s AND %s ", ("POR PROCESAR", fecha1, fecha2) ) solicitudes = cursor.fetchall() body = """ <!DOCTYPE html> <html> <style> table { border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; padding: 15px; } th { text-align: center; } tr:nth-child(even) { background-color: #dddddd; } </style> <head> <img src="https://preview.ibb.co/fKfW3F/gjg.png"> <title>Solicitudes Despachadas</title> <meta name="pdfkit-page-size" content="Legal"/> <meta name="pdfkit-orientation" content="Landscape"/> <meta charset="utf-8"> </head> <body> <center> <h2>Solicitudes Despachadas</h2> </center> <table width="100%"> <tr> <th># Orden</th> <th>Enviado a</th> <th>Comercio</th> <th>Costo</th> <th>Fecha de Compra</th> <th>Fecha Estimada</th> <th>Estado</th> <th>Direccion</th> </tr> """ for solicitud in solicitudes: body += """ <tr style="text-align:center;"> <td>""" + solicitud[0] + """ </td> """ body += """<td>""" + solicitud[1] + """ </td> """ body += """<td>""" + solicitud[2] + """ </td> """ body += """<td>""" + str(solicitud[3]) + """ </td> """ body += """<td>""" + str(solicitud[4]) + """ </td> """ body += """<td>""" + str(solicitud[5]) + """ </td> """ body += """<td>""" + str(solicitud[6]) + """ </td> """ body += """<td>""" + solicitud[7] + """ </td> """ body += """</tr> </table> </body> </html>""" pdf = pdfkit.from_string(body, False, configuration=config) elif solicitud == "Solicitudes Pendientes": tipo_fecha = request.form['tipo_fecha'] if tipo_fecha == 'Dia': cursor.execute("SELECT * FROM view_solicitudes WHERE estatus=%s AND fechaCompra=%s ", ("POR PROCESAR", fecha1) ) else: cursor.execute("SELECT * FROM view_solicitudes WHERE estatus=%s AND fechaCompra BETWEEN %s AND %s ", ("POR PROCESAR", fecha1, fecha2) ) solicitudes = cursor.fetchall() body = """ <!DOCTYPE html> <html> <style> table { border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; padding: 15px; } th { text-align: center; } tr:nth-child(even) { background-color: #dddddd; } </style> <head> <img src="https://preview.ibb.co/fKfW3F/gjg.png"> <title>Solicitudes Pendientes</title> <meta name="pdfkit-page-size" content="Legal"/> <meta name="pdfkit-orientation" content="Landscape"/> <meta charset="utf-8"> </head> <body> <center> <h2>Solicitudes Pendientes</h2> </center> <table width="100%"> <tr> <th># Orden</th> <th>Enviado a</th> <th>Comercio</th> <th>Costo</th> <th>Fecha de Compra</th> <th>Fecha Estimada</th> <th>Estado</th> <th>Direccion</th> </tr> """ for solicitud in solicitudes: body += """ <tr style="text-align:center;"> <td>""" + solicitud[0] + """ </td> """ body += """<td>""" + solicitud[1] + """ </td> """ body += """<td>""" + solicitud[2] + """ </td> """ body += """<td>""" + str(solicitud[3]) + """ </td> """ body += """<td>""" + str(solicitud[4]) + """ </td> """ body += """<td>""" + str(solicitud[5]) + """ </td> """ body += """<td>""" + str(solicitud[6]) + """ </td> """ body += """<td>""" + solicitud[7] + """ </td> """ body += """</tr> </table> </body> </html>""" pdf = pdfkit.from_string(body, False, configuration=config) elif solicitud == "Clientes": cursor.execute("SELECT * FROM view_clientes") solicitudes = cursor.fetchall() body = """ <!DOCTYPE html> <html> <style> table { border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; padding: 15px; } th { text-align: center; } tr:nth-child(even) { background-color: #dddddd; } </style> <head> <img src="https://preview.ibb.co/fKfW3F/gjg.png"> <title>Clientes</title> <meta name="pdfkit-page-size" content="Legal"/> <meta name="pdfkit-orientation" content="Landscape"/> <meta charset="utf-8"> </head> <body> <center> <h2>Clientes</h2> </center> <table width="100%"> <tr> <th>Nombre</th> <th>Email</th> <th>RIF</th> <th>Codigo Postal</th> <th>Cantidad de Solicitudes</th> </tr> """ for solicitud in solicitudes: body += """ <tr style="text-align:center;"> <td>""" + solicitud[0] + """ </td> """ body += """<td>""" + solicitud[1] + """ </td> """ body += """<td>J-""" + str(solicitud[2]) + """ </td> """ body += """<td>""" + str(solicitud[3]) + """ </td> """ body += """<td>""" + str(solicitud[4]) + """ </td> """ body += """</tr> </table> </body> </html>""" pdf = pdfkit.from_string(body, False, configuration=config) elif solicitud == "Destinos": cursor.execute("SELECT * FROM view_destinos ") solicitudes = cursor.fetchall() body = """ <!DOCTYPE html> <html> <style> table { border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; padding: 15px; } th { text-align: center; } tr:nth-child(even) { background-color: #dddddd; } </style> <head> <img src="https://preview.ibb.co/fKfW3F/gjg.png"> <title>Destinos</title> <meta name="pdfkit-page-size" content="Legal"/> <meta name="pdfkit-orientation" content="Landscape"/> <meta charset="utf-8"> </head> <body> <center> <h2>Destinos</h2> </center> <table width="100%"> <tr> <th>Codigo Postal</th> <th>Direccion de Envio</th> <th>Cantidad de Solicitudes</th> </tr> """ for solicitud in solicitudes: body += """ <tr style="text-align:center;"> <td>""" + str(solicitud[0]) + """ </td> """ body += """<td>""" + solicitud[1] + """ </td> """ body += """<td>""" + str(solicitud[2]) + """ </td> """ body += """</tr> </table> </body> </html>""" pdf = pdfkit.from_string(body, False, configuration=config) elif solicitud == "Facturas Canceladas": cursor.execute("SELECT * FROM view_facturas_cancelacion ") solicitudes = cursor.fetchall() body = """ <!DOCTYPE html> <html> <style> table { border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; padding: 15px; } th { text-align: center; } tr:nth-child(even) { background-color: #dddddd; } </style> <head> <img src="https://preview.ibb.co/fKfW3F/gjg.png"> <title>Facturas Canceladas</title> <meta charset="utf-8"> </head> <body> <center> <h2>Facturas Canceladas</h2> </center> <table width="100%"> <tr> <th>Fecha de Cancelacion</th> <th>Fecha de Vencimiento</th> <th>Monto</th> <th>Comercio</th> </tr> """ for solicitud in solicitudes: body += """ <tr style="text-align:center;"> <td>""" + str(solicitud[0]) + """ </td> """ body += """<td>""" + str(solicitud[1]) + """ </td> """ body += """<td>""" + str(solicitud[2]) + """ </td> """ body += """<td>""" + solicitud[3] + """ </td> """ body += """</tr> </table> </body> </html>""" pdf = pdfkit.from_string(body, False, configuration=config) elif solicitud == "Facturas Vigentes": cursor.execute("SELECT * FROM view_facturas_vigentes ") solicitudes = cursor.fetchall() body = """ <!DOCTYPE html> <html> <style> table { border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; padding: 15px; } th { text-align: center; } tr:nth-child(even) { background-color: #dddddd; } </style> <head> <img src="https://preview.ibb.co/fKfW3F/gjg.png"> <title>Facturas Vigentes</title> <meta charset="utf-8"> </head> <body> <center> <h2>Facturas Vigentes</h2> </center> <table width="100%"> <tr> <th>Fecha de Vencimiento</th> <th>Monto</th> <th>Comercio</th> </tr> """ for solicitud in solicitudes: body += """ <tr style="text-align:center;"> <td>""" + str(solicitud[0]) + """ </td> """ body += """<td>""" + str(solicitud[1]) + """ </td> """ body += """<td>""" + solicitud[2] + """ </td> """ body += """</tr> </table> </body> </html>""" pdf = pdfkit.from_string(body, False, configuration=config) elif solicitud == "Facturas Vencidas": cursor.execute("SELECT * FROM view_facturas_vencidas ") solicitudes = cursor.fetchall() body = """ <!DOCTYPE html> <html> <style> table { border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; padding: 15px; } th { text-align: center; } tr:nth-child(even) { background-color: #dddddd; } </style> <head> <img src="https://preview.ibb.co/fKfW3F/gjg.png"> <title>Facturas Vencidas</title> <meta charset="utf-8"> </head> <body> <center> <h2>Facturas Vencidas</h2> </center> <table width="100%"> <tr> <th>Fecha de Vencimiento</th> <th>Monto</th> <th>Comercio</th> </tr> """ for solicitud in solicitudes: body += """ <tr style="text-align:center;"> <td>""" + str(solicitud[0]) + """ </td> """ body += """<td>""" + str(solicitud[1]) + """ </td> """ body += """<td>""" + solicitud[2] + """ </td> """ body += """</tr> </table> </body> </html>""" pdf = pdfkit.from_string(body, False, configuration=config) descripcion = 'Se genero un PDF para las solicitudes de ' + real_solicitud cursor.execute("INSERT INTO auditoria (fecha, usuario, descripcion) VALUES(%s,%s,%s)", (date.today(), 'Administrador', descripcion) ) con.commit() response = make_response(pdf) response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] = 'inline; filename=reporte.pdf' return response
def jpg(): config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltoimage') doc = handle_request(config) return Response(doc, mimetype='image/jpg')
__PORT__ = 8000 class Config(object): JOBS = [ { 'id': 'scheduled_mail', 'func': '__main__:scheduled_mail', 'trigger': 'interval', 'days': 1 } ] SCHEDULER_VIEWS_ENABLED = True # Requires wkhtmltopdf and put it's path here config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf') # PDF Options pdf_options = { 'enable-smart-shrinking': None, 'page-size': 'A4', 'margin-top': '0.59in', 'margin-right': '0.98in', 'margin-bottom': '0.59in', 'margin-left': '0.98in', 'encoding': "UTF-8", 'no-outline': None, 'footer-font-name': 'Times New Roman', 'footer-font-size': 11, 'header-font-name': 'Times New Roman', 'header-font-size': 11, 'header-right': "Avantia",
from reversion.models import Version, Revision from reversion_compare.forms import SelectDiffForm from reversion_compare.views import HistoryCompareDetailView from django_slack import slack_message from curricula.models import * from curricula.serializers import * from curricula.forms import ChangelogForm from documentation.models import IDE, Block, Map logger = logging.getLogger(__name__) pdfkit_config = pdfkit.configuration(wkhtmltopdf=settings.WKHTMLTOPDF_BIN) def index(request): if request.user.is_staff: curricula = Curriculum.objects.filter(version=Curriculum.CURRENT) else: curricula = Curriculum.objects.filter(login_required=False, version=Curriculum.CURRENT) return render(request, 'curricula/index.html', {'curricula': curricula}) ''' Core curricula and lesson views '''