def generate_pdf_and_upload(invoice_json): # Adding ".pdf" fo the name of the SDR file file_name = "{0}.pdf".format(invoice_json['sdr_file_name']) invoice_json['invoice'] = compute_invoice_details() order_data = invoice_json['order'] pisa.showLogging() with codecs.open(TEMPLATE_PATH, 'r', 'utf-8') as f: template_content = f.read() template = Template(template_content) with open (file_name, "wb") as f: pdf = pisa.CreatePDF(template.render(invoice_json), f) if not pdf.err: with open (file_name, "r") as f: invoice_code = compute_uuid() order_code = order_data['order_code'] order = Order.objects.get(order_code=order_code) invoice = Invoice(file_name=file_name, invoice_code=invoice_code, order=order) invoice.set_content('{0}.pdf'.format(invoice_code), f) invoice.save() invoice_json['pdf_file_name'] = file_name return (invoice_json, None)
def generate_pdf(template, context, name): """Generates PDF files based on given input :param template: the template filename including the extension :param context: the context object to be used while rendering the template :param name: the name to be given to PDF file in disk including the extension """ # Get jinja2 template pisa.showLogging() env = Environment(loader=PackageLoader('mopa', 'templates')) template = env.get_template(template) html = template.render(context) # Write PDF to file file_name = os.path.join(config.REPORTS_DIR, name) with open(file_name + '.html', "w+b") as f_html: f_html.write(html.encode('utf-8')) with open(file_name, "w+b") as f_pdf: pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=f_pdf) # Return PDF document for mail sending f_pdf.seek(0) pdf = f_pdf.read() f_pdf.close() return pdf
def convertHtmlToPdf(sourceHtml, fp): from xhtml2pdf import pisa pisa.showLogging() # convert HTML to PDF pisaStatus = pisa.CreatePDF(sourceHtml, dest=fp) # return True on success and False on errors return pisaStatus.err
def menu_pdf_clicked(self, widget): """ returns PDF file but doesn't keep the layout""" url = urllib2.urlopen('http://127.0.0.1:8081') sourceHtml = url.read() pisa.showLogging() outputFilename = "test555.pdf" resultFile = open(outputFilename, "w+b") pisaStatus = pisa.CreatePDF(sourceHtml, resultFile) resultFile.close()
def generate_pdf(data, storeData): file_path = generate_folder(str(data["customerPhoneNumber"]), str(storeData["name"])) sourceHtml = template.render(data=data, storeData=storeData, css=CSS_FILE) amountTotal = str(data["invoiceAmount"]) outputFilename = (file_path + data["createdAt"].strftime("%Y%m%d%H%M%S") + "_" + amountTotal + ".pdf") pisa.showLogging() convertHtmlToPdf(sourceHtml, outputFilename) return outputFilename
def make_pdf_from_applications(applications): html = render_template('applications_pdf.html', generation_date=time.strftime('%Y-%m-%d %H:%M'), applications=applications) f = StringIO() pisa.showLogging() pisa.CreatePDF(html, dest=f) return f.getvalue()
def create_pdf(recipient, verification_code, created_timestamp, primary_mail_address): """ Create a letter in the form of a PDF-document, containing a verification code to be sent to a user. :param recipient: Official address the letter should be sent to :param verification_code: Verification code to include in the letter :param created_timestamp: Timestamp for when the proofing was initiated :param primary_mail_address The users primary mail address """ # Imported here to avoid exposing # render_template to the calling function. from flask import render_template pisa.showLogging() try: name, care_of, address, misc_address, postal_code, city = format_address( recipient) except FormatException as e: current_app.logger.error( 'Postal address formatting failed: {!r}'.format(e)) raise ApiException('Postal address formatting failed', status_code=500, payload={'errors': ['{!r}'.format(e)]}) # Calculate the validity period of the verification # code that is to be shown in the letter. max_wait = timedelta(hours=current_app.config['LETTER_WAIT_TIME_HOURS']) validity_period = (created_timestamp + max_wait).strftime('%Y-%m-%d') letter_template = render_template( 'letter.html', recipient_name=name, recipient_care_of=care_of, recipient_address=address, recipient_misc_address=misc_address, recipient_postal_code=postal_code, recipient_city=city, recipient_verification_code=verification_code, recipient_validity_period=validity_period, recipient_primary_mail_address=primary_mail_address) if current_app.config.get("EKOPOST_DEBUG_PDF", None): pdf_document = open(current_app.config.get("EKOPOST_DEBUG_PDF"), "w") pisa.CreatePDF(StringIO(letter_template), pdf_document) else: pdf_document = StringIO() pisa.CreatePDF(StringIO(letter_template), pdf_document) # Only return the document if it should be sent to Ekopost, # since in debug mode we only want to have it printed locally. return pdf_document
def gen_pdf(): """ using createPDF() """ output = StringIO() pisa.CreatePDF(StringIO(render_template('temp.html').encode("UTF-8")), output) pisa.showLogging() response = make_response(output.getvalue()) response.headers['Content-Disposition'] = "attachment; filename=file.pdf" response.mimetype = "application/pdf" #'application/x-download' return response
def hello_pdf(): pisa.showLogging() packet = StringIO.StringIO() sourcehtml = "<html><body><p>To PDF or not to PDF<p></body></html>" pisa.CreatePDF( sourcehtml, dest=packet) packet.seek(0) return send_file(packet, attachment_filename="willi.pdf", as_attachment=False)
def writePDF(html, fn, folder): fn += ".pdf" out_f = open("chunk.pdf", "w") pisa.showLogging() try: pisaStatus = pisa.CreatePDF(src=html, dest=out_f) shutil.move("chunk.pdf", fn) except: print("Failed to produce " + fn) finally: out_f.close()
def minutesHtmlToPdf(html_string, name_pdf, css_string): pdf_address = "/pdf/%s_Actarium%s.pdf" % ( name_pdf, int(random.random() * 100000)) file_dir = "%s%s" % (MEDIA_ROOT, pdf_address) file_dir = open(file_dir, "w+b") try: showLogging() pdf = CreatePDF(html_string, file_dir, default_css=css_string) if not pdf.err: startViewer(name_pdf) except Exception, e: print e return False
def test_generatePdf(self): default.DEFAULT_FONT["helvetica"]="msyh" fontFile = os.path.join( constant.DirConstant.ROOT_DIR+ '/DoctorSpring/static/font', 'msyh.ttf') pdfmetrics.registerFont(TTFont('msyh',fontFile)) with open(constant.DirConstant.ROOT_DIR+'/DoctorSpring/templates/diagnoseResultPdfTest.html', "rb") as html: pdf_data = html.read() print pisa.showLogging() pdf = convertHtmlToPdf(pdf_data) fd = open("test3.pdf", "w+b") fd.write(pdf.getvalue()) fd.close()
def create_pdf(recipient, verification_code, created_timestamp, primary_mail_address): """ Create a letter in the form of a PDF-document, containing a verification code to be sent to a user. :param recipient: Official address the letter should be sent to :param verification_code: Verification code to include in the letter :param created_timestamp: Timestamp for when the proofing was initiated :param primary_mail_address The users primary mail address """ # Imported here to avoid exposing # render_template to the calling function. from flask import render_template pisa.showLogging() try: name, care_of, address, misc_address, postal_code, city = format_address(recipient) except FormatException as e: current_app.logger.error('Postal address formatting failed: {!r}'.format(e)) raise ApiException('Postal address formatting failed', status_code=500, payload={'errors': ['{!r}'.format(e)]}) # Calculate the validity period of the verification # code that is to be shown in the letter. max_wait = timedelta(hours=current_app.config['LETTER_WAIT_TIME_HOURS']) validity_period = (created_timestamp + max_wait).strftime('%Y-%m-%d') letter_template = render_template('letter.html', recipient_name=name, recipient_care_of=care_of, recipient_address=address, recipient_misc_address=misc_address, recipient_postal_code=postal_code, recipient_city=city, recipient_verification_code=verification_code, recipient_validity_period=validity_period, recipient_primary_mail_address=primary_mail_address) if current_app.config.get("EKOPOST_DEBUG_PDF", None): pdf_document = open(current_app.config.get("EKOPOST_DEBUG_PDF"), "w") pisa.CreatePDF(StringIO(letter_template), pdf_document) else: pdf_document = StringIO() pisa.CreatePDF(StringIO(letter_template), pdf_document) # Only return the document if it should be sent to Ekopost, # since in debug mode we only want to have it printed locally. return pdf_document
def create_pdf(recipient, verification_code, created_timestamp, primary_mail_address): """ Create a letter in the form of a PDF-document, containing a verification code to be sent to a user. :param recipient: Official address the letter should be sent to :param verification_code: Verification code to include in the letter :param created_timestamp: Timestamp for when the proofing was initiated :param primary_mail_address The users primary mail address """ # Imported here to avoid exposing # render_template to the calling function. from flask import render_template pisa.showLogging() try: name, care_of, address, misc_address, postal_code, city = format_address( recipient) except AddressFormatException as e: current_app.logger.error( 'Postal address formatting failed: {!r}'.format(e)) raise e # Calculate the validity period of the verification # code that is to be shown in the letter. max_wait = timedelta(hours=current_app.config.letter_wait_time_hours) validity_period = (created_timestamp + max_wait).strftime('%Y-%m-%d') letter_template = render_template( 'letter.html', recipient_name=name, recipient_care_of=care_of, recipient_address=address, recipient_misc_address=misc_address, recipient_postal_code=postal_code, recipient_city=city, recipient_verification_code=verification_code, recipient_validity_period=validity_period, recipient_primary_mail_address=primary_mail_address, ) pdf_document = BytesIO() pisa.CreatePDF(StringIO(letter_template), pdf_document) return pdf_document
def hello_pdf(): pisa.showLogging() packet = StringIO.StringIO() sourcehtml = "<html><body><p>To PDF or not to PDF<p></body></html>" if (request.values.has_key("url")): print request.values["url"] url = urllib2.urlopen(request.values["url"]) sourcehtml = url.read() pisa.CreatePDF( sourcehtml, dest=packet, show_error_as_pdf=True) packet.seek(0) return send_file(packet, attachment_filename="result.pdf", as_attachment=False)
def test_generatePdf(self): default.DEFAULT_FONT["helvetica"] = "msyh" fontFile = os.path.join( constant.DirConstant.ROOT_DIR + '/DoctorSpring/static/font', 'msyh.ttf') pdfmetrics.registerFont(TTFont('msyh', fontFile)) with open( constant.DirConstant.ROOT_DIR + '/DoctorSpring/templates/diagnoseResultPdfTest.html', "rb") as html: pdf_data = html.read() print pisa.showLogging() pdf = convertHtmlToPdf(pdf_data) fd = open("test3.pdf", "w+b") fd.write(pdf.getvalue()) fd.close()
def create_pdf(recipient, verification_code, created_timestamp, primary_mail_address): """ Create a letter in the form of a PDF-document, containing a verification code to be sent to a user. :param recipient: Official address the letter should be sent to :param verification_code: Verification code to include in the letter :param created_timestamp: Timestamp for when the proofing was initiated :param primary_mail_address The users primary mail address """ # Imported here to avoid exposing # render_template to the calling function. from flask import render_template pisa.showLogging() try: name, care_of, address, misc_address, postal_code, city = format_address(recipient) except AddressFormatException as e: current_app.logger.error('Postal address formatting failed: {!r}'.format(e)) raise e # Calculate the validity period of the verification # code that is to be shown in the letter. max_wait = timedelta(hours=current_app.config['LETTER_WAIT_TIME_HOURS']) validity_period = (created_timestamp + max_wait).strftime('%Y-%m-%d') letter_template = render_template('letter.html', recipient_name=name, recipient_care_of=care_of, recipient_address=address, recipient_misc_address=misc_address, recipient_postal_code=postal_code, recipient_city=city, recipient_verification_code=verification_code, recipient_validity_period=validity_period, recipient_primary_mail_address=primary_mail_address) pdf_document = BytesIO() pisa.CreatePDF(StringIO(letter_template), pdf_document) return pdf_document
def generate_pdf_and_upload(invoice_json): # Adding ".pdf" fo the name of the SDR file file_name = "{0}.pdf".format(invoice_json['sdr_file_name']) invoice_json['invoice'] = compute_invoice_details() pisa.showLogging() with codecs.open(TEMPLATE_PATH, 'r', 'utf-8') as f: template_content = f.read() template = Template(template_content) with open (file_name, "wb") as f: pdf = pisa.CreatePDF(template.render(invoice_json), f) if not pdf.err: upload_invoice_to_s3(file_name) invoice_json['pdf_file_name'] = file_name return invoice_json
def create(userId, fullName, group, compensationName, dormitoryBox, scholarBox, workBox, docsBox): # open file file = open(os.path.join(module_dir, 'data.html')) # Define your data sourceHtml = "".join(file.readlines()) sourceHtml = sourceHtml.replace( "insert_your_font_path", os.path.join(module_dir, 'TimesNewRoman.ttf')) outputFilename = "your_application_" + userId + ".pdf" pisa.showLogging() today = datetime.today() dayOfMonth = str(today.day) month = monthsNames[today.month - 1] year = str(today.year) profiledHtml = adjustHtml(sourceHtml, fullName, group, compensationName, dormitoryBox, scholarBox, workBox, docsBox, dayOfMonth, month, year) convertHtmlToPdf(profiledHtml, outputFilename)
def generate_pdf(data_in): # the current time right now day=strftime("%d-%b-%Y", localtime()) time=strftime("%H%M%S", localtime()) now="%s_%s" % (day, time) # the name of the PDF file to generate pdf_file="%s_%s_cluster.pdf" % (now, data_in["name"]) # # the next block parses some of the cluster info that currently exists as arrays # ntp_servers = "" for ntp_server in data_in["ntpServers"]: ntp_servers = ntp_servers + ", " + ntp_server ntp_servers = ntp_servers.strip(',') name_servers = "" for name_server in data_in["nameServers"]: name_servers = name_servers + ", " + name_server name_servers = name_servers.strip(',') hypervisors = "" for hypervisor in data_in["hypervisorTypes"]: if hypervisor == "kKvm": hypervisor_name = "Acropolis" elif hypervisor == "kVMware": hypervisor_name = "ESXi" elif hypervisor == "kHyperv": hypervisor_name = "Hyper-V" hypervisors = hypervisors + ", " + hypervisor_name hypervisors = hypervisors.strip(',') node_models = "" for model in data_in["rackableUnits"]: node_models = node_models + ", " + model["model"] + " [S/N " + model["serial"] + "]" node_models = node_models.strip(',') # specify the HTML page template source_html_test = Template("""<!doctype html> <html lang="en-us"> <head> <meta charset="utf-8"> <title>Nutanix Cluster Details</title> </head> <body> <p>Nutanix cluster details :: Generated on <strong>$day</strong> at <strong>$now</strong> by <strong>$name</strong> (logged in as $username)</p> <table> <tr> <td>Cluster Name</td> <td>Cluster IP address</td> <td># Nodes</td> <td>NOS Version</td> </tr> <tr> <td>$cluster_name</td> <td>$cluster_ip</td> <td>$nodes</td> <td>$nos</td> </tr> </table> <hr> <table> <tr> <td>Hypervisors</td> </tr> <tr> <td>$hypervisors</td> </tr> </table> <hr> <table> <tr> <td>Models</td> </tr> <tr> <td>$models</td> </tr> </table> <hr> <table> <tr> <td>Cluster Timezone</td> <td>NTP Servers</td> <td>Name Servers</td> </tr> <tr> <td>$timezone</td> <td>$ntp_servers</td> <td>$name_servers</td> </tr> </table> <hr> <table> <tr> <td>Desired RF</td> <td>Actual RF</td> </tr> <tr> <td>$desired_rf</td> <td>$actual_rf</td> </tr> </table> </body> </html> """) # substitute the template variables for actual cluster data template = source_html_test.safe_substitute( day=day, now=time, name=name, username=getpass.getuser(), cluster_name=data_in["name"], cluster_ip=data_in["clusterExternalIPAddress"], nodes=data_in["numNodes"], nos=data_in["version"], hypervisors=hypervisors, models=node_models, timezone=data_in["timezone"], ntp_servers=ntp_servers, name_servers=name_servers, desired_rf=data_in["clusterRedundancyState"]["desiredRedundancyFactor"], actual_rf=data_in["clusterRedundancyState"]["currentRedundancyFactor"] ) # enable logging so we can see what's going on, then generate the final PDF file pisa.showLogging() convert_html_to_pdf(template, pdf_file) print """ Finished generating PDF file: %s """ % pdf_file
async def generatePDF(request): print("generatePDF() Created") timestamp = datetime.timestamp(datetime.now()) # Define your data sourceHtml = """ <html> <head> <style> @page { size: letter portrait; margin: 2cm; } p { margin: 0; } .header_date { font-size: 10pt; } table { -pdf-keep-with-next: true; } </style> <head> <body style="background:#fff;color:#677a89;"> <table> <tbody> <tr> <td> <span style="font-size:10pt;">Date: 21/05/2019</span> </td> <td style="text-align:right;"> <img width='200px' src='https://mytonic.com//sites/all/themes/tonicplus/dist/images/tonic-logo.png' alt='Tonic Logo'> </td> </tr> <tr style="padding-top: .5cm;"> <td> <span style="font-size:22pt;color:#677a89;">INVOICE</span><br> <span style="font-size:8pt;">ORDER 10000010</span> </td> <td style="text-align:right;"> <img width='200px' src='https://s3-production.mytonic.com/revamp/s3fs-public/thyrocare-logo.png' alt='Thyrocare Logo'> </td> <tr style="padding-top: .4cm;"> <td colspan="2"> <span style='font-size:16pt;color:#404448;'>Thank you for your purchase!</span> <br> <br> <span style='font-size:10pt;margin-top:.3cm;'>Hi, We are getting your order ready to be shipped. We will notify you when it has been sent</span> </td> </tr> </tr> </tbody> </table> <br> <br> <br> <hr style="display:block;border-color:#DCDCDC;background-color:#DCDCDC;padding:1cm 0;"> <br> <br> <br> <table> <tbody> <tr> <td> <span style='font-size:16pt;color:#404448;'>Order Summary</span><br> </td> <td style="text-align:right;"> <span style="font-size:16pt;border:1px solid #00b450;color:#00b450;padding:10px 5px 0px 5px;width:40px;text-align:center;display:inline-block;">PAID</span> </td> </tr> <tr> <td> <span style='color:#404448;'>Type - Item</span> </td> <td style="text-align:right;"> <span style='color:#404448;'>Price (tk)</span> </td> </tr> <tr> <td> <span style='color:#404448;'>1. Diabetes Test with a Free Diabetes Machine</span> </td> <td style="text-align:right;"> <span style='color:#404448;'>6,199.00</span> </td> </tr> </tbody> </table> <br> <br> <hr style="display:block;border-color:#DCDCDC;background-color:#DCDCDC;padding:1cm 0;"> <br> <br> <table> <tbody> <tr> <td> <span style='color:#404448;'>Subtotal</span> </td> <td style="text-align:right;"> <span style='color:#404448;'>6,199.00</span> </td> </tr> <tr> <td> <span style='color:#404448;'>Tonic Discount</span> </td> <td style="text-align:right;"> <span style='color:#404448;'>0.00</span> </td> </tr> <tr> <td> <span style='color:#404448;'>Total Price</span> </td> <td style="text-align:right;"> <span style='color:#404448;'>6,199.00</span> </td> </tr> <tr> <td> <span style='color:#404448;'>Delivery Fee</span> </td> <td style="text-align:right;"> <span style='color:#404448;'>0.00</span> </td> </tr> <tr> <td colspan="2"> <hr> </td> </tr> <tr> <td> <span style='color:#404448;'>Net Payable</span> </td> <td style="text-align:right;"> <span style='color:#404448;'>6,199.00</span> </td> </tr> </tbody> </table> <br> <br> <hr style="display:block;border-color:#DCDCDC;background-color:#DCDCDC;padding:1cm 0;"> <br> <br> <table> <tbody> <tr> <td colspan="2"> <span>Customer Information</span> <br> <span>Abdullah Al Noman</span> <br> <span>Address: House no 3/A, Road 4, Block C, Gulshan, Dhaka 1212 Phone: +8801712345678</span> <br> </td> </tr> </tbody> </table> <br> <br> <hr style="display:block;border-color:#DCDCDC;background-color:#DCDCDC;padding:1cm 0;"> <br> <br> <table> <tbody> <tr> <td colspan="2"> <span>Contact us</span> <br> <span>Hotline: (+88) 09666737373 / (+88) 01944443850 (+88) 01944443851 </span> <br> <span>Address: House no 3/A, Road 4, Block C, Gulshan, Dhaka 1212 Phone: +8801712345678</span> <br> <span>Address: Confidence Centre (12th floor), Kha-9, Pragoti Sarani, Shazadpur, Gulshan, Dhaka -1212, Bangladesh</span> </td> </tr> </tbody> </table> </body> </html> """ outputFilename = "INVOICE-{}.pdf".format(timestamp) pisa.showLogging() generated = await convertHtmlToPdf(sourceHtml, outputFilename) print("PDF Created Result: {}".format(generated)) return web.json_response({"msg": "PDF created"}, status=200)
def writeStoryImpl(self, out): self.wrap_width = self.getConfig('wrap_width') if self.wrap_width == '' or self.wrap_width == '0': self.wrap_width = 0 else: self.wrap_width = int(self.wrap_width) wrapout = KludgeStringIO() if self.hasConfig("file_start"): FILE_START = string.Template(self.getConfig("file_start")) else: FILE_START = self.TEXT_FILE_START if self.hasConfig("file_end"): FILE_END = string.Template(self.getConfig("file_end")) else: FILE_END = self.TEXT_FILE_END wrapout.write(FILE_START.substitute(self.story.getAllMetadata())) self.writeTitlePage(wrapout, self.TEXT_TITLE_PAGE_START, self.TEXT_TITLE_ENTRY, self.TEXT_TITLE_PAGE_END) towrap = wrapout.getvalue() self.writeTOCPage(wrapout, self.TEXT_TOC_PAGE_START, self.TEXT_TOC_ENTRY, self.TEXT_TOC_PAGE_END) towrap = wrapout.getvalue() wrapout.close() towrap = removeAllEntities(towrap) self._write(out,self.lineends(self.wraplines(towrap))) if self.hasConfig('chapter_start'): CHAPTER_START = string.Template(self.getConfig("chapter_start")) else: CHAPTER_START = self.TEXT_CHAPTER_START if self.hasConfig('chapter_end'): CHAPTER_END = string.Template(self.getConfig("chapter_end")) else: CHAPTER_END = self.TEXT_CHAPTER_END storyHTML = "" for index, chap in enumerate(self.story.getChapters()): if chap.html: logging.debug('Writing chapter text for: %s' % chap.title) vals={'url':chap.url, 'chapter':chap.title, 'index':"%04d"%(index+1), 'number':index+1} storyHTML = storyHTML + "<code><pre>" + removeAllEntities(CHAPTER_START.substitute(vals)) + "</pre></code>" storyHTML = storyHTML + chap.html storyHTML = storyHTML + removeAllEntities(CHAPTER_END.substitute(vals)) storyHTML = storyHTML + FILE_END.substitute(self.story.getAllMetadata()) header = '<meta charset="utf-8"><style>@page {size: a5;top: 1cm;left: 1cm;right: 1cm;bottom: 1cm;}*{font-size:20px;font-family: "Verdana";}pre{text-align:center;font-weight:bold;page-break-before:always;margin-top:30px;}code{font-size:36px;font-family: "Verdana";}blockquote{margin:0px;}.h1{text-align:center;font-size:48px;margin-top:70px;margin-bottom:20px;padding-top:40px}.h3{margin-top:40px;font-size:24px;text-align:center;}p:nth-of-type(1),p:nth-of-type(2),p:nth-of-type(3){display:none;}</style><p class="h1">' + self.story.getAllMetadata()['title'] + '</p><p class="h3">' + self.story.getAllMetadata()['author'] + '</p><p class="h3">' + self.story.getAllMetadata()['description'] + '</h3>' html = header + storyHTML with open("my.html","w") as f: f.write(html) pisa.showLogging() pisa.CreatePDF(StringIO.StringIO(html), out)
def html2pdf(self): Name = self.nameLineEdit.text() lastname = self.lastnameLineEdit.text() email = self.emailLineEdit.text() address = self.addressLineEdit.text() phone = self.phoneLineEdit.text() education = self.educationLineEdit.text() experience1 = self.experience1LineEdit.text() experience2 = self.experience2LineEdit.text() experience3 = self.experience3LineEdit.text() nCAP = self.nCAPLineEdit.text() interests = self.hobbiesLineEdit.text() about = self.descriptionLineEdit.text() job = self.jobLineEdit.text() skills = self.skillsLineEdit.text() layout = self.layoutColorComboBox.currentText() html = "" simple_pink = f'''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html style="max-width: 700px; margin: auto;"><body style="max-width: 700px; margin: auto;"> <div id="header" style="max-width:700px;margin:auto;border-radius:5px;height:40px;width:100%;background-color:#ffcccc;position:fixed;z-index:1;"></div> <div class="stuff" style="max-width:700px;margin:auto;border-radius:5px;display:inline-block;margin-top:6px;margin-left:10px;width:100%;height:1000px;"> <br style="max-width: 700px; margin: auto;"><br style="max-width: 700px; margin: auto;"><h1 style="max-width: 700px; margin: auto;">Resume</h1> <h2 style="max-width: 700px; margin: auto;">{Name} {lastname} </h2> <hr style="max-width: 700px; margin: auto;"> <br style="max-width: 700px; margin: auto;"><p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Interests</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{interests}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Skills</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{skills}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Education</p> <ul style="max-width: 700px; margin: auto;"> <a style="max-width:700px;margin:auto;color:black;text-decoration:none;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{education}</li> </a> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Experience</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience1}</li> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience2}</li> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience3}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">About me</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{job} | {about}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Notable Courses and Projects</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{nCAP}</li> </ul> </div> <div id="footer" style="max-width:700px;margin:auto;border-radius:5px;height:50px;width:100%;background-color:#ffcccc;clear:both;position:relative;"> <h2 id="name" style="max-width:700px;margin:auto;font-family:Sacramento;float:right;margin-top:10px;margin-right:4%;">{phone} | {email}</h2> <h2 id="name" style="max-width:700px;margin:auto;font-family:Sacramento;float:right;margin-top:10px;margin-right:4%;">{address}</h2> </div> </body></html> ''' simple_green = f'''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html style="max-width: 700px; margin: auto;"><body style="max-width: 700px; margin: auto;"> <div id="header" style="max-width:700px;margin:auto;border-radius:5px;height:40px;width:100%;background-color:#28B463 ;position:fixed;z-index:1;"></div> <div class="stuff" style="max-width:700px;margin:auto;border-radius:5px;display:inline-block;margin-top:6px;margin-left:10px;width:100%;height:1000px;"> <br style="max-width: 700px; margin: auto;"><br style="max-width: 700px; margin: auto;"><h1 style="max-width: 700px; margin: auto;">Resume</h1> <h2 style="max-width: 700px; margin: auto;">{Name} {lastname} </h2> <hr style="max-width: 700px; margin: auto;"> <br style="max-width: 700px; margin: auto;"><p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Interests</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{interests}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Skills</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{skills}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Education</p> <ul style="max-width: 700px; margin: auto;"> <a style="max-width:700px;margin:auto;color:black;text-decoration:none;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{education}</li> </a> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Experience</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience1}</li> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience2}</li> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience3}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">About me</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{job} | {about}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Notable Courses and Projects</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{nCAP}</li> </ul> </div> <div id="footer" style="max-width:700px;margin:auto;border-radius:5px;height:50px;width:100%;background-color:#28B463 ;clear:both;position:relative;"> <h2 id="name" style="max-width:700px;margin:auto;font-family:Sacramento;float:right;margin-top:10px;margin-right:4%;">{phone} | {email}</h2> <h2 id="name" style="max-width:700px;margin:auto;font-family:Sacramento;float:right;margin-top:10px;margin-right:4%;">{address}</h2> </div> </body></html> ''' simple_blue = f'''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html style="max-width: 700px; margin: auto;"><body style="max-width: 700px; margin: auto;"> <div id="header" style="max-width:700px;margin:auto;border-radius:5px;height:40px;width:100%;background-color:#FFBF00 ;position:fixed;z-index:1;"></div> <div class="stuff" style="max-width:700px;margin:auto;border-radius:5px;display:inline-block;margin-top:6px;margin-left:10px;width:100%;height:1000px;"> <br style="max-width: 700px; margin: auto;"><br style="max-width: 700px; margin: auto;"><h1 style="max-width: 700px; margin: auto;">Resume</h1> <h2 style="max-width: 700px; margin: auto;">{Name} {lastname} </h2> <hr style="max-width: 700px; margin: auto;"> <br style="max-width: 700px; margin: auto;"><p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Interests</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{interests}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Skills</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{skills}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Education</p> <ul style="max-width: 700px; margin: auto;"> <a style="max-width:700px;margin:auto;color:black;text-decoration:none;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{education}</li> </a> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Experience</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience1}</li> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience2}</li> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience3}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">About me</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{job} | {about}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Notable Courses and Projects</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{nCAP}</li> </ul> </div> <div id="footer" style="max-width:700px;margin:auto;border-radius:5px;height:50px;width:100%;background-color:#6495ED ;clear:both;position:relative;"> <h2 id="name" style="max-width:700px;margin:auto;font-family:Sacramento;float:right;margin-top:10px;margin-right:4%;">{phone} | {email}</h2> <h2 id="name" style="max-width:700px;margin:auto;font-family:Sacramento;float:right;margin-top:10px;margin-right:4%;">{address}</h2> </div> </body></html> ''' simple_yellow = f'''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html style="max-width: 700px; margin: auto;"><body style="max-width: 700px; margin: auto;"> <div id="header" style="max-width:700px;margin:auto;border-radius:5px;height:40px;width:100%;background-color:#6495ED ;position:relative;z-index:1;"></div> <div class="stuff" style="max-width:700px;margin:auto;border-radius:5px;display:inline-block;margin-top:6px;margin-left:10px;width:100%;height:1000px;"> <br style="max-width: 700px; margin: auto;"><br style="max-width: 700px; margin: auto;"><h1 style="max-width: 700px; margin: auto;">Resume</h1> <h2 style="max-width: 700px; margin: auto;">{Name} {lastname} </h2> <hr style="max-width: 700px; margin: auto;"> <br style="max-width: 700px; margin: auto;"><p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Interests</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{interests}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Skills</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{skills}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Education</p> <ul style="max-width: 700px; margin: auto;"> <a style="max-width:700px;margin:auto;color:black;text-decoration:none;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{education}</li> </a> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Experience</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience1}</li> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience2}</li> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{experience3}</li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">About me</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{job}|{about} </li> </ul> <p class="head" style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';font-size:20px;">Notable Courses and Projects</p> <ul style="max-width: 700px; margin: auto;"> <li style="max-width:700px;margin:auto;font-family:'Cormorant Garamond';">{nCAP} </li> </ul> </div> <div id="footer" style="max-width:700px;margin:auto;border-radius:5px;height:50px;width:100%;background-color:#FFBF00 ;clear:both;position:relative;"> <h2 id="name" style="max-width:700px;margin:auto;font-family:Sacramento;float:right;margin-top:10px;margin-right:4%;">{phone} | {email}</h2> <h2 id="name" style="max-width:700px;margin:auto;font-family:Sacramento;float:right;margin-top:10px;margin-right:4%;">{address}</h2> </div> </body></html> ''' if layout == "simple_pink": html = simple_pink elif layout == "simple_green": html = simple_green elif layout == "simple_yellow": html = simple_yellow else: html = simple_blue output_filename = "Resume.pdf" pisa.showLogging() self.convert_html_to_pdf(html, output_filename)
def writeStoryImpl(self, out): self.wrap_width = self.getConfig('wrap_width') if self.wrap_width == '' or self.wrap_width == '0': self.wrap_width = 0 else: self.wrap_width = int(self.wrap_width) wrapout = KludgeStringIO() if self.hasConfig("file_start"): FILE_START = string.Template(self.getConfig("file_start")) else: FILE_START = self.TEXT_FILE_START if self.hasConfig("file_end"): FILE_END = string.Template(self.getConfig("file_end")) else: FILE_END = self.TEXT_FILE_END wrapout.write(FILE_START.substitute(self.story.getAllMetadata())) self.writeTitlePage(wrapout, self.TEXT_TITLE_PAGE_START, self.TEXT_TITLE_ENTRY, self.TEXT_TITLE_PAGE_END) towrap = wrapout.getvalue() self.writeTOCPage(wrapout, self.TEXT_TOC_PAGE_START, self.TEXT_TOC_ENTRY, self.TEXT_TOC_PAGE_END) towrap = wrapout.getvalue() wrapout.close() towrap = removeAllEntities(towrap) self._write(out, self.lineends(self.wraplines(towrap))) if self.hasConfig('chapter_start'): CHAPTER_START = string.Template(self.getConfig("chapter_start")) else: CHAPTER_START = self.TEXT_CHAPTER_START if self.hasConfig('chapter_end'): CHAPTER_END = string.Template(self.getConfig("chapter_end")) else: CHAPTER_END = self.TEXT_CHAPTER_END storyHTML = "" for index, chap in enumerate(self.story.getChapters()): if chap.html: logging.debug('Writing chapter text for: %s' % chap.title) vals = { 'url': chap.url, 'chapter': chap.title, 'index': "%04d" % (index + 1), 'number': index + 1 } storyHTML = storyHTML + "<code><pre>" + removeAllEntities( CHAPTER_START.substitute(vals)) + "</pre></code>" storyHTML = storyHTML + chap.html storyHTML = storyHTML + removeAllEntities( CHAPTER_END.substitute(vals)) storyHTML = storyHTML + FILE_END.substitute( self.story.getAllMetadata()) header = '<meta charset="utf-8"><style>@page {size: a5;top: 1cm;left: 1cm;right: 1cm;bottom: 1cm;}*{font-size:20px;font-family: "Verdana";}pre{text-align:center;font-weight:bold;page-break-before:always;margin-top:30px;}code{font-size:36px;font-family: "Verdana";}blockquote{margin:0px;}.h1{text-align:center;font-size:48px;margin-top:70px;margin-bottom:20px;padding-top:40px}.h3{margin-top:40px;font-size:24px;text-align:center;}p:nth-of-type(1),p:nth-of-type(2),p:nth-of-type(3){display:none;}</style><p class="h1">' + self.story.getAllMetadata( )['title'] + '</p><p class="h3">' + self.story.getAllMetadata( )['author'] + '</p><p class="h3">' + self.story.getAllMetadata( )['description'] + '</h3>' html = header + storyHTML with open("my.html", "w") as f: f.write(html) pisa.showLogging() pisa.CreatePDF(StringIO.StringIO(html), out)
def invitation(request, idattendee): response = HttpResponse(mimetype='application/pdf; charset=utf-8') #response['Content-Disposition'] = 'attachment; filename=test.pdf' qrCode = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qrCode.add_data('Some data') qrCode.make(fit=True) qrImage = qrCode.make_image() qrFile = StringIO.StringIO() qrImage.save(qrFile, "PNG") ''' file_name = "static/test.png" image_file = open(file_name, 'w+') qrImage.save(image_file, "PNG") image_file.close() ''' #import ipdb; ipdb.set_trace() imagen = qrImage.getdata() #import ipdb; ipdb.set_trace() #imagen = "data:image/png;base64, %s" % b64encode(qrFile.getvalue()) imagen = "data:image/png;base64, %s" % qrFile.getvalue().encode("base64") pdfStringData = render_to_string('landing/pdf.html', { 'QR_CODE' : imagen, 'PROTOCOL' : 'http://', 'HOSTNAME' : request.get_host(), 'CLIENT_TYPE' : 'Agencia', 'EVENT_TYPE_NAME' : 'Título del evento', 'CLIENT_NAME' : 'Nombre', 'CLIENT_SURNAME' : 'Apellidos', 'CLIENT_EMAIL' : '*****@*****.**', 'CLIENT_WEB' : 'www.test.es', 'EVENT_PLACE' : 'Edificio 1', 'EVENT_ADDRESS' : 'C/ No hay calle y menos número', 'EVENT_CITY ' : 'Madrid', 'EVENT_DATES' : 'Días 2 de junio a las 09:00h' }, context_instance=RequestContext(request)) pdfStringData = pdfStringData.encode("UTF-8") pisa.showLogging() packet = StringIO.StringIO() pisa.CreatePDF( pdfStringData, dest=packet) packet.seek(0) response.write(packet.getvalue()) return response
def __call__(self): """Create and render selected report """ # if there's an error, we return productivity.pt which requires these. self.selection_macros = SelectionMacrosView(self.context, self.request) report_id = self.request.get('report_id', '') if not report_id: message = "No report specified in request" self.logger.error(message) self.context.plone_utils.addPortalMessage(message, 'error') return self.template() self.date = DateTime() username = self.context.portal_membership.getAuthenticatedMember( ).getUserName() self.reporter = self.user_fullname(username) self.reporter_email = self.user_email(username) # signature image self.reporter_signature = "" c = [ x for x in self.bika_setup_catalog(portal_type='LabContact') if x.getObject().getUsername() == username ] if c: sf = c[0].getObject().getSignature() if sf: self.reporter_signature = sf.absolute_url() + "/Signature" lab = self.context.bika_setup.laboratory self.laboratory = lab self.lab_title = lab.getName() self.lab_address = lab.getPrintAddress() self.lab_email = lab.getEmailAddress() self.lab_url = lab.getLabURL() client = logged_in_client(self.context) if client: clientuid = client.UID() self.client_title = client.Title() self.client_address = client.getPrintAddress() else: clientuid = None self.client_title = None self.client_address = None ## Render form output # the report can add file names to this list; they will be deleted # once the PDF has been generated. temporary plot image files, etc. self.request['to_remove'] = [] try: exec("from bika.lims.browser.reports.%s import Report" % report_id) except ImportError: message = "Report %s not found (shouldn't happen)" % report_id self.logger.error(message) self.context.plone_utils.addPortalMessage(message, 'error') return self.template() # Report must return dict with: # - report_title - title string for pdf/history listing # - report_data - rendered report output = Report(self.context, self.request)() if type(output) in (str, unicode, bytes): # remove temporary files for f in self.request['to_remove']: os.remove(f) return output ## The report output gets pulled through report_frame.pt self.reportout = output['report_data'] framed_output = self.frame_template() # this is the good part pisa.showLogging() ramdisk = StringIO() pdf = pisa.CreatePDF(framed_output, ramdisk) result = ramdisk.getvalue() ramdisk.close() ## Create new report object reportid = self.aq_parent.generateUniqueId('Report') self.aq_parent.invokeFactory(id=reportid, type_name="Report") report = self.aq_parent._getOb(reportid) report.edit(Client=clientuid) report.processForm() ## write pdf to report object report.edit(title=output['report_title'], ReportFile=result) report.reindexObject() fn = "%s - %s" % (self.date.strftime( self.date_format_short), _u(output['report_title'])) # remove temporary files for f in self.request['to_remove']: os.remove(f) if not pdf.err: setheader = self.request.RESPONSE.setHeader setheader('Content-Type', 'application/pdf') setheader("Content-Disposition", "attachment;filename=\"%s\"" % _c(fn)) self.request.RESPONSE.write(result) return
def _generatePDF(self, raw=False): """ """ def fetch_resources(uri, rel): """ Callback to allow pisa/reportlab to retrieve Images,Stylesheets, etc. `uri` is the href attribute from the html link element. `rel` gives a relative path, but it's not used here. """ urltool = getToolByName(self.context, "portal_url") portal = urltool.getPortalObject() base = portal.absolute_url() if uri.startswith(base): response = subrequest(unquote(uri[len(base)+1:])) if response.status != 200: return None try: # stupid pisa doesn't let me send charset. ctype,encoding = response.getHeader('content-type').split('charset=') ctype = ctype.split(';')[0] # pisa only likes ascii css data = response.getBody().decode(encoding).encode('ascii',errors='ignore') except ValueError: ctype = response.getHeader('content-type').split(';')[0] data = response.getBody() data = data.encode("base64").replace("\n", "") data_uri = 'data:{0};base64,{1}'.format(ctype, data) return data_uri return uri pisa.showLogging(debug=True) # REQUEST = self.REQUEST # open output file for writing (truncated binary) #resultFile = os.tmpfile() #open(outputFilename, "w+b") resultFile = StringIO() html = self.context.restrictedTraverse('@@print')() # convert HTML to PDF pisaStatus = pisa.CreatePDF( html, # the HTML to convert dest=resultFile, debug=True, link_callback=fetch_resources) # file handle to recieve result #print pisaStatus.err resultFile.seek(0) pdfcontent = resultFile.read() # close output file resultFile.close() # close output file now = DateTime() nice_filename = '%s_%s' % (self.context.getId(), now.strftime('%Y%m%d')) if not raw: self.request.response.setHeader("Content-Disposition", "attachment; filename=%s.pdf" % nice_filename) self.request.response.setHeader("Content-Type", "application/pdf") self.request.response.setHeader("Content-Length", len(pdfcontent)) self.request.response.setHeader('Last-Modified', DateTime.rfc822(DateTime())) self.request.response.setHeader("Cache-Control", "no-store") self.request.response.setHeader("Pragma", "no-cache") self.request.response.write(pdfcontent) return pdfcontent
def go(content, filename): print '\n Prepare PDF...\n' cont = header + content + footer pisa.showLogging() pisa.CreatePDF(cont, file(filename, 'wb'), encoding='UTF-8')
def __call__(self): #import pdb #pdb.set_trace() lab = self.context.bika_setup.laboratory self.lab_title = lab.getName() self.address = lab.getPrintAddress() self.date = DateTime() username = self.context.portal_membership.getAuthenticatedMember( ).getUserName() self.reporter = pretty_user_name_or_id(self.context, username) self.reporter_email = pretty_user_email(self.context, username) report_id = self.request.form['report_id'] if report_id == 'analysesperservice': self.reportout = AnalysesPerService(self.context, self.request)() elif report_id == 'analysespersampletype': self.reportout = AnalysesPerSampleType(self.context, self.request)() elif report_id == 'analysesperclient': self.reportout = AnalysesPerClient(self.context, self.request)() elif report_id == 'analysestats': self.reportout = AnalysesTats(self.context, self.request)() elif report_id == 'analysesattachments': self.reportout = AnalysesAttachments(self.context, self.request)() else: self.reportout = "no report to out" # this works but the html is not rendered. #filename = "testing4.pdf" #ramdisk = StringIO() #pdf = pisa.CreatePDF(StringIO(self.reportout), ramdisk) #result = ramdisk.getvalue() #ramdisk.close() #if not pdf.err: # #stream file to browser # setheader = self.request.RESPONSE.setHeader # #setheader('Content-Length',len(result)) # setheader('Content-Type', 'Application/pdf') # setheader('Content-Disposition', 'inline; filename=%s' % filename) # self.request.RESPONSE.write(result) #filename = "testing4.pdf" ramdisk = StringIO() pdf = pisa.CreatePDF(self.template(), ramdisk) result = ramdisk.getvalue() ramdisk.close() if not pdf.err: #stream file to browser setheader = self.request.RESPONSE.setHeader #setheader('Content-Length',len(result)) setheader('Content-Type', 'application/pdf') #setheader('Content-Disposition', 'inline; filename=%s' % filename) #self.request.RESPONSE.write(result) thisid = self.context.invokeFactory("File", id="tmp") thisfile = self.context[thisid] from bika.lims.idserver import renameAfterCreation renameAfterCreation(thisfile) thisfile.setFile(result) self.request.RESPONSE.redirect(thisfile.absolute_url()) pisa.showLogging() """pisa.CreatePDF(self.reportout, "testing.pdf")
def __call__(self): """Create and render selected report """ # if there's an error, we return productivity.pt which requires these. self.selection_macros = SelectionMacrosView(self.context, self.request) report_id = self.request.get('report_id', '') if not report_id: message = "No report specified in request" self.logger.error(message) self.context.plone_utils.addPortalMessage(message, 'error') return self.template() self.date = DateTime() username = self.context.portal_membership.getAuthenticatedMember().getUserName() self.reporter = self.user_fullname(username) self.reporter_email = self.user_email(username) # signature image self.reporter_signature = "" c = [x for x in self.bika_setup_catalog(portal_type='LabContact') if x.getObject().getUsername() == username] if c: sf = c[0].getObject().getSignature() if sf: self.reporter_signature = sf.absolute_url() + "/Signature" lab = self.context.bika_setup.laboratory self.laboratory = lab self.lab_title = lab.getName() self.lab_address = lab.getPrintAddress() self.lab_email = lab.getEmailAddress() self.lab_url = lab.getLabURL() client = logged_in_client(self.context) if client: clientuid = client.UID() self.client_title = client.Title() self.client_address = client.getPrintAddress() else: clientuid = None self.client_title = None self.client_address = None ## Render form output # the report can add file names to this list; they will be deleted # once the PDF has been generated. temporary plot image files, etc. self.request['to_remove'] = [] try: exec("from bika.lims.browser.reports.%s import Report" % report_id) except ImportError: message = "Report %s not found (shouldn't happen)" % report_id self.logger.error(message) self.context.plone_utils.addPortalMessage(message, 'error') return self.template() # Report must return dict with: # - report_title - title string for pdf/history listing # - report_data - rendered report output = Report(self.context, self.request)() if type(output) in (str, unicode, bytes): # remove temporary files for f in self.request['to_remove']: os.remove(f) return output ## The report output gets pulled through report_frame.pt self.reportout = output['report_data'] framed_output = self.frame_template() # this is the good part pisa.showLogging() ramdisk = StringIO() pdf = pisa.CreatePDF(framed_output, ramdisk) result = ramdisk.getvalue() ramdisk.close() ## Create new report object reportid = self.aq_parent.generateUniqueId('Report') self.aq_parent.invokeFactory(id = reportid, type_name = "Report") report = self.aq_parent._getOb(reportid) report.edit(Client = clientuid) report.processForm() ## write pdf to report object report.edit(title = output['report_title'], ReportFile = result) report.reindexObject() fn = "%s - %s" % (self.date.strftime(self.date_format_short), _u(output['report_title'])) # remove temporary files for f in self.request['to_remove']: os.remove(f) if not pdf.err: setheader = self.request.RESPONSE.setHeader setheader('Content-Type', 'application/pdf') setheader("Content-Disposition", "attachment;filename=\"%s\""%_c(fn)) self.request.RESPONSE.write(result) return
def generate_report(country): """ Meta function to generate a report. """ iso3 = country['iso3'] sites = get_sites(iso3) tech_percs = get_tech_percentages(iso3) share_percs = get_sharing_data(iso3) policy_percs = get_policy_data(iso3) energy_percs = get_emissions_data(iso3) power_percs = get_power_data(iso3) policy_inputs = get_policy_inputs(iso3) energy_gen = get_energy_gen_inputs(country['iea_group']) hist_emissions = historical_emissions(iso3) path = os.path.join(BASE_PATH, '..', 'reports', 'templates') env = Environment(loader=FileSystemLoader(path)) template = env.get_template('template.html') template_vars = { "css_location": "D:\\Github\\cuba\\reports\\templates\\style_template.css", "prefered_name": country['prefered_name'], "country": iso3, "figure_1": os.path.join(IMAGES, iso3, 'social_costs_by_strategy.png'), # "upgraded_sites_baseline_10mbps_3g_w": sites['baseline_10mbps_3g_w']['total_upgraded_sites'], # "new_sites_baseline_10mbps_3g_w": sites['baseline_10mbps_3g_w']['total_new_sites'], "upgraded_sites_baseline_10mbps_4g_w": sites['baseline_10mbps_4g_w']['total_upgraded_sites'], "new_sites_baseline_10mbps_4g_w": sites['baseline_10mbps_4g_w']['total_new_sites'], "upgraded_sites_baseline_10mbps_5g_w": sites['baseline_10mbps_5g_w']['total_upgraded_sites'], "new_sites_baseline_10mbps_5g_w": sites['baseline_10mbps_5g_w']['total_new_sites'], # "baseline_10mbps_3g_w": tech_percs['baseline_10mbps_3g_w']['social_cost_bn'], "baseline_10mbps_4g_w": tech_percs['baseline_10mbps_4g_w']['social_cost_bn'], "baseline_10mbps_5g_w": tech_percs['baseline_10mbps_5g_w']['social_cost_bn'], # "w_over_fb_3g_10mbps": round(abs(tech_percs['baseline_10mbps_3g_w']['w_over_fb'])), "w_over_fb_4g_10mbps": round(abs(tech_percs['baseline_10mbps_4g_w']['w_over_fb'])), "w_over_fb_5g_10mbps": round(abs(tech_percs['baseline_10mbps_5g_w']['w_over_fb'])), # "perc_saving_vs_3g_4g_10mbps": round(abs(tech_percs['baseline_10mbps_4g_w']['perc_saving_vs_3g'])), # "perc_saving_vs_3g_5g_10mbps": round(abs(tech_percs['baseline_10mbps_5g_w']['perc_saving_vs_3g'])), # "low_10mbps_3g_w": tech_percs['low_10mbps_3g_w']['social_cost_bn'], "low_10mbps_4g_w": tech_percs['low_10mbps_4g_w']['social_cost_bn'], "low_10mbps_5g_w": tech_percs['low_10mbps_5g_w']['social_cost_bn'], # "high_10mbps_3g_w": tech_percs['high_10mbps_3g_w']['social_cost_bn'], "high_10mbps_4g_w": tech_percs['high_10mbps_4g_w']['social_cost_bn'], "high_10mbps_5g_w": tech_percs['high_10mbps_5g_w']['social_cost_bn'], # "baseline_5mbps_3g_w": tech_percs['baseline_5mbps_3g_w']['social_cost_bn'], "baseline_5mbps_4g_w": tech_percs['baseline_5mbps_4g_w']['social_cost_bn'], "baseline_5mbps_5g_w": tech_percs['baseline_5mbps_5g_w']['social_cost_bn'], # "baseline_20mbps_3g_w": tech_percs['baseline_20mbps_3g_w']['social_cost_bn'], "baseline_20mbps_4g_w": tech_percs['baseline_20mbps_4g_w']['social_cost_bn'], "baseline_20mbps_5g_w": tech_percs['baseline_20mbps_5g_w']['social_cost_bn'], "figure_2": os.path.join(IMAGES, iso3, 'social_costs_by_sharing_strategy.png'), "passive_vs_base_4g_10mbps": round( abs(share_percs['baseline_10mbps_passive'] ['saving_against_baseline'])), "active_vs_base_4g_10mbps": round( abs(share_percs['baseline_10mbps_active'] ['saving_against_baseline'])), "srn_vs_base_4g_10mbps": round( abs(share_percs['baseline_10mbps_srn'] ['saving_against_baseline'])), "passive_cost_4g_10mbps": share_percs['baseline_10mbps_passive']['social_cost_bn'], "active_cost_4g_10mbps": share_percs['baseline_10mbps_active']['social_cost_bn'], "srn_cost_4g_10mbps": share_percs['baseline_10mbps_srn']['social_cost_bn'], "figure_3": os.path.join(IMAGES, iso3, 'social_costs_by_policy_options.png'), "tax_low": int(float(policy_inputs['tax_low'])), "tax_baseline": int(float(policy_inputs['tax_baseline'])), "tax_high": int(float(policy_inputs['tax_high'])), "perc_lowtax": policy_percs['baseline_10mbps_lowtax']['perc_against_baseline'], "perc_hightax": policy_percs['baseline_10mbps_hightax']['perc_against_baseline'], "lowtax_cost_4g_10mbps": policy_percs['baseline_10mbps_lowtax']['social_cost_bn'], "hightax_cost_4g_10mbps": policy_percs['baseline_10mbps_hightax']['social_cost_bn'], "baselinetax_cost_4g_10mbps": policy_percs['baseline_10mbps_baseline']['social_cost_bn'], "profit_margin": int(float(policy_inputs['profit_margin'])), "spectrum_coverage_baseline_usd_mhz_pop": policy_inputs['spectrum_coverage_baseline_usd_mhz_pop'], "spectrum_capacity_baseline_usd_mhz_pop": policy_inputs['spectrum_capacity_baseline_usd_mhz_pop'], "spectrum_cost_low": int(float(policy_inputs['spectrum_cost_low'])), "spectrum_cost_high": int(float(policy_inputs['spectrum_cost_high'])), "perc_lowspectrum": policy_percs['baseline_10mbps_lowspectrumfees'] ['perc_against_baseline'], "perc_highspectrum": policy_percs['baseline_10mbps_highspectrumfees'] ['perc_against_baseline'], "lowspectrum_cost_4g_10mbps": policy_percs['baseline_10mbps_lowspectrumfees']['social_cost_bn'], "highspectrum_cost_4g_10mbps": policy_percs['baseline_10mbps_highspectrumfees']['social_cost_bn'], "iea_group": country['iea_group'], "coal_2020_perc": energy_gen['coal_2020_perc'], "gas_2020_perc": energy_gen['gas_2020_perc'], "renewables_2020_perc": energy_gen['renewables_2020_perc'], "nuclear_2020_perc": energy_gen['nuclear_2020_perc'], "coal_2030_perc": energy_gen['coal_2030_perc'], "gas_2030_perc": energy_gen['gas_2030_perc'], "renewables_2030_perc": energy_gen['renewables_2030_perc'], "nuclear_2030_perc": energy_gen['nuclear_2030_perc'], "figure_4": os.path.join(IMAGES, iso3, 'energy_emissions.png'), "figure_5": os.path.join(IMAGES, iso3, 'health_emissions.png'), "energy_baseline_5mbps_4g_w": float( round( energy_percs['baseline_5mbps_4g_w'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_5mbps_4g_fb": float( round( energy_percs['baseline_5mbps_4g_fb'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_5mbps_5g_w": float( round( energy_percs['baseline_5mbps_5g_w'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_5mbps_5g_fb": float( round( energy_percs['baseline_5mbps_5g_fb'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_10mbps_4g_w": float( round( energy_percs['baseline_10mbps_4g_w'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_10mbps_4g_fb": float( round( energy_percs['baseline_10mbps_4g_fb'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_10mbps_5g_w": float( round( energy_percs['baseline_10mbps_5g_w'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_10mbps_5g_fb": float( round( energy_percs['baseline_10mbps_5g_fb'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_20mbps_4g_w": float( round( energy_percs['baseline_20mbps_4g_w'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_20mbps_4g_fb": float( round( energy_percs['baseline_20mbps_4g_fb'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_20mbps_5g_w": float( round( energy_percs['baseline_20mbps_5g_w'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "energy_baseline_20mbps_5g_fb": float( round( energy_percs['baseline_20mbps_5g_fb'] ['total_energy_annual_demand_kwh'] / 1e9, 1)), "carbon_baseline_5mbps_4g_w": float( round( energy_percs['baseline_5mbps_4g_w']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_5mbps_4g_fb": float( round( energy_percs['baseline_5mbps_4g_fb']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_5mbps_5g_w": float( round( energy_percs['baseline_5mbps_5g_w']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_5mbps_5g_fb": float( round( energy_percs['baseline_5mbps_5g_fb']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_10mbps_4g_w": float( round( energy_percs['baseline_10mbps_4g_w']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_10mbps_4g_fb": float( round( energy_percs['baseline_10mbps_4g_fb']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_10mbps_5g_w": float( round( energy_percs['baseline_10mbps_5g_w']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_10mbps_5g_fb": float( round( energy_percs['baseline_10mbps_5g_fb']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_20mbps_4g_w": float( round( energy_percs['baseline_20mbps_4g_w']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_20mbps_4g_fb": float( round( energy_percs['baseline_20mbps_4g_fb']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_20mbps_5g_w": float( round( energy_percs['baseline_20mbps_5g_w']['demand_carbon_per_kwh'] / 1e9, 1)), "carbon_baseline_20mbps_5g_fb": float( round( energy_percs['baseline_20mbps_5g_fb']['demand_carbon_per_kwh'] / 1e9, 1)), "nitrogen_baseline_5mbps_4g_w": int( round( energy_percs['baseline_5mbps_4g_w']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_5mbps_4g_fb": int( round( energy_percs['baseline_5mbps_4g_fb']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_5mbps_5g_w": int( round( energy_percs['baseline_5mbps_5g_w']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_5mbps_5g_fb": int( round( energy_percs['baseline_5mbps_5g_fb']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_10mbps_4g_w": int( round( energy_percs['baseline_10mbps_4g_w']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_10mbps_4g_fb": int( round( energy_percs['baseline_10mbps_4g_fb']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_10mbps_5g_w": int( round( energy_percs['baseline_10mbps_5g_w']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_10mbps_5g_fb": int( round( energy_percs['baseline_10mbps_5g_fb']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_20mbps_4g_w": int( round( energy_percs['baseline_20mbps_4g_w']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_20mbps_4g_fb": int( round( energy_percs['baseline_20mbps_4g_fb']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_20mbps_5g_w": int( round( energy_percs['baseline_20mbps_5g_w']['nitrogen_oxide_per_kwh'] / 1e3)), "nitrogen_baseline_20mbps_5g_fb": int( round( energy_percs['baseline_20mbps_5g_fb']['nitrogen_oxide_per_kwh'] / 1e3)), "sulpher_baseline_5mbps_4g_w": int( round( energy_percs['baseline_5mbps_4g_w']['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_5mbps_4g_fb": int( round( energy_percs['baseline_5mbps_4g_fb']['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_5mbps_5g_w": int( round( energy_percs['baseline_5mbps_5g_w']['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_5mbps_5g_fb": int( round( energy_percs['baseline_5mbps_5g_fb']['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_10mbps_4g_w": int( round( energy_percs['baseline_10mbps_4g_w']['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_10mbps_4g_fb": int( round(energy_percs['baseline_10mbps_4g_fb'] ['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_10mbps_5g_w": int( round( energy_percs['baseline_10mbps_5g_w']['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_10mbps_5g_fb": int( round(energy_percs['baseline_10mbps_5g_fb'] ['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_20mbps_4g_w": int( round( energy_percs['baseline_20mbps_4g_w']['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_20mbps_4g_fb": int( round(energy_percs['baseline_20mbps_4g_fb'] ['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_20mbps_5g_w": int( round( energy_percs['baseline_20mbps_5g_w']['sulpher_dioxide_per_kwh'] / 1e6)), "sulpher_baseline_20mbps_5g_fb": int( round(energy_percs['baseline_20mbps_5g_fb'] ['sulpher_dioxide_per_kwh'] / 1e6)), "pm10_baseline_5mbps_4g_w": int(round(energy_percs['baseline_5mbps_4g_w']['pm10_per_kwh'] / 1e6)), "pm10_baseline_5mbps_4g_fb": int(round(energy_percs['baseline_5mbps_4g_fb']['pm10_per_kwh'] / 1e6)), "pm10_baseline_5mbps_5g_w": int(round(energy_percs['baseline_5mbps_5g_w']['pm10_per_kwh'] / 1e6)), "pm10_baseline_5mbps_5g_fb": int(round(energy_percs['baseline_5mbps_5g_fb']['pm10_per_kwh'] / 1e6)), "pm10_baseline_10mbps_4g_w": int(round(energy_percs['baseline_10mbps_4g_w']['pm10_per_kwh'] / 1e6)), "pm10_baseline_10mbps_4g_fb": int(round(energy_percs['baseline_10mbps_4g_fb']['pm10_per_kwh'] / 1e6)), "pm10_baseline_10mbps_5g_w": int(round(energy_percs['baseline_10mbps_5g_w']['pm10_per_kwh'] / 1e6)), "pm10_baseline_10mbps_5g_fb": int(round(energy_percs['baseline_10mbps_5g_fb']['pm10_per_kwh'] / 1e6)), "pm10_baseline_20mbps_4g_w": int(round(energy_percs['baseline_20mbps_4g_w']['pm10_per_kwh'] / 1e6)), "pm10_baseline_20mbps_4g_fb": int(round(energy_percs['baseline_20mbps_4g_fb']['pm10_per_kwh'] / 1e6)), "pm10_baseline_20mbps_5g_w": int(round(energy_percs['baseline_20mbps_5g_w']['pm10_per_kwh'] / 1e6)), "pm10_baseline_20mbps_5g_fb": int(round(energy_percs['baseline_20mbps_5g_fb']['pm10_per_kwh'] / 1e6)), "perc_energy_baseline_5mbps_4g_w": energy_percs['baseline_5mbps_4g_w']['perc_energy_dif_vs_4G'], "perc_energy_baseline_5mbps_4g_fb": energy_percs['baseline_5mbps_4g_fb']['perc_energy_dif_vs_4G'], "perc_energy_baseline_5mbps_5g_w": energy_percs['baseline_5mbps_5g_w']['perc_energy_dif_vs_4G'], "perc_energy_baseline_5mbps_5g_fb": energy_percs['baseline_5mbps_5g_fb']['perc_energy_dif_vs_4G'], "perc_energy_baseline_10mbps_4g_w": energy_percs['baseline_10mbps_4g_w']['perc_energy_dif_vs_4G'], "perc_energy_baseline_10mbps_4g_fb": energy_percs['baseline_10mbps_4g_fb']['perc_energy_dif_vs_4G'], "perc_energy_baseline_10mbps_5g_w": energy_percs['baseline_10mbps_5g_w']['perc_energy_dif_vs_4G'], "perc_energy_baseline_10mbps_5g_fb": energy_percs['baseline_10mbps_5g_fb']['perc_energy_dif_vs_4G'], "perc_energy_baseline_20mbps_4g_w": energy_percs['baseline_20mbps_4g_w']['perc_energy_dif_vs_4G'], "perc_energy_baseline_20mbps_4g_fb": energy_percs['baseline_20mbps_4g_fb']['perc_energy_dif_vs_4G'], "perc_energy_baseline_20mbps_5g_w": energy_percs['baseline_20mbps_5g_w']['perc_energy_dif_vs_4G'], "perc_energy_baseline_20mbps_5g_fb": energy_percs['baseline_20mbps_5g_fb']['perc_energy_dif_vs_4G'], "perc_carbon_baseline_5mbps_4g_w": energy_percs['baseline_5mbps_4g_w']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_5mbps_4g_fb": energy_percs['baseline_5mbps_4g_fb']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_5mbps_5g_w": energy_percs['baseline_5mbps_5g_w']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_5mbps_5g_fb": energy_percs['baseline_5mbps_5g_fb']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_10mbps_4g_w": energy_percs['baseline_10mbps_4g_w']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_10mbps_4g_fb": energy_percs['baseline_10mbps_4g_fb']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_10mbps_5g_w": energy_percs['baseline_10mbps_5g_w']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_10mbps_5g_fb": energy_percs['baseline_10mbps_5g_fb']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_20mbps_4g_w": energy_percs['baseline_20mbps_4g_w']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_20mbps_4g_fb": energy_percs['baseline_20mbps_4g_fb']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_20mbps_5g_w": energy_percs['baseline_20mbps_5g_w']['perc_carbon_dif_vs_4G'], "perc_carbon_baseline_20mbps_5g_fb": energy_percs['baseline_20mbps_5g_fb']['perc_carbon_dif_vs_4G'], "perc_nitrogen_baseline_5mbps_4g_w": energy_percs['baseline_5mbps_4g_w']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_5mbps_4g_fb": energy_percs['baseline_5mbps_4g_fb']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_5mbps_5g_w": energy_percs['baseline_5mbps_5g_w']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_5mbps_5g_fb": energy_percs['baseline_5mbps_5g_fb']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_10mbps_4g_w": energy_percs['baseline_10mbps_4g_w']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_10mbps_4g_fb": energy_percs['baseline_10mbps_4g_fb']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_10mbps_5g_w": energy_percs['baseline_10mbps_5g_w']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_10mbps_5g_fb": energy_percs['baseline_10mbps_5g_fb']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_20mbps_4g_w": energy_percs['baseline_20mbps_4g_w']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_20mbps_4g_fb": energy_percs['baseline_20mbps_4g_fb']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_20mbps_5g_w": energy_percs['baseline_20mbps_5g_w']['perc_nitrogen_dif_vs_4G'], "perc_nitrogen_baseline_20mbps_5g_fb": energy_percs['baseline_20mbps_5g_fb']['perc_nitrogen_dif_vs_4G'], "perc_sulpher_baseline_5mbps_4g_w": energy_percs['baseline_5mbps_4g_w']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_5mbps_4g_fb": energy_percs['baseline_5mbps_4g_fb']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_5mbps_5g_w": energy_percs['baseline_5mbps_5g_w']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_5mbps_5g_fb": energy_percs['baseline_5mbps_5g_fb']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_10mbps_4g_w": energy_percs['baseline_10mbps_4g_w']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_10mbps_4g_fb": energy_percs['baseline_10mbps_4g_fb']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_10mbps_5g_w": energy_percs['baseline_10mbps_5g_w']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_10mbps_5g_fb": energy_percs['baseline_10mbps_5g_fb']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_20mbps_4g_w": energy_percs['baseline_20mbps_4g_w']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_20mbps_4g_fb": energy_percs['baseline_20mbps_4g_fb']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_20mbps_5g_w": energy_percs['baseline_20mbps_5g_w']['perc_sulpher_dif_vs_4G'], "perc_sulpher_baseline_20mbps_5g_fb": energy_percs['baseline_20mbps_5g_fb']['perc_sulpher_dif_vs_4G'], "perc_pm10_baseline_5mbps_4g_w": energy_percs['baseline_5mbps_4g_w']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_5mbps_4g_fb": energy_percs['baseline_5mbps_4g_fb']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_5mbps_5g_w": energy_percs['baseline_5mbps_5g_w']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_5mbps_5g_fb": energy_percs['baseline_5mbps_5g_fb']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_10mbps_4g_w": energy_percs['baseline_10mbps_4g_w']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_10mbps_4g_fb": energy_percs['baseline_10mbps_4g_fb']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_10mbps_5g_w": energy_percs['baseline_10mbps_5g_w']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_10mbps_5g_fb": energy_percs['baseline_10mbps_5g_fb']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_20mbps_4g_w": energy_percs['baseline_20mbps_4g_w']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_20mbps_4g_fb": energy_percs['baseline_20mbps_4g_fb']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_20mbps_5g_w": energy_percs['baseline_20mbps_5g_w']['perc_pm10_dif_vs_4G'], "perc_pm10_baseline_20mbps_5g_fb": energy_percs['baseline_20mbps_5g_fb']['perc_pm10_dif_vs_4G'], "figure_6": os.path.join(IMAGES, iso3, 'power_strategies.png'), "perc_carbon_baseline_10mbps_4g_w_renewables": round( abs(power_percs['baseline_10mbps_4g_w_renewables'] ['perc_carbon_dif_vs_renewables'])), "perc_carbon_baseline_10mbps_4g_fb_renewables": round( abs(power_percs['baseline_10mbps_4g_fb_renewables'] ['perc_carbon_dif_vs_renewables'])), "perc_carbon_baseline_10mbps_5g_w_renewables": round( abs(power_percs['baseline_10mbps_5g_w_renewables'] ['perc_carbon_dif_vs_renewables'])), "perc_carbon_baseline_10mbps_5g_fb_renewables": round( abs(power_percs['baseline_10mbps_5g_fb_renewables'] ['perc_carbon_dif_vs_renewables'])), "perc_nitrogen_baseline_10mbps_4g_w_renewables": round( abs(power_percs['baseline_10mbps_4g_w_renewables'] ['perc_nitrogen_dif_vs_renewables'])), "perc_nitrogen_baseline_10mbps_4g_fb_renewables": round( abs(power_percs['baseline_10mbps_4g_fb_renewables'] ['perc_nitrogen_dif_vs_renewables'])), "perc_nitrogen_baseline_10mbps_5g_w_renewables": round( abs(power_percs['baseline_10mbps_5g_w_renewables'] ['perc_nitrogen_dif_vs_renewables'])), "perc_nitrogen_baseline_10mbps_5g_fb_renewables": round( abs(power_percs['baseline_10mbps_5g_fb_renewables'] ['perc_nitrogen_dif_vs_renewables'])), "perc_sulpher_baseline_10mbps_4g_w_renewables": round( abs(power_percs['baseline_10mbps_4g_w_renewables'] ['perc_sulpher_dif_vs_renewables'])), "perc_sulpher_baseline_10mbps_4g_fb_renewables": round( abs(power_percs['baseline_10mbps_4g_fb_renewables'] ['perc_sulpher_dif_vs_renewables'])), "perc_sulpher_baseline_10mbps_5g_w_renewables": round( abs(power_percs['baseline_10mbps_5g_w_renewables'] ['perc_sulpher_dif_vs_renewables'])), "perc_sulpher_baseline_10mbps_5g_fb_renewables": round( abs(power_percs['baseline_10mbps_5g_fb_renewables'] ['perc_sulpher_dif_vs_renewables'])), "perc_pm10_baseline_10mbps_4g_w_renewables": round( abs(power_percs['baseline_10mbps_4g_w_renewables'] ['perc_pm10_dif_vs_renewables'])), "perc_pm10_baseline_10mbps_4g_fb_renewables": round( abs(power_percs['baseline_10mbps_4g_fb_renewables'] ['perc_pm10_dif_vs_renewables'])), "perc_pm10_baseline_10mbps_5g_w_renewables": round( abs(power_percs['baseline_10mbps_5g_w_renewables'] ['perc_pm10_dif_vs_renewables'])), "perc_pm10_baseline_10mbps_5g_fb_renewables": round( abs(power_percs['baseline_10mbps_5g_fb_renewables'] ['perc_pm10_dif_vs_renewables'])), "historical_co2": round(hist_emissions['historical_co2'], 1), } html_out = template.render(template_vars) filename = 'Oughton, E.J. (2022) Assessment of 4G and 5G Universal Broadband Infrastructure Strategies for {}.pdf'.format( country['prefered_name']) path = os.path.join(OUTPUT, filename) pisa.showLogging() convert_html_to_pdf(html_out, path)
def __call__(self): rc = getToolByName(self.context, REFERENCE_CATALOG) workflow = getToolByName(self.context, "portal_workflow") BatchEmail = self.context.bika_setup.getBatchEmail() username = self.context.portal_membership.getAuthenticatedMember().getUserName() self.reporter = self.user_fullname(username) self.reporter_email = self.user_email(username) # signature image self.reporter_signature = "" c = [x for x in self.bika_setup_catalog(portal_type="LabContact") if x.getObject().getUsername() == username] if c: sf = c[0].getObject().getSignature() if sf: self.reporter_signature = sf.absolute_url() + "/Signature" # lab address self.laboratory = laboratory = self.context.bika_setup.laboratory self.lab_address = "<br/>".join(laboratory.getPrintAddress()) # group/publish analysis requests by contact ARs_by_contact = {} for ar in self.analysis_requests: contact_uid = ar.getContact().UID() if contact_uid not in ARs_by_contact: ARs_by_contact[contact_uid] = [] ARs_by_contact[contact_uid].append(ar) for contact_uid, ars in ARs_by_contact.items(): ars.sort() self.contact = ars[0].getContact() self.pub_pref = self.contact.getPublicationPreference() batch_size = "email" in self.pub_pref and BatchEmail or 5 # client address self.client = ars[0].aq_parent self.client_address = "<br/>".join(self.client.getPrintAddress()) self.Footer = self.context.bika_setup.getResultFooter() # send batches of ARs to each contact for b in range(0, len(ars), batch_size): self.batch = ars[b : b + batch_size] self.any_accredited = False self.any_drymatter = False # get all services from all requests in this batch into a # dictionary: # {'Point Of Capture': {'Category': [service,service,...]}} self.services = {} out_fn = "_".join([ar.Title() for ar in self.batch]) for ar in self.batch: if ar.getReportDryMatter(): self.any_drymatter = True states = ("verified", "published") for analysis in ar.getAnalyses(full_objects=True, review_state=states): service = analysis.getService() poc = POINTS_OF_CAPTURE.getValue(service.getPointOfCapture()) cat = service.getCategoryTitle() if poc not in self.services: self.services[poc] = {} if cat not in self.services[poc]: self.services[poc][cat] = [] if service not in self.services[poc][cat]: self.services[poc][cat].append(service) if service.getAccredited(): self.any_accredited = True # compose and send email if "email" in self.pub_pref: # render template ar_results = self.ar_results() ar_results = safe_unicode(ar_results).encode("utf-8") ar_results = self.escape(ar_results) debug_mode = App.config.getConfiguration().debug_mode if debug_mode: open(join(Globals.INSTANCE_HOME, "var", out_fn + ".html"), "w").write(ar_results) pisa.showLogging() ramdisk = StringIO() pdf = pisa.CreatePDF(ar_results, ramdisk) pdf_data = ramdisk.getvalue() ramdisk.close() if debug_mode: open(join(Globals.INSTANCE_HOME, "var", out_fn + ".pdf"), "wb").write(pdf_data) mime_msg = MIMEMultipart("related") mime_msg["Subject"] = self.get_mail_subject() mime_msg["From"] = formataddr((encode_header(laboratory.getName()), laboratory.getEmailAddress())) mime_msg["To"] = formataddr( (encode_header(self.contact.getFullname()), self.contact.getEmailAddress()) ) mime_msg.preamble = "This is a multi-part MIME message." msg_txt = MIMEText(ar_results, _subtype="html") mime_msg.attach(msg_txt) if not pdf.err: part = MIMEBase("application", "application/pdf") part.add_header("Content-Disposition", 'attachment; filename="%s.pdf"' % out_fn) part.set_payload(pdf_data) Encoders.encode_base64(part) mime_msg.attach(part) try: host = getToolByName(self.context, "MailHost") host.send(mime_msg.as_string(), immediate=True) except SMTPServerDisconnected, msg: if not debug_mode: raise SMTPServerDisconnected(msg) except SMTPRecipientsRefused, msg: raise WorkflowException(str(msg)) if self.action == "publish": for ar in self.batch: try: workflow.doActionFor(ar, "publish") except WorkflowException: pass ## if not pdf.err: ## setheader = self.request.RESPONSE.setHeader ## setheader('Content-Type', 'application/pdf') ## setheader("Content-Disposition", "attachment;filename=\"%s.pdf\"" % out_fn) ## self.request.RESPONSE.write(pdf_data) else: raise Exception, "XXX pub_pref %s" % self.pub_pref
def generate_pdf(cluster_in, container_in): # the current time right now day=strftime("%d-%b-%Y", localtime()) time=strftime("%H%M%S", localtime()) now="%s_%s" % (day, time) # the name of the PDF file to generate pdf_file="%s_%s_cluster.pdf" % (now, cluster_in["name"]) # # the next block parses some of the cluster info that currently exists as arrays # ntp_servers = "" for ntp_server in cluster_in["ntpServers"]: ntp_servers = ntp_servers + ", " + ntp_server ntp_servers = ntp_servers.strip(',') name_servers = "" for name_server in cluster_in["nameServers"]: name_servers = name_servers + ", " + name_server name_servers = name_servers.strip(',') hypervisors = "" for hypervisor in cluster_in["hypervisorTypes"]: if hypervisor == "kKvm": hypervisor_name = "Acropolis" elif hypervisor == "kVMware": hypervisor_name = "ESXi" elif hypervisor == "kHyperv": hypervisor_name = "Hyper-V" hypervisors = hypervisors + ", " + hypervisor_name hypervisors = hypervisors.strip(',') node_models = "" for model in cluster_in["rackableUnits"]: try: node_models = node_models + ", " + model["modelName"] + " [ S/N " + model["serial"] + " ]" except TypeError: node_models = 'None available' node_models = node_models.strip(',') containers = "" for container in container_in["entities"]: containers = containers + "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % (container["name"], str(container["replicationFactor"]), str(container["compressionEnabled"]), str(container["onDiskDedup"]) ) # specify the HTML page template # nutanix.html doesn't exist in the public repo (used for testing without messing with repo version) # at this point we have already verified that template.html exists, at least if os.path.isfile( "./templates/nutanix.html" ): template_name = "./templates/nutanix.html" else: template_name = "./templates/template.html" # load the HTML content from the template with open( template_name, "r") as data_file: source_html = Template( data_file.read() ) # substitute the template variables for actual cluster data template = source_html.safe_substitute( day=day, now=time, name=name, username=getpass.getuser(), cluster_name=str(cluster_in["name"]), cluster_ip=str(cluster_in["clusterExternalIPAddress"]) if cluster_in["clusterExternalIPAddress"] else "Not set", nodes=str(cluster_in["numNodes"]), nos=str(cluster_in["version"]), hypervisors=hypervisors, models=str(node_models), timezone=str(cluster_in["timezone"]), ntp_servers=str(ntp_servers), name_servers=str(name_servers), desired_rf=cluster_in["clusterRedundancyState"]["desiredRedundancyFactor"], actual_rf=cluster_in["clusterRedundancyState"]["currentRedundancyFactor"], nos_full=str(cluster_in["fullVersion"]), containers=str(containers), container_count=container_in["metadata"]["grandTotalEntities"], computer_name=socket.gethostname() ) # enable logging so we can see what's going on, then generate the final PDF file pisa.showLogging() convert_html_to_pdf(template, pdf_file) print """ Finished generating PDF file: %s """ % pdf_file
def __call__(self): rc = getToolByName(self.context, REFERENCE_CATALOG) workflow = getToolByName(self.context, 'portal_workflow') BatchEmail = self.context.bika_setup.getBatchEmail() username = self.context.portal_membership.getAuthenticatedMember().getUserName() self.reporter = self.user_fullname(username) self.reporter_email = self.user_email(username) # signature image self.reporter_signature = "" c = [x for x in self.bika_setup_catalog(portal_type='LabContact') if x.getObject().getUsername() == username] if c: sf = c[0].getObject().getSignature() if sf: self.reporter_signature = sf.absolute_url() + "/Signature" # lab address self.laboratory = laboratory = self.context.bika_setup.laboratory lab_address = laboratory.getPostalAddress() \ or laboratory.getBillingAddress() \ or laboratory.getPhysicalAddress() if lab_address: _keys = ['address', 'city', 'state', 'zip', 'country'] _list = [lab_address.get(v) for v in _keys] self.lab_address = "<br/>".join(_list).replace("\n", "<br/>") else: self.lab_address = None # group/publish analysis requests by contact ARs_by_contact = {} for ar in self.analysis_requests: contact_uid = ar.getContact().UID() if contact_uid not in ARs_by_contact: ARs_by_contact[contact_uid] = [] ARs_by_contact[contact_uid].append(ar) for contact_uid, ars in ARs_by_contact.items(): ars.sort() self.contact = ars[0].getContact() self.pub_pref = self.contact.getPublicationPreference() batch_size = 'email' in self.pub_pref and BatchEmail or 5 # client address self.client = ars[0].aq_parent client_address = self.client.getPostalAddress() \ or self.contact.getBillingAddress() \ or self.contact.getPhysicalAddress() if client_address: _keys = ['address', 'city', 'state', 'zip', 'country'] _list = [client_address.get(v) for v in _keys] self.client_address = "<br/>".join(_list).replace("\n", "<br/>") else: self.client_address = None self.Footer = self.context.bika_setup.getResultFooter() # send batches of ARs to each contact for b in range(0, len(ars), batch_size): self.batch = ars[b:b+batch_size] self.any_accredited = False self.any_drymatter = False # get all services from all requests in this batch into a # dictionary: # {'Point Of Capture': {'Category': [service,service,...]}} self.services = {} out_fn = "_".join([ar.Title() for ar in self.batch]) for ar in self.batch: if ar.getReportDryMatter(): self.any_drymatter = True states = ("verified", "published") for analysis in ar.getAnalyses(full_objects=True, review_state=states): service = analysis.getService() poc = POINTS_OF_CAPTURE.getValue(service.getPointOfCapture()) cat = service.getCategoryTitle() if poc not in self.services: self.services[poc] = {} if cat not in self.services[poc]: self.services[poc][cat] = [] if service not in self.services[poc][cat]: self.services[poc][cat].append(service) if (service.getAccredited()): self.any_accredited = True # compose and send email if 'email' in self.pub_pref: # render template ar_results = self.ar_results() debug_mode = App.config.getConfiguration().debug_mode if debug_mode: open(join(Globals.INSTANCE_HOME,'var', out_fn + ".html"), "w").write(ar_results) pisa.showLogging() ramdisk = StringIO() pdf = pisa.CreatePDF(ar_results, ramdisk) pdf_data = ramdisk.getvalue() ramdisk.close() if debug_mode: open(join(Globals.INSTANCE_HOME,'var', out_fn + ".pdf"), "wb").write(pdf_data) mime_msg = MIMEMultipart('related') mime_msg['Subject'] = self.get_mail_subject() mime_msg['From'] = formataddr( (encode_header(laboratory.getName()), laboratory.getEmailAddress())) mime_msg['To'] = formataddr( (encode_header(self.contact.getFullname()), self.contact.getEmailAddress())) mime_msg.preamble = 'This is a multi-part MIME message.' msg_txt = MIMEText(ar_results, _subtype='html') mime_msg.attach(msg_txt) if not pdf.err: part = MIMEBase('application', "application/pdf") part.add_header('Content-Disposition', 'attachment; filename="%s.pdf"' % out_fn) part.set_payload( pdf_data ) Encoders.encode_base64(part) mime_msg.attach(part) try: host = getToolByName(self.context, 'MailHost') host.send(mime_msg.as_string(), immediate=True) except SMTPServerDisconnected, msg: if not debug_mode: raise SMTPServerDisconnected(msg) except SMTPRecipientsRefused, msg: raise WorkflowException(str(msg)) if self.action == 'publish': for ar in self.batch: try: workflow.doActionFor(ar, 'publish') except WorkflowException: pass ## if not pdf.err: ## setheader = self.request.RESPONSE.setHeader ## setheader('Content-Type', 'application/pdf') ## setheader("Content-Disposition", "attachment;filename=\"%s.pdf\"" % out_fn) ## self.request.RESPONSE.write(pdf_data) else: raise Exception, "XXX pub_pref %s" % self.pub_pref
def generate_pdf(html_content, path_out): pisa.showLogging() with open(path_out, 'wb') as fw: pisaStatus = pisa.CreatePDF(html_content, dest=fw) return pisaStatus.err
def mainFunction(): # read rows from CSV file rowsToProcess = [] with open('input/barcodes.csv', newline='') as csvFile: reader = csv.reader(csvFile) for row in reader: rowsToProcess.append(row) # print(row) print("csv has",len(rowsToProcess),"rows"); reportInfo["csvlines"] = len(rowsToProcess) exelIndex = 0; for row in rowsToProcess: exelIndex+=1 # attempt to select row data try: barcodeNumStr = row[0] barcodeNumInt = float(barcodeNumStr) pNumber = row[1] pNumberStr = pNumber.replace("/","") # for filenames. P180351B-M/XL becomes P180351B-MXL description = row[2] colour = row[3] except ValueError: print("ValueError trying to parse row", row) errorCollector( "row %s: ValueError trying to parse row: %s" % (exelIndex, row) ) continue; except: print("Unknown error trying to parse row", row) errorCollector( "row %s: Unknown error trying to parse row: %s" % (exelIndex, row) ) continue; try: with open('label_template.html', 'r') as myfile: thisBarcodeHTML = myfile.read(); except: print("Error reading label_template") errorCollector( "row %s: Error reading label_template" % (exelIndex) ) continue # replace placeholders thisBarcodeHTML = thisBarcodeHTML.replace("P_NUMBER_VALUE_HERE", pNumber) thisBarcodeHTML = thisBarcodeHTML.replace("COLOUR_VALUE_HERE", colour) thisBarcodeHTML = thisBarcodeHTML.replace("DESCRIPTION_VALUE_HERE", description[:40]) # description clipped to first 40 characters thisBarcodeHTML = thisBarcodeHTML.replace("BARCODE_VALUE_HERE", barcodeNumStr) outputFilename = "output/"+pNumberStr+".pdf" try: pisa.showLogging() convertHtmlToPdf(thisBarcodeHTML, outputFilename) reportInfo["successes"] +=1 except: print("error creating pdf", outputFilename) errorCollector( "row %s: Error creading pdf %s" % (exelIndex, outputFilename) ) continue print("created", outputFilename) reportWriter() print("finished with", reportInfo["successes"], "files created and", reportInfo["failures"], "errors. See report.txt for info") input("Press enter to finish...")
template = env.get_template('report_template.html') import csv import sys import os ROOT = lambda base : os.path.join(os.path.dirname(__file__), base).replace('\\','/') from operator import itemgetter from pychart import * from xhtml2pdf import pisa import cStringIO from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from smtplib import SMTP pisa.showLogging() reload(sys) sys.setdefaultencoding('utf-8') theme.default_font_size = 14 theme.use_color = True theme.get_options() theme.reinitialize() stock_text = { 'TOL1': '''-Students are cognitively and emotionally engaged by a rich topic with real-world importance.\n-Students get outside the walls of the classroom.\n-Students see a connection to their own lives and communities.\n-Students experience a sense of discovery.\n-Students reflect on their own learning process.\n-Students feel supported by their teachers, parents and mentors in the community.''', 'TOL2': '''-Students have freedom (choice, pace, time) within structure (materials, procedures, interaction with materials)\n-Students are completely engaged in a task.\n-Students develop curiosity grounded in knowledge.\n-Students are engaged in a prepared environment and allowed to act on their intrinsic nature to learn.''', 'TOL3': '''-Students experience collective pressure and support to meet behavioral and academic norms and expectations.\n -Students feel a sense of ongoing accomplishment for meeting commonly recognized benchmarks of mastery.\n-Students experience a highly consistent daily structure for how learning happens.\n-Students are in a highly structured environment with high behavioral expectations and consistent personal consequences for misbehaviors.\n-Students learn content that has been broken down into discrete pieces that are meant to be mastered in sequence and spiraled back to repeatedly until mastery has been achieved.\n-Students get many "at bats" to practice mastering content.\n-They get frequent and consistent feedback on mastery against absolute benchmarks.\n-Students feel a sense of urgency.''', 'TOL4': '''-Students collaborate explore answers to a complex question.\n-Students operate as a team to uncover the meaning of text or material.\n-Students exercise control (with reasonable limits and accountability) over the direction of a discussion.\n-Students ask difficult questions of each other.\n-Students subsume their own egos and self in favor of deeper understanding of the material, prioritizing self-monitoring of the discussion rather than trying to look smart.\n-Students make their own meaning and meeting their personal learning objectives.''',
def __call__(self): lab = self.context.bika_setup.laboratory self.lab_title = lab.getName() self.lab_address = lab.getPrintAddress() self.lab_email = lab.getEmailAddress() self.lab_url = lab.getLabURL() self.date = DateTime() client = logged_in_client(self.context) if client: self.client_title = client.Title() self.client_address = client.getPrintAddress() else: self.client_title = None self.client_address = None if client: clientuid = client.UID() else: clientuid = None username = self.context.portal_membership.getAuthenticatedMember().getUserName() self.reporter = pretty_user_name_or_id(self.context, username) self.reporter_email = pretty_user_email(self.context, username) report_id = self.request.form["report_id"] reporttype = "" if report_id == "analysesperservice": reporttype = "Analyses per service" self.reportout = AnalysesPerService(self.context, self.request)() elif report_id == "analysespersampletype": reporttype = "Analyses per sampletype" self.reportout = AnalysesPerSampleType(self.context, self.request)() elif report_id == "analysesperclient": reporttype = "Analyses per client" self.reportout = AnalysesPerClient(self.context, self.request)() elif report_id == "analysestats": reporttype = "Analyses TATs" self.reportout = AnalysesTats(self.context, self.request)() elif report_id == "analysestats_overtime": reporttype = "Analyses TATs over time" self.reportout = AnalysesTatsOverTime(self.context, self.request)() elif report_id == "analysesattachments": reporttype = "Analyses attachments" self.reportout = AnalysesAttachments(self.context, self.request)() elif report_id == "analysesoutofrange": reporttype = "Analyses out of range" self.reportout = AnalysesOutOfRange(self.context, self.request)() elif report_id == "analysesrepeated": reporttype = "Analyses repeated" self.reportout = AnalysesRepeated(self.context, self.request)() elif report_id == "arsnotinvoiced": reporttype = "ARs not invoiced" self.reportout = ARsNotInvoiced(self.context, self.request)() elif report_id == "resultspersamplepoint": reporttype = "Results per sample point" self.reportout = ResultsPerSamplePoint(self.context, self.request)() else: self.reportout = "no report to out" # this is the good part ramdisk = StringIO() pdf = pisa.CreatePDF(self.template(), ramdisk) result = ramdisk.getvalue() ramdisk.close() # write pdf to report object reportid = self.aq_parent.generateUniqueId("Report") self.aq_parent.invokeFactory(id=reportid, type_name="Report") report = self.aq_parent._getOb(reportid) report.edit(title=reporttype, ReportFile=result, ReportType=reporttype, Client=clientuid) report.processForm() report.reindexObject() if not pdf.err: setheader = self.request.RESPONSE.setHeader setheader("Content-Type", "application/pdf") self.request.RESPONSE.write(result) pisa.showLogging() return self.template()
pdfmetrics.registerFont(TTFont('yh', os.path.join(static_dir, "微软雅黑.ttf"))) DEFAULT_FONT['helvetica'] = 'yh' def convert_html2pdf(html, output_path): """ html -> pdf :param html: html path :param output_path: output path :return: """ # open output file for writing (truncated binary) with open(output_path, "wb+") as output_file: # convert HTML to PDF with open(html, 'rb') as html_file: pisa_status = pisa.CreatePDF(html_file.read(), dest=output_file, encoding='utf-8') # return True on success and False on errors return pisa_status.err if __name__ == '__main__': base_path = '/home/magician/Project/python3/data' html_path = base_path + '/test.html' out_path = base_path + '/test.pdf' pisa.showLogging() convert_html2pdf(html_path, out_path)
def __call__(self): pc = self.portal_catalog bc = self.bika_catalog bsc = self.bika_setup_catalog self.checkPermission = self.context.portal_membership.checkPermission self.now = DateTime() self.SamplingWorkflowEnabled = self.context.bika_setup.getSamplingWorkflowEnabled() # Client details (if client is associated) self.client = None client_uid = hasattr(self.context, 'getClientUID') and self.context.getClientUID() if client_uid: proxies = pc(portal_type='Client', UID=client_uid) if proxies: self.client = proxies[0].getObject() client_address = self.client.getPostalAddress() \ or self.contact.getBillingAddress() \ or self.contact.getPhysicalAddress() if client_address: _keys = ['address', 'city', 'state', 'zip', 'country'] _list = [client_address.get(v) for v in _keys if client_address.get(v)] self.client_address = "<br/>".join(_list).replace("\n", "<br/>") if self.client_address.endswith("<br/>"): self.client_address = self.client_address[:-5] else: self.client_address = None # Reporter self.member = self.context.portal_membership.getAuthenticatedMember() self.username = self.member.getUserName() self.reporter = self.user_fullname(self.username) self.reporter_email = self.user_email(self.username) self.reporter_signature = "" c = [x for x in self.bika_setup_catalog(portal_type='LabContact') if x.getObject().getUsername() == self.username] if c: sf = c[0].getObject().getSignature() if sf: self.reporter_signature = sf.absolute_url() + "/Signature" # laboratory self.laboratory = self.context.bika_setup.laboratory self.accredited = self.laboratory.getLaboratoryAccredited() lab_address = self.laboratory.getPrintAddress() if lab_address: _keys = ['address', 'city', 'state', 'zip', 'country'] _list = [lab_address.get(v) for v in _keys if lab_address.get(v)] self.lab_address = "<br/>".join(_list).replace("\n", "<br/>") if self.lab_address.endswith("<br/>"): self.lab_address = self.lab_address[:-5] else: self.lab_address = None # Analysis Request results self.ars = [] self.ar_headers = [_("Request ID"), _("Date Requested"), _("Sample Type"), _("Sample Point")] self.analysis_headers = [_("Analysis Service"), _("Method"), _("Result"), _("Analyst")] for ar in self.context.getAnalysisRequests(): datecreated = ar.created() datereceived = ar.getDateReceived() datepublished = ar.getDatePublished() datalines = [] for analysis in ar.getAnalyses(full_objects=True): service = analysis.getService() method = service.getMethod() sample = ar.getSample() result = analysis.getResult() try: precision = service.getPrecision() and service.getPrecision() or "2" result = float(result) formatted_result = str("%." + precision + "f")%result except: precision = "2" formatted_result = result datalines.append({_("Analysis Service"): analysis.getService().Title(), _("Method"): method and method.Title() or "", _("Result"): formatted_result, _("Analyst"): self.user_fullname(analysis.getAnalyst()), _("Remarks"): analysis.getRemarks()}) self.ars.append({ _("Request ID"): ar.getRequestID(), _("Date Requested"): self.ulocalized_time(datecreated), # requested->created _("Sample Type"): sample.getSampleType() and sample.getSampleType().Title() or '', _("Sample Point"): sample.getSamplePoint() and sample.getSamplePoint().Title() or '', _("datalines"): datalines, }) # Create Report fn = self.context.Title() + " " + self.ulocalized_time(self.now) report_html = self.template() debug_mode = App.config.getConfiguration().debug_mode if debug_mode: open(os.path.join(Globals.INSTANCE_HOME,'var', fn + ".html"), "w").write(report_html) pisa.showLogging() ramdisk = StringIO() pdf = pisa.CreatePDF(report_html, ramdisk) pdf_data = ramdisk.getvalue() ramdisk.close() if debug_mode: open(os.path.join(Globals.INSTANCE_HOME,'var', fn + ".pdf"), "wb").write(pdf_data) # Email to who? # Send PDF to browser if not pdf.err: setheader = self.request.RESPONSE.setHeader setheader('Content-Type', 'application/pdf') setheader("Content-Disposition", "attachment;filename=\"%s\""%fn) self.request.RESPONSE.write(pdf_data)