def test_issue_140_empty_cookie_value(self): roptions_bad = { '--page-size': 'Letter', 'cookie': [ ('test_cookie1', ''), ('test_cookie2', 'cookie_value2'), ] } roptions_good = { '--page-size': 'Letter', 'cookie': [ ('test_cookie1', '""'), ('test_cookie2', 'cookie_value2'), ] } r1 = pdfkit.PDFKit('html', 'string', options=roptions_bad) self.assertRaises(AssertionError, r1.to_pdf) r2 = pdfkit.PDFKit('html', 'string', options=roptions_good) output2 = r2.to_pdf() self.assertEqual(output2[:4].decode('utf-8'), '%PDF')
def test_verbose_option(self): options = {'outline': '', 'footer-line': None, 'quiet': True} r = pdfkit.PDFKit('html', 'string') cmd = r.command() self.assertTrue('--quiet' in cmd) r = pdfkit.PDFKit('html', 'string', options=options) cmd = r.command() self.assertTrue('--quiet' in cmd)
def test_lists_of_input_args(self): urls = ['http://ya.ru', 'http://google.com'] paths = ['fixtures/example.html', 'fixtures/example.html'] r = pdfkit.PDFKit(urls, 'url') r2 = pdfkit.PDFKit(paths, 'file') cmd = r.command() cmd2 = r2.command() self.assertEqual(cmd[-3:], ['http://ya.ru', 'http://google.com', '-']) self.assertEqual( cmd2[-3:], ['fixtures/example.html', 'fixtures/example.html', '-'])
def generate_pdf(html, directory, filename): pdfkit_settings = { 'dpi': '96', 'image-dpi': '3500', 'image-quality': '94', 'page-size': 'A4', 'encoding': "UTF-8", 'margin-top': '1cm', 'margin-bottom': '1cm', 'margin-right': '1cm', 'margin-left': '1cm', 'quiet': '', 'disable-smart-shrinking': '', 'footer-left': '[page] of [topage]' } if platform.system() == 'Windows': configuration = pdfkit.configuration(wkhtmltopdf=os.path.join( os.path.dirname(__file__), 'wkhtmltox', 'bin', 'wkhtmltopdf.exe')) elif platform.system() == 'Linux': configuration = pdfkit.configuration(wkhtmltopdf=os.path.join( os.path.dirname(__file__), 'wkhtmltopdf.sh')) else: configuration = pdfkit.configuration() if directory and not os.path.exists(directory): os.makedirs(directory) with open(os.path.join(directory, filename), 'wb') as pdf_file: pdf_file.write( pdfkit.PDFKit(html, "string", options=pdfkit_settings, configuration=configuration).to_pdf())
def test_repeatable_options(self): roptions = { '--page-size': 'Letter', 'cookies': [ ('test_cookie1', 'cookie_value1'), ('test_cookie2', 'cookie_value2'), ] } r = pdfkit.PDFKit('html', 'string', options=roptions) test_command = r.command('test') idx1 = test_command.index( '--page-size') # Raise exception in case of not found self.assertTrue(test_command[idx1 + 1] == 'Letter') self.assertTrue(test_command.count('--cookies') == 2) idx2 = test_command.index('--cookies') self.assertTrue(test_command[idx2 + 1] == 'test_cookie1') self.assertTrue(test_command[idx2 + 2] == 'cookie_value1') idx3 = test_command.index('--cookies', idx2 + 2) self.assertTrue(test_command[idx3 + 1] == 'test_cookie2') self.assertTrue(test_command[idx3 + 2] == 'cookie_value2')
def generateProductCatalog(products, filename): template_src = 'product/product_catalog.html' #template = get_template(template_src) html = template.render(products) options = { 'quiet': '', 'margin-top': '0in', 'margin-right': '0in', 'margin-bottom': '0in', 'margin-left': '0in', 'no-outline': None, } config = pdfkit.configuration(wkhtmltopdf=settings.WKHTMLTOPDFPATH) contentString = "attachment; filename=" + filename pdf = pdfkit.PDFKit(html, "string", options=options, configuration=config).to_pdf() response = HttpResponse(pdf) response['Content-Type'] = 'application/pdf' response['Content-disposition'] = contentString return response
def download_pdf(request, certificate_id): options = { 'page-size': 'A4', 'margin-top': '0.55in', 'margin-right': '0.55in', 'margin-bottom': '0.55in', 'margin-left': '0.55in', 'encoding': "UTF-8", # any other wkhtmltopdf options } results = get_object_or_404(Certificate, id=certificate_id) content = render_to_string( 'certificate/pdf_certificate.html', { 'cert': results } ) config = pdfkit.configuration(wkhtmltopdf='C:/Program Files/wkhtmltopdf/bin/bin/wkhtmltopdf.exe') pdf = pdfkit.PDFKit(content, "string", options=options, configuration=config).to_pdf() response = HttpResponse(pdf) response['Content-Type'] = 'application/pdf' pdf_name = str(results.leave_date) + "-" + results.user.first_name + "-" + str(results.leave_hour) # change attachment to attachment if you want open file in browser tab instead downloading response['Content-disposition'] = 'attachment;filename={}.pdf'.format(pdf_name) return response
def convert_into_pdf_stream(string_array, options=None): if not options: options = dict() options.update({'quiet': ''}) bytes_array = pdfkit.PDFKit(string_array, 'string', options=options).to_pdf() return bytes_array
def test_toc_handling_without_options(self): r = pdfkit.PDFKit('hmtl', 'string', toc={'xsl-style-sheet': 'test.xsl'}) self.assertEqual(r.command()[1], '--quiet') self.assertEqual(r.command()[2], 'toc') self.assertEqual(r.command()[3], '--xsl-style-sheet')
def test_options_parsing_with_dashes(self): r = pdfkit.PDFKit('html', 'string', options={'--page-size': 'Letter'}) test_command = r.command('test') idx = test_command.index( '--page-size') # Raise exception in case of not found self.assertTrue(test_command[idx + 1] == 'Letter')
def test_cover_without_options(self): r = pdfkit.PDFKit('html', 'string', cover='test.html') command = r.command() self.assertEqual(command[1], 'cover') self.assertEqual(command[2], 'test.html')
def test_options_parsing_with_tuple_no_dashes(self): options = {'custom-header': [('Accept-Encoding', 'gzip')]} r = pdfkit.PDFKit('html', 'string', options=options) command = r.command() idx1 = command.index( '--custom-header') # Raise exception in case of not found self.assertTrue(command[idx1 + 1] == 'Accept-Encoding') self.assertTrue(command[idx1 + 2] == 'gzip')
def test_outline_options(self): options = {'outline': None, 'outline-depth': 1} r = pdfkit.PDFKit('ya.ru', 'url', options=options) cmd = r.command() #self.assertEqual(cmd[1:], ['--outline', '--outline-depth', '1', 'ya.ru', '-']) self.assertIn('--outline', cmd) self.assertEqual(cmd[cmd.index('--outline-depth') + 1], '1')
def test_stylesheet_adding_to_the_head(self): #TODO rewrite this part of pdfkit.py r = pdfkit.PDFKit('<html><head></head><body>Hai!</body></html>', 'string', css='fixtures/example.css') with open('fixtures/example.css') as f: css = f.read() r._prepend_css('fixtures/example.css') self.assertIn('<style>%s</style>' % css, r.source.to_s())
def test_stylesheet_adding_without_head_tag(self): r = pdfkit.PDFKit('<html><body>Hai!</body></html>', 'string', options={'quiet': None}, css='fixtures/example.css') with open('fixtures/example.css') as f: css = f.read() r._prepend_css('fixtures/example.css') self.assertIn('<style>%s</style><html>' % css, r.source.to_s())
def convert_into_pdf_stream(string_array, options=None, css=None, config=None): if config: config = pdfkit.configuration(**config) if not options: options = dict() options.update({'quiet': ''}) bytes_array = pdfkit.PDFKit(url_or_file=string_array, type_='string', options=options, css=css, configuration=config).to_pdf() return bytes_array
def test_raise_error_if_bad_wkhtmltopdf_option(self): r = pdfkit.PDFKit('<html><body>Hai!</body></html>', 'string', options={'bad-option': None}) with self.assertRaises(IOError) as cm: r.to_pdf() raised_exception = cm.exception self.assertRegex( str(raised_exception), '^wkhtmltopdf exited with non-zero code 1. error:\nUnknown long argument --bad-option\r?\n' )
def test_command_construction(self): r = pdfkit.PDFKit('html', 'string', options={ 'page-size': 'Letter', 'toc-l1-font-size': 12 }) command = r.command() self.assertEqual(command[0], r.wkhtmltopdf) self.assertEqual(command[command.index('--page-size') + 1], 'Letter') self.assertEqual(command[command.index('--toc-l1-font-size') + 1], '12')
def test_cover_with_options(self): options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8" } r = pdfkit.PDFKit('html', 'string', options=options, cover='test.html') self.assertEqual(r.command()[1 + len(options) * 2], 'cover') self.assertEqual(r.command()[1 + len(options) * 2 + 1], 'test.html')
def test_multiple_stylesheets_adding_to_the_head(self): #TODO rewrite this part of pdfkit.py css_files = ['fixtures/example.css', 'fixtures/example2.css'] r = pdfkit.PDFKit('<html><head></head><body>Hai!</body></html>', 'string', css=css_files) css = [] for css_file in css_files: with open(css_file) as f: css.append(f.read()) r._prepend_css(css_files) self.assertIn('<style>%s</style>' % "\n".join(css), r.source.to_s())
def test_pdfkit_meta_tags(self): body = """ <html> <head> <meta name="pdfkit-page-size" content="Legal"/> <meta name="pdfkit-orientation" content="Landscape"/> </head> """ r = pdfkit.PDFKit(body, 'string') command = r.command() self.assertEqual(command[command.index('--page-size') + 1], 'Legal') self.assertEqual(command[command.index('--orientation') + 1], 'Landscape')
def test_multiple_stylesheet_adding_without_head_tag(self): css_files = ['fixtures/example.css', 'fixtures/example2.css'] r = pdfkit.PDFKit('<html><body>Hai!</body></html>', 'string', options={'quiet': None}, css=css_files) css = [] for css_file in css_files: with open(css_file) as f: css.append(f.read()) r._prepend_css(css_files) self.assertIn('<style>%s</style><html>' % "\n".join(css), r.source.to_s())
def test_raise_error_if_timeout_exceeded(self): r = pdfkit.PDFKit('<html><body>Hai!</body></html>', 'string', options={'bad-option': None}) timeout = 0.1 if sys.platform == 'win32': fake_command = ['timeout', str(timeout + 5)] else: fake_command = ['sleep', str(timeout + 5)] r.command = lambda _: fake_command with self.assertRaises(IOError) as cm: r.to_pdf(timeout=timeout) raised_exception = cm.exception self.assertRegex(str(raised_exception), '^Command exceeded timeout.*')
def pdf_pdfkit(request): mac = get_mac() if request.POST: data_mathml = request.POST.get("data_mathml", False) data_mathml = ast.literal_eval(data_mathml) print(data_mathml) data_mathml = [n.strip() for n in data_mathml] data_mathml = "<br><br>".join(data_mathml) print(data_mathml) # template = get_template('pdf/pdf_template.html') img_html = """ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <head> <title>Mathedemo</title> <meta charset="utf-8"> <script type="text/x-mathjax-config"> MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}}); </script> <script type="text/javascript" src="http://localhost:80/static/main/js/mathjax/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> </head> <body style="margin: 50px; font-size: 30px; color: white;"> <div style="color: black"> %s </div> </body> </html> """ img_html = img_html % data_mathml path_img = "/tmp/" + str(mac) + "img_out.png" img_generate = imgkit.from_string(img_html, path_img) template = get_template("pdf/pdf_template.html") nhtml = template.render({"img_path": path_img}) # pdf = pdfkit.from_file("templates/pdf/pdf_template.html", "output.pdf") pdf = pdfkit.PDFKit(img_html, "string").to_pdf() response = HttpResponse(pdf) response['Content-Type'] = 'application/pdf' response[ 'Content-Disposition'] = 'inline;filename=presentacion_ecuaciones.pdf' return response # returns the response. else: raise Http404("Not found")
def pdf2(request): if request.POST: nhtml = """ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="http://fred-wang.github.io/mathml.css/mspace.js"></script> <script src="http://fred-wang.github.io/mathjax.js/mpadded.js"></script> <script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML"></script> </head> <body style="margin: 60px; font-size: 25px"> %s </body> </html> """ data_mathml = request.POST.get("data_mathml", False) print(data_mathml) try: if data_mathml: data_mathml = ast.literal_eval(data_mathml) print(data_mathml) data_mathml = [n.strip() for n in data_mathml] print(data_mathml) print(data_mathml) data_mathml = data_mathml.replace( '<math>', '<math xmlns="http://www.w3.org/1998/Math/MathML">') print(data_mathml) nhtml = nhtml % data_mathml print(nhtml) pdf = pdfkit.PDFKit(nhtml, "string").to_pdf() response = HttpResponse( pdf) # Generates the response as pdf response. response['Content-Type'] = 'application/pdf' response['Content-Disposition'] = 'filename=output.pdf' return response # returns the response. else: raise Http404("Not found") except Exception as e: print(e) raise Http404("Not found") else: return render(request, 'main/index.html', {})
def test_toc_with_options(self): options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8" } r = pdfkit.PDFKit('html', 'string', options=options, toc={'xsl-style-sheet': 'test.xsl'}) self.assertEqual(r.command()[1 + len(options) * 2], 'toc') self.assertEqual(r.command()[1 + len(options) * 2 + 1], '--xsl-style-sheet')
def test_cover_and_toc(self): options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8" } r = pdfkit.PDFKit('html', 'string', options=options, toc={'xsl-style-sheet': 'test.xsl'}, cover='test.html') command = r.command() self.assertEqual(command[-7:], [ 'toc', '--xsl-style-sheet', 'test.xsl', 'cover', 'test.html', '-', '-' ])
def download_analytics(request, *args, **kwargs): template = 'reports/report_analytics_summary.html' data_from = request.GET.get('from') data_to = request.GET.get('to') state_code = request.GET.get('state') messages = [] successfull = True # tracking_ids = Tracking.objects.filter(created_at__range=[data_from, data_to]).values_list('report_id', flat=True) # tracking = Tracking.objects.filter(created_at__range=[data_from, data_to]) # reports = Reports.objects.filter(id__in=tracking_ids) #reports = Reports.objects.filter(data__today__range=[data_from, data_to]) trackings = Tracking.objects.filter( created_at__range=[data_from, data_to]).values_list('report_id', flat=True) #Add check and exception here state_id = BoundaryStateCode.objects.get(char_id=state_code).boundary_id state = Boundary.objects.get(id=state_id) reports = Reports.objects.filter(id__in=trackings).filter(state=state_id) data = { 'district_level': getDistrictLevel(reports), 'block_level': getBlockLevel(reports), 'cluster_level': getClusterLevel(reports), 'top_summary': getTopSummary(reports), 'by_type': getByReportType(reports), 'by_user': getByUser(trackings), 'state_name': state.name, 'state_code': state } options = { 'encoding': 'utf-8', } # pdf = pdfkit.PDFKit(html, 'string', configuration=config, options=options).to_pdf() html = render_to_string(template, {'data': data}) config = pdfkit.configuration() pdf = pdfkit.PDFKit(html, 'string', configuration=config, options=options).to_pdf() response = HttpResponse(pdf, content_type="application/pdf") response[ 'Content-Disposition'] = 'inline; filename=' + 'REPORTANALYTICS.pdf' return response
def download_analytics(request): template = 'reports/report_analytics_summary.html' data_from = request.GET.get('from') data_to = request.GET.get('to') messages = [] successfull = True reports = Reports.objects.filter(data__today__range=[data_from, data_to]) data = { 'district_level': getDistrictLevel(reports), 'block_level': getBlockLevel(reports), 'cluster_level': getClusterLevel(reports), 'top_summary': getTopSummary(reports), 'by_user': getByReportType(reports) } html = render_to_string(template, {'data': data}) config = pdfkit.configuration() pdf = pdfkit.PDFKit(html, 'string', configuration=config).to_pdf() response = HttpResponse(pdf, content_type="application/pdf") response[ 'Content-Disposition'] = 'inline; filename=' + 'REPORTANALYTICS.pdf' return response
def generate(): options = { 'footer-right': '[page]' } if request.form.get('pagenumbers') == 'true' else None toc = { 'xsl-style-sheet': 'toc.xsl' } if request.form.get('toc') == 'true' else None cover_file = False if request.files.get('cover'): cover_file = tfile.NamedTemporaryFile(mode="w+", suffix=".html", prefix="cover") cover_file.write( request.files.get('cover').read().decode("ISO-8859-1")) cover_file.flush() cover = cover_file.name if cover_file else None pdf = pdfkit.PDFKit(request.files.get('file').read().decode("ISO-8859-1"), 'string', options=options, cover=cover, toc=toc, cover_first=True).to_pdf() response = make_response(pdf) response.headers.set('Content-Type', 'application/pdf') response.headers.set('Content-Disposition', 'attachment', filename=request.form.get('filename')) if cover_file: cover_file.close() return response