def generate_pdf_view(request): try: # create an API client instance client = pdfcrowd.Client("mjnasir", "a90dfc17a16777af1087a5b00e88b5c2") # convert a web page and store the generated PDF to a variable ro_number = request.GET.get("ro_number") dealer_id = request.session["dealer_id"] url = request.GET.get("url") # url_str = "https://greenlightautomotive.com/app/flagger/action_plan_pdf/?roNumber=" +str(ro_number)+"&dealer_code=infiniti-0134&dealer_id="+str(dealer_id) url_str = settings.SITE_MAIN_URL + reverse( "flagging:action_plan_pdf") + "?roNumber=" + str( ro_number) + "&dealer_id=" + str(dealer_id) print url_str pdf = client.convertURI(url_str) # render(request,"flagging_app/action_plan_pdf") # set HTTP response headers response = HttpResponse(content_type="application/pdf") response["Cache-Control"] = "max-age=0" response["Accept-Ranges"] = "none" response[ "Content-Disposition"] = "attachment; filename=action_plan.pdf" # send the generated PDF response.write(pdf) except pdfcrowd.Error, why: print why response = HttpResponse(mimetype="text/plain") response.write(why)
def save_as_pdf(s): global i try: client = pdfcrowd.Client("mkap1234", "fc5ada9fbd1c55f46822d6e9e985a9bb") output_file = open('amazon'+str(i)+'.pdf', 'wb') i=i+1 html=get_page(s) client.convertHtml(html, output_file) output_file.close() except pdfcrowd.Error,why: print 'Failed:', why
def send_travel(message): print message chat_id = message.chat.id name = message.chat.first_name html = "<h1>Thank you," + name + "</h1>" html += "<p>You have just bought your ticket</p>" html += "<p>Hope you enjoy your travel</p>" html += "<p>Best,<br/></p>" _input = os.path.dirname(os.path.realpath(__file__)) + '/file1.html' output = os.path.dirname(os.path.realpath(__file__)) + '/hola.pdf' try: bot.send_message(chat_id, 'I\'m genereting your recepit. Please be patient ;)') # create an API client instance client = pdfcrowd.Client(PDFCROWD_USERNAME, PDFCROWD_KEY) # convert a web page and store the generated PDF into a pdf variable #pdf = client.convertURI('http://www.google.com') # convert an HTML string and save the result to a file output_file = open('html.pdf', 'wb') name = message.chat.first_name html = "<h1>Thank you," + name + "</h1>" html += "<p>You have just bought your ticket</p>" html += "<p>Hope you enjoy your travel</p>" html += "<p>Best,<br/></p>" client.convertHtml(html, output_file) output_file.close() #f = open('tarjeta.png', 'rb') # some file on local disk f = open('html.pdf', 'rb') # some file on local disk response = bot.send_document(chat_id, f) #pprint(response) # convert an HTML file #output_file = open('file.pdf', 'wb') #client.convertFile('/path/to/MyLayout.html', output_file) #output_file.close() except pdfcrowd.Error, why: bot.send_message( chat_id, 'Sorry! I fail this time. We\'re goint to write you an email with the recepeit' ) print('Failed: {}'.format(why))
def save_as_pdf(link, fileName): try: # we can get user id and toeken by registering on pdfcrowd.com client = pdfcrowd.Client("USER_ID", "TOKEN") output_file = open(fileName, 'wb') page = requests.get(link) soup = BeautifulSoup(page.text) html = soup.find_all('div', {'class': 'container'}) client.convertHtml(''.join(map(str, html)), output_file) output_file.close() print fileName, " saved" except pdfcrowd.Error, why: print 'Failed:', why
def save_as_pdf(s): global ii try: print("entered save as pdf") client = pdfcrowd.Client("mkap1234", "fc5ada9fbd1c55f46822d6e9e985a9bb") output_file = open('amazon' + str(ii) + '.pdf', 'wb') ii += 1 print("calling getpage", s) html = get_page(s) print("html", html) client.convertHtml(html, output_file) output_file.close() except pdfcrowd.Error as why: print('Failed:', why)
def generate_receipt(message): print message chat_id = message.chat.id username = message.chat.username firstName = message.chat.first_name print firstName bot.send_location(chat_id, '20', '20') filename = '-' + firstName + '_' + username + '_bill.pdf' input_html = os.path.dirname( os.path.realpath(__file__)) + '/static/bill.html' output_pdf = os.path.dirname(os.path.realpath(__file__)) + filename try: bot.send_chat_action(chat_id, 'typing') bot.send_message(chat_id, 'I\'m genereting your recepit. Please be patient ;)') client = pdfcrowd.Client(PDFCROWD_USERNAME, PDFCROWD_KEY) # create an API client instance # Get a file-like object for the Python Web site's home page. f = urllib.urlopen(input_html) # Read from the object, storing the page's contents in 's'. htmlPage = f.read() f.close() service = 'Travel from madrid to Barcelona' price = 30 quantity = 3 total = price * quantity htmlPage = htmlPage % (service, price, quantity, total, total) output_file = open(output_pdf, 'wb') client.convertHtml(htmlPage, output_file) output_file.close() f = open(output_pdf, 'rb') # some file on local disk response = bot.send_document(chat_id, f) f.close() except pdfcrowd.Error, why: bot.send_message( chat_id, 'Sorry! I fail this time. We\'re goint to write you an email with the recepeit' ) print('Failed: {}'.format(why))
def save_as_pdf(s): try: m = re.search('http://www.geeksforgeeks.org/(.+?)/', s) if m: filename = m.group(1) else: filename = ''.join(choice(ascii_uppercase) for i in range(12)) client = pdfcrowd.Client(dotenv.get('akhileshk'), dotenv.get('api-key')) output_file = open('BST_' + filename + '.pdf', 'wb') html = get_page(s) client.convertHtml(html, output_file) output_file.close() except pdfcrowd.Error, why: print 'Failed: ', why
def post(self, request, *args, **kwargs): # create an API client instance client = pdfcrowd.Client("username", "apikey") # convert a web page and store the generated PDF to a variable pdf = client.convertFile( "/home/raghu/ticketing/ticket/templates/hello.html") response = HttpResponse(mimetype="application/pdf") response["Cache-Control"] = "max-age=0" response["Accept-Ranges"] = "none" response["Content-Disposition"] = "attachment; filename=google_com.pdf" response.write(pdf) response = HttpResponse(mimetype="text/plain") return response
def save_as_pdf(link, filename): try: client = pdfcrowd.Client("MayankPratap", "28d53cddfd1b63f50748fd6c58ad0646") output_file = open(filename, 'wb') page = requests.get(link) soup = BeautifulSoup(page.text) html = soup.find_all('div', {'class': 'container'}) client.convertHtml(''.join(map(str, html)), output_file) output_file.close() print filename, " saved" except pdfcrowd.Error, why: print "Failed:", why
def pdf_view(request): # create an API client instance client = pdfcrowd.Client("niti", "896b4517ed9216d9932c6147a74fd3ba") # convert a web page and store the generated PDF to a variable #pdf = client.convertURI("http://www.google.com") pdf = client.convertFile( r"C:\Users\spgna\Documents\Django project\askmeout\app\templates\base.html" ) # set HTTP response headers response = HttpResponse(content_type="application/pdf") response["Cache-Control"] = "max-age=0" response["Accept-Ranges"] = "none" response["Content-Disposition"] = "attachment; filename=google_com.pdf" # send the generated PDF response.write(pdf) return response
def get_payslip(user_profile): template_file = os.path.join(settings.PROJECT_DIR, os.path.pardir, "payroll/templates/payroll/payroll.html") template = Template(open(template_file, 'rb').read()) context = Context({ 'user_profile': user_profile, 'timezone': timezone.now().strftime("%B") }) html = template.render(context) try: client = pdfcrowd.Client(settings.PDF_USERNAME, settings.PDF_KEY) pdf = client.convertHtml(html.encode("utf-8")) except pdfcrowd.Error, why: buffer = BytesIO() p = canvas.Canvas(buffer) p.showPage() p.save() pdf = buffer.getvalue() buffer.close()
def generate_pdf_view(request): try: # create an API client instance client = pdfcrowd.Client("susahe", "31184c7f95430a5d528990c4a421a9c2") # convert a web page and store the generated PDF to a variable pdf = client.convertURI("http://www.google.com") # set HTTP response headers response = HttpResponse(mimetype="application/pdf") response["Cache-Control"] = "max-age=0" response["Accept-Ranges"] = "none" response["Content-Disposition"] = "attachment; filename=google_com.pdf" # send the generated PDF response.write(pdf) except pdfcrowd.Error, why: response = HttpResponse(mimetype="text/plain") response.write(why)
def generate_pdf_view(request): try: # create an API client instance client = pdfcrowd.Client("niti", "896b4517ed9216d9932c6147a74fd3ba") # convert a web page and store the generated PDF to a variable pdf = client.convertURI("http://www.google.com") #pdf = client.convertFile("base.html") # set HTTP response headers response = HttpResponse(content_type="application/pdf") response["Cache-Control"] = "max-age=0" response["Accept-Ranges"] = "none" response["Content-Disposition"] = "attachment; filename=google_com.pdf" # send the generated PDF response.write(pdf) except pdfcrowd.Error: response = HttpResponse(mimetype="text/plain") response.write(why) return response
def generate_pdf_view(request): try: # create an API client instance client = pdfcrowd.Client("Dosseh", "39481d764d9f5e5d4eb848f46dfa3ebd") # convert a web page and store the generated PDF to a variable pdf = client.convertURI("http://www.google.com") # set HTTP response headers response = HttpResponse(mimetype="application/pdf") response["Cache-Control"] = "max-age=0" response["Accept-Ranges"] = "none" response["Content-Disposition"] = "attachment; filename=google_com.pdf" # send the generated PDF response.write(pdf) except pdfcrowd.Error as why: response = HttpResponse(mimetype="text/plain") response.write(why) return response
def dashboard_multiple(request): user_logo = avatar_print_url(request.user, 200) urls = [] # data = request.POST data = json.loads(request.body) domainpath = request.META.get('HTTP_HOST') domainpath += '/v2' if re.match('^/v2', request.path) else '' v2_folder = '' headerparam_dict = { p: request.GET.get(p, '') for p in ['hideuserinfo', 'lang'] if p in request.GET } headerparam = urllib.urlencode(headerparam_dict) bodyparam_dict = {} bodyparam_dict['lang'] = request.GET.get('lang') or str( translation.get_language()) bodyparam = urllib.urlencode(bodyparam_dict) try: print request.META.get('HTTP_HOST'), request.META.get('PATH_INFO') date_string = dateformat.format(datetime.date.today(), "Y-m-d") # create an API client instance client = pdfcrowd.Client(getattr(settings, 'PDFCROWD_UNAME'), getattr(settings, 'PDFCROWD_UPASS')) client.setPageWidth('8.3in') client.setPageHeight('11.7in') # client.setPageMargins('1in', '1in', '1in', '1in') client.setVerticalMargin("0.75in") client.setHorizontalMargin("0.25in") client.setHeaderUrl('http://' + request.META.get('HTTP_HOST') + '/static/' + v2_folder + 'rep_header_vector.html?onpdf=' + user_logo['onpdf'] + '&userlogo=' + user_logo['logo_url'] + '&name=' + request.user.first_name + ' ' + request.user.last_name + '&cust_title=' + quote(data['mapTitle'].encode('utf-8')) + '&organization=' + request.user.organization + '&isodate=' + date_string + '&' + headerparam) # convert a web page and store the generated PDF to a variable # get map pdf req = urllib2.Request(data['mapUrl']) req.add_unredirected_header( 'User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36' ) fh = urllib2.urlopen(req) f = fh.read() merger = PdfFileMerger() merger.append(StringIO(f)) for i in data['urls']: if i is not None and i != '': # urls.append(str('http://'+domainpath+'/dashboard/print'+i+'&user='******'http://' + domainpath + '/dashboard/print' + i + '&user='******'&' + bodyparam)) merger.append(StringIO(pdf)) # set HTTP response headers # response = HttpResponse(content_type="application/pdf") # response["Cache-Control"] = "no-cache" # response["Accept-Ranges"] = "none" # response["Content-Disposition"] = 'attachment; filename="'+data['fileName']+'.pdf"' # send the generated PDF # merger.write(response) # return response merger.write( getattr(settings, 'PRINT_CACHE_PATH') + data['mapUrl'].split('/')[-1]) return HttpResponse(json.dumps( {'filename': data['mapUrl'].split('/')[-1]}), content_type='application/json') except pdfcrowd.Error, why: options = { 'quiet': '', 'page-size': 'A4', 'page-width': '2550px', 'page-height': '3300px', 'dpi': 300, # 'margin-left': 10, # 'margin-right': 10, 'margin-bottom': 10, 'margin-top': 25, # 'viewport-size':'800x600', 'header-html': 'http://' + request.META.get('HTTP_HOST') + '/static/' + v2_folder + 'rep_header.html?onpdf=' + user_logo['onpdf'] + '&userlogo=' + user_logo['logo_url'] + '&name=' + request.user.first_name + ' ' + request.user.last_name + '&cust_title=' + quote(data['mapTitle'].encode('utf-8')) + '&organization=' + request.user.organization + '&' + headerparam, # 'lowquality':'-', # 'disable-smart-shrinking':'-', # 'print-media-type':'-', # 'no-stop-slow-scripts':'-', # 'enable-javascript':'-', 'javascript-delay': 25000, # 'window-status': 'ready', 'encoding': "UTF-8", } # f = urllib.request.urlopen(data['mapUrl']).read() req = urllib2.Request(data['mapUrl']) req.add_unredirected_header( 'User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36' ) fh = urllib2.urlopen(req) f = fh.read() merger = PdfFileMerger() merger.append(StringIO(f)) for i in data['urls']: if i is not None and i != '': urls.append( str('http://' + domainpath + '/dashboard/print' + i + '&user='******'&' + bodyparam)) pdf = pdfkit.from_url(urls, False, options=options) merger.append(StringIO(pdf)) # resp = HttpResponse(pdf,content_type='application/pdf') # resp = HttpResponse(content_type="application/pdf") # resp["Cache-Control"] = "no-cache" # resp["Accept-Ranges"] = "none" # resp['Content-Disposition'] = 'attachment; filename="'+data['fileName']+'.pdf"' merger.write( getattr(settings, 'PRINT_CACHE_PATH') + data['mapUrl'].split('/')[-1]) return HttpResponse(json.dumps( {'filename': data['mapUrl'].split('/')[-1]}), content_type='application/json')
def dashboard_detail(request): v2_folder = '' user_logo = avatar_print_url(request.user, 200) headerparam_dict = { p: request.GET.get(p, '') for p in ['hideuserinfo', 'lang'] if p in request.GET } headerparam = urllib.urlencode(headerparam_dict) bodyparam_dict = {} if not request.GET.get('lang'): bodyparam_dict['lang'] = str(translation.get_language()) bodyparam = urllib.urlencode(bodyparam_dict) # add '?page=baseline' to url if none exist if not request.GET.get('page'): currenturl = request.build_absolute_uri() return redirect(set_query_parameter(currenturl, 'page', 'baseline')) if 'pdf' in request.GET: try: domainpath = 'asdc.immap.org' + request.META.get('PATH_INFO') date_string = dateformat.format(datetime.date.today(), "Y-m-d") # create an API client instance client = pdfcrowd.Client(getattr(settings, 'PDFCROWD_UNAME'), getattr(settings, 'PDFCROWD_UPASS')) client.setPageWidth('8.3in') client.setPageHeight('11.7in') # client.setPageMargins('1in', '1in', '1in', '1in') client.setVerticalMargin("0.75in") client.setHorizontalMargin("0.25in") client.setHeaderUrl( 'http://asdc.immap.org/static/isdc/head_print/rep_header_vector.html?onpdf=' + user_logo['onpdf'] + '&userlogo=' + user_logo['logo_url'] + '&name=' + request.user.first_name + ' ' + request.user.last_name + '&cust_title=&organization=' + (request.user.organization or '') + '&isodate=' + date_string + '&' + headerparam) # convert a web page and store the generated PDF to a variable pdf = client.convertURI('http://' + str(domainpath) + 'print?' + request.META.get('QUERY_STRING') + '&user='******'&' + bodyparam) # set HTTP response headers response = HttpResponse(content_type="application/pdf") response["Cache-Control"] = "no-cache" response["Accept-Ranges"] = "none" response[ "Content-Disposition"] = 'attachment; filename="' + request.GET[ 'page'] + '_' + date_string + '.pdf"' # send the generated PDF response.write(pdf) except pdfcrowd.Error, why: options = { 'quiet': '', 'page-size': 'A4', 'page-width': '2550px', 'page-height': '3300px', 'dpi': 300, # 'margin-left': 10, # 'margin-right': 10, 'margin-bottom': 10, 'margin-top': 25, # 'viewport-size':'800x600', 'header-html': 'http://' + request.META.get('HTTP_HOST') + '/static/isdc/head_print/rep_header_vector.html?onpdf=' + user_logo['onpdf'] + '&userlogo=' + user_logo['logo_url'] + '&name=' + request.user.first_name + ' ' + request.user.last_name + '&cust_title=&organization=' + (request.user.organization or '') + '&' + headerparam, # 'header-html': 'http://'+request.META.get('HTTP_HOST')+'/static/rep_header(v2).html?name='+request.user.first_name+'-'+request.user.last_name+'&cust_title=&organization='+request.user.organization, # 'lowquality':'-' # 'disable-smart-shrinking':'-', # 'print-media-type':'-', # 'no-stop-slow-scripts':'-', # 'enable-javascript':'-', # 'javascript-delay': 30000, # 'window-status': 'ready', } if re.match('^/v2', request.path): options['viewport-size'] = '1240x800' domainpath = request.META.get('HTTP_HOST') + request.META.get( 'PATH_INFO') url = 'http://' + str(domainpath) + 'print?' + request.META.get( 'QUERY_STRING') + '&user='******'&' + bodyparam pdf = pdfkit.from_url(url, False, options=options) date_string = dateformat.format(datetime.date.today(), "Y-m-d") response = HttpResponse(pdf, content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="' + request.GET[ 'page'] + '_' + date_string + '.pdf"' return response
import pdfcrowd try: # create an API client instance client = pdfcrowd.Client("susahe", "31184c7f95430a5d528990c4a421a9c2") # convert a web page and store the generated PDF into a pdf variable pdf = client.convertURI('http://www.google.com') # convert an HTML string and save the result to a file output_file = open('html.pdf', 'wb') html = "<head></head><body>My HTML Layout hi man i'm sumudu </body>" client.convertHtml(html, output_file) output_file.close() # convert an HTML file output_file = open('file.pdf', 'wb') client.convertFile('base.html', output_file) output_file.close() except pdfcrowd.Error, why: print('Failed: {}'.format(why))
# Demo program to show how to use the PDFcrowd API # to convert HTML content to PDF. # Author: Vasudev Ram - www.dancingbison.com import pdfcrowd try: # create an API client instance # Dummy credentials used; to actually run the program, enter your own. client = pdfcrowd.Client("user_name", "api_key") client.setAuthor('author_name') # Dummy credentials used; to actually run the program, enter your own. client.setUserPassword('user_password') # Convert a web page and store the generated PDF in a file. pdf = client.convertURI('http://www.dancingbison.com') with open('dancingbison.pdf', 'wb') as output_file: output_file.write(pdf) # Convert a web page and store the generated PDF in a file. pdf = client.convertURI( 'http://jugad2.blogspot.in/p/about-vasudev-ram.html') with open('jugad2-about-vasudevram.pdf', 'wb') as output_file: output_file.write(pdf) # convert an HTML string and save the result to a file output_file = open('html.pdf', 'wb') html = "My Small HTML File" client.convertHtml(html, output_file) output_file.close()
import pdfcrowd try: client = pdfcrowd.Client('snorthway','ea32e0248bb556ffa73e74e290731649') pdf = client.convertURI('http://serene-plains-1573.herokuapp.com/resume') with open('resume.pdf', 'w') as f: f.write(pdf) except pdfcrowd.Error, why: print 'failed', why
import pdfcrowd try: # create an API client instance client = pdfcrowd.Client("username", "apikey") # convert a web page and store the generated PDF into a pdf variable pdf = client.convertURI('http://www.google.com') # convert an HTML string and save the result to a file output_file = open('html.pdf', 'wb') html = "<head></head><body>My HTML Layout</body>" client.convertHtml(html, output_file) output_file.close() # convert an HTML file output_file = open('file.pdf', 'wb') client.convertFile('teste.html', output_file) output_file.close() except pdfcrowd.Error, why: print('Failed: {}'.format(why))
def dashboard_detail(request): v2_folder = '' # user_logo = avatar_print_url(request.user,200) user_logo = {} headerparam_dict = {p: request.GET.get(p, '') for p in ['hideuserinfo','lang'] if p in request.GET} headerparam_dict.update({ 'onpdf': user_logo.get('onpdf'), 'userlogo': user_logo.get('logo_url'), 'name': request.user.first_name+' '+request.user.last_name, 'cust_title': '%s %s'%('Dashboard',request.GET.get('page', '').title()), 'organization': (request.user.organization or ''), }) headerparam = urllib.urlencode(headerparam_dict) bodyparam_dict = {} if not request.GET.get('lang'): bodyparam_dict['lang'] = str(translation.get_language()) bodyparam = urllib.urlencode(bodyparam_dict) # add '?page=baseline' to url if none exist if not request.GET.get('page'): currenturl = request.build_absolute_uri() return redirect(set_query_parameter(currenturl, 'page', 'baseline')) if 'pdf' in request.GET: try: domainpath = 'asdc.immap.org'+request.META.get('PATH_INFO') date_string = dateformat.format(datetime.date.today(), "Y-m-d") # create an API client instance client = pdfcrowd.Client(getattr(settings, 'PDFCROWD_UNAME', ''), getattr(settings, 'PDFCROWD_UPASS', '')) client.setPageWidth('8.3in') client.setPageHeight('11.7in') # client.setPageMargins('1in', '1in', '1in', '1in') client.setVerticalMargin("0.75in") client.setHorizontalMargin("0.25in") client.setHeaderUrl('http://asdc.immap.org/static/isdc/head_print/rep_header_vector.html?onpdf='+user_logo.get('onpdf','')+'&userlogo='+user_logo.get('logo_url','')+'&name='+request.user.first_name+'+'+request.user.last_name+'&cust_title=&organization='+(request.user.organization or '')+'&isodate='+date_string+'&'+headerparam) # convert a web page and store the generated PDF to a variable pdf = client.convertURI('http://'+str(domainpath)+'print?'+request.META.get('QUERY_STRING')+'&user='******'&'+bodyparam) # set HTTP response headers response = HttpResponse(content_type="application/pdf") response["Cache-Control"] = "no-cache" response["Accept-Ranges"] = "none" response["Content-Disposition"] = 'attachment; filename="'+request.GET['page']+'_'+date_string+'.pdf"' # send the generated PDF response.write(pdf) except pdfcrowd.Error, why: options = { # wkhtmltopdf settings # 'quiet': '', # 'page-size': 'A4', # 'page-width': '2550px', # 'page-height': '3300px', # 'dpi':300, # 'margin-left': 10, # 'margin-right': 10, # 'margin-bottom':10, # 'margin-top':25, # 'viewport-size':'800x600', # 'header-html': 'http://%s/static/isdc/head_print/rep_header.html?%s'%(request.META.get('HTTP_HOST'),headerparam), # 'header-html': 'http://'+request.META.get('HTTP_HOST')+'/static/rep_header(v2).html?name='+request.user.first_name+'-'+request.user.last_name+'&cust_title=&organization='+request.user.organization, # 'lowquality':'-' # 'disable-smart-shrinking':'-', # 'print-media-type':'-', # 'no-stop-slow-scripts':'-', # 'enable-javascript':'-', # 'window-status': 'ready', # pychrome settings # match screen to print layout and resolution as close as possible # in order for the map to scale correctly # for print debugging, uncomment ruler.png in custombase.html, # resolution in pixel, size in inches, time in seconds 'screen-width':1024, # resolution when loading the page 'screen-height':1024, # resolution when loading the page 'paperWidth':8.27, 'paperHeight':11.69, 'marginTop':0.78, 'marginBottom':0.45, 'marginLeft':0.3, 'marginRight':0.3, 'scale':0.71, # 0.71 roughly equal to 1024 px print width on 1024 screen-width 'after-document-loaded-delay': 1, # in seconds 'timeout': 60, # in seconds 'header-html': 'http://%s/static/epr_bgd/head_print/rep_header_chrome.html?%s'%(request.META.get('HTTP_HOST'),headerparam), 'headerparam':headerparam_dict, } # if re.match('^/v2', request.path): # options['viewport-size'] = '1240x800' domainpath = request.META.get('HTTP_HOST')+request.META.get('PATH_INFO') url = 'http://'+str(domainpath)+'print?'+request.META.get('QUERY_STRING')+'&user='******'&'+bodyparam # pdf = pdfkit.from_url(url, False, options=options) pdf = print_from_urls([url], print_option=options) date_string = dateformat.format(datetime.date.today(), "Y-m-d") response = HttpResponse(pdf,content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="'+request.GET['page']+'_'+date_string+'.pdf"' return response
browser.find_elements_by_class_name("pagedlist_item")) if loaded_answers_length == loaded_answers_length_new: count += 1 if count == 3: break else: loaded_answers_length = loaded_answers_length_new time.sleep(3) print "All answers loaded " html_source = browser.page_source return html_source, browser urls = [ "http://www.quora.com/What-are-the-best-Python-scripts-youve-ever-written", "http://www.quora.com/What-are-the-very-best-answers-on-Quora-as-chosen-by-the-Top-Writers-who-wrote-them", "http://www.quora.com/How-many-times-can-you-interview-with-Google-1", "http://www.quora.com/Im-writing-a-school-thesis-about-TDD-applied-to-web-applications-What-type-of-project-would-be-best-for-showcasing-TDD" ] url = urls[3] html, browser = get_browser_html(url) client = pdfcrowd.Client("username", "token") file_name = url.split('/')[-1] + '.pdf' output_file = open(file_name, 'wb') print "Converting to pdf..." client.enableJavaScript(False) pdf = client.convertHtml(html, output_file) output_file.close() print "File ", file_name, "created" browser.close()
#!/usr/bin/env python import pdfcrowd import sys if len(sys.argv) != 4: print(len(sys.argv)) print('required args: username apikey hostname') sys.exit(2) c = pdfcrowd.Client(*sys.argv[1:]) c.convertURI( 'http://dl.dropboxusercontent.com/u/9346438/tests/webtopdfcom.html') c.convertHtml('raw html') c.convertFile('./test_files/in/simple.html')
import pdfcrowd # create an API client instance client = pdfcrowd.Client("morningrain", "12ab704789a57360d41232b313ed80ed") # # convert a web page and store the generated PDF into a pdf variable # pdf = client.convertURI('http://www.google.com') # # # convert an HTML string and save the result to a file # output_file = open('html.pdf', 'wb') # html="<head></head><body>My HTML Layout</body>" # client.convertHtml(html, output_file) # output_file.close() # convert an HTML file output_file = open('scikit-learn文本挖掘系列 17-主题抽取.pdf', 'wb') client.convertFile('scikit-learn文本挖掘系列 17-主题抽取.html', output_file) output_file.close()
time.sleep(3) loaded_answers_length_new = len( browser.find_elements_by_class_name("pagedlist_item")) if loaded_answers_length == loaded_answers_length_new: count += 1 if count == 3: break else: loaded_answers_length = loaded_answers_length_new time.sleep(3) print "All answers loaded " html_source = browser.page_source return html_source, browser q = str(raw_input("paste question url here >>")) + "?ref=1" urls = [ q, ] url = urls[0] html, browser = get_browser_html(url) client = pdfcrowd.Client("vicodin", "f9c9879101395033866005dc0c83e1b3") file_name = url.split('/')[-1] + '.pdf' output_file = open(file_name, 'wb') print "Converting to pdf..." client.enableJavaScript(False) pdf = client.convertHtml(html, output_file) output_file.close() print "File ", file_name, "created" browser.close() #justchecking
# Closing the html and the file htmlResult.write('</body></html>') htmlResult.close() print '<><><> HTML created <><><>' winsound.Beep(2500, 100) # Removing the temporary file os.remove('tempAccessHTML.html') # This part converts the OUTPUT html into a PDF using pdfcrowd.com's API # you need a free pdfcrowd.com account. Use the given username and apikey print '<><><> Going for conversion of HTML to PDF <><><>' try: # create an API client instance client = pdfcrowd.Client(USERNAME, API_KEY) # convert an HTML file output_file = open(nameOfSubject + '.pdf', 'wb') client.convertFile(str(nameOfSubject + '.html'), output_file) output_file.close() print '<><><> Conversion Completed <><><>' except pdfcrowd.Error, why: print('Failed: {}'.format(why)) # Beep soung to indicate the completion winsound.Beep(2500, 100) winsound.Beep(2500, 100)
print("using %s ports %d %d" % (pdfcrowd.HOST, pdfcrowd.HTTP_PORT, pdfcrowd.HTTPS_PORT)) os.chdir(os.path.dirname(os.path.realpath(__file__))) test_dir = 'test_files' def out_stream(name, use_ssl): fname = test_dir + '/out/py_client_%s' % name if use_ssl: fname = fname + '_ssl' return open(fname + '.pdf', 'wb') html = "<html><body>Uploaded content!</body></html>" client = pdfcrowd.Client(sys.argv[1], sys.argv[2]) for use_ssl in [False, True]: client.useSSL(use_ssl) try: ntokens = client.numTokens() print('Current Tokens:', ntokens) client.setFooterText("%p out of %n") client.convertURI( 'http://dl.dropboxusercontent.com/u/9346438/tests/webtopdfcom.html', out_stream('uri', use_ssl)) client.convertHtml(html, out_stream('content', use_ssl))
import pdfcrowd #Initially, I wanted to save things as a pdf, but decided that using something #with an api that cost money was kind of worthless url = "https://www.webassign.net/login.html" try: client = pdfcrowd.Client("_ignoreme", "cec86c8baaf06622b256adea0b73f635") #todo create api key newpdf = client.convertURI('http://www.google.com') except pdfcrowd.Error, err: print("Failed to fetch PDF: {}".format(err))