Django: Generate PDFs - django

I am currently building a ticketing page using Django. I now have to find the 'best way' to generate a PDF ticket, which ticket buyers can download from our Server.
I looked into different ways and apps including ReportLab in the official documentation. The ticket will include personal information and I am also planning to include a Bar/QR code on the ticket. The question I am struggling with, is which of the available apps is for my purpose the best option. From my first understanding, ReportLab might not be the best solution and I might better generate the ticket from a HTML page.
Before I now dig deeper in documentations I wanted to ask you guys if you have some experience with my objective and can give me some recommendations?

In my case I've used wkhtmltopdf and pdfkit.
Read: https://learnbatta.com/blog/django-html-to-pdf-using-pdfkit-and-wkhtmltopdf-5/

If you want to generate pdf from an HTML page I would suggest you use PhantomJS for this.
Open URL in a subprocess using PhantomJS and direct output to the STDOUT:
import subprocess
proc = subprocess.Popen(
['phantomjs', 'rasterize.js', url, '/dev/stdout'],
stdout=subprocess.PIPE
)
Then create pdf from the STDOUT output:
import io
from PIL import Image
from tempfile import TemporaryFile
with TemporaryFile() as temp_pdf:
img = Image.open(io.BytesIO(proc.stdout.read()))
if img.mode == 'RGBA':
img = img.convert('RGB')
img.save(temp_pdf, "PDF", quality=100)

Related

How to turn a Django webpage into a PDF

I would like to add a feature to my Django website where the user can click on a link saying "Save as PDF". I would like this link to 1) produce a slightly different version of the page the user is currently on and 2) generate a PDF file in a separate window that the user can then save to wherever he or she wants.
All of the PDF functions I came across related to Django assumed that you already had a PDF that you wanted to render. In this case though, I want to create a PDF based on the content of the current page. Any idea how to do this? Thank you.
You can try this tool WeasyPrint. You can use it with Django
Any webpage is just a HTML basically so any html to pdf library would work. But this one is specifically built for django. Hope this helps.
Documentation for django-wkhtmltopdf

Retrieve PDF file generated on the fly and embedded in a HTML page

I am trying to retrieve a PDF file embedded in a HTML page using Python 2.7. I have tried using urllib and BeautifulSoup, but with no success. My problem is that I can't find any PDF link when I display the source code of the page.
Here is an example of the PDF I am trying to download : link.
How can I download this file on my computer using Python ?
EDIT : I just realized that the PDF is probably generated on the fly. Is it even possible to automatically download this type of file ?
Ciao,
thats my working solution:
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import pyautogui
browser = webdriver.Firefox()
browser.get('your-link') # Load page
browser.find_element_by_id('download').click() # here I press the download button of the PDF
time.sleep(0.5)
pyautogui.hotkey('enter')
time.sleep(0.5)
pyautogui.hotkey('enter')
browser.close()

How to begin creating a web application using a Python and xlrd/django script?

I'm not sure where to begin, as in do I start working towards PHP, Ruby or what, but here is what I'd like to do:
I have a Python script that takes a pre-formatted Excel document and using xlrd and Django, I output a nicely formatted HTML page, based on a template HTML page.
But currently on my team, I'm the only one that can use this Python script because our setups, and I'd like to simplify the process by creating a web app that has a couple drop down menus to specify which script to run, then let me upload the .xls file, at which point the HTML file is automatically generated and a download link is created or the HTML file is spit out somehow.
Does anyone have any guidance as to how I should even begin this project?
I would suggest having a good read of the django docs, and probably working through the tutorials.
Django's documentation is very good.
If you just want to hack at the code you've got then probably read the following to get a very basic overview of some core django functionality -
url dispatcher
views
models
forms
templating
With your app, the url dispatcher will pass the request to a view which will use a template to render your excel document.
You want a form to handle your user parameters and a single view to render and process the form and also render the excel template.

Django file upload via API

I'm new to django and been designing some basic models that contain FileFields.
Here is an example of my model:
class Sample(models.Model):
pub_date = models.DateTimeField('Publish Date', default=datetime.now)
upfile = models.FileField(upload_to='samples/')
I have tested the file upload via admin, but now I'm looking for other solutions to submit files via REST API. My first searches lead to Piston but most examples don't seem to involve models, only file upload to websites.
My objective is to parse directories, for example with os.walk, and submit the files and fill the model with the file info.
That said I'm looking for suggestions and leads in order to start investigating.
Thanks in advance!
You probably shouldn't be looking to piston for new builds anymore. It's essentially unmaintained and has been for a while now. django-tastypie and django-rest-framework are your best bets, although there's also a bunch of less fully featured frameworks cropping up.
REST framework supports standard form-encoded file uploads, see http://django-rest-framework.org/api-guide/fields.html#filefield
I'm not sure about tastypie's support for file uploads.
I've went back to the basics and decided to try creating a local script that reads calls File and the Sample Model. Since I will submit files directly from the same server, this solution immensely more simple than using a REST API, which delivers more flexibility than what I need.
This was my solution:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import sys
sys.path.append('/opt/proj')
sys.path.append('/opt/proj/web')
from django import db
from django.core.files import File
from django.utils import timezone
from web.myapp.models import Sample
filesample = File(open(sys.argv[1],'rb'))
filesample.name = os.path.basename(filesample.name)
Sample(upfile=filesample, pub_date=timezone.now()).save()
Looking back this was incredibly simple, but I hope it can help someone with the same problem.
Feel free to comment.
Thanks!

Django - Flickr feed without sync

I want to show the latest 8 images from a Flickr photostream using Django. I've had a good google and the only articles I can find focus on syncing the results with a database. I'd rather not do this if possible, I just want to show the images and nothing else.
http://code.djangoproject.com/wiki/FlickrIntegration This page has some adaptable code, but the library he uses seems to be offline now.
Does anyone have any examples of how I might integrate with a flickr stream without syncing the results?
Why can't you just use the flickr API from Python? There's probably python packages to do it. All you do is get the user's photostream info, map the photos to URLS:
http://www.flickr.com/services/api/flickr.people.getPhotos.html
Then your Django template just has an <img> tag with the right URL.
Edit: python packages listed on the flickr API page:
http://stuvel.eu/flickrapi
http://code.google.com/p/flickrpy/
I made Flickr Pony for use Flickr with Django Storage API and more.
You'll only need an API KEY and launch this:
>>> from flickr_pony.storage import FlickrStorage
>>> storage = FlickrStorage(api_key="myApiKey")
>>> storage.listdir('140893176#N07')
([], ['https://farm2.staticflickr.com/1586/25309081103_518e989396_o.jpg',
'https://farm2.staticflickr.com/1623/25911906696_84c8cf31ae_o.jpg',
'https://farm2.staticflickr.com/1617/25637193860_98a08d224f_o.jpg',
...
'https://farm2.staticflickr.com/1671/25794942526_5b54c8a908_o.jpg',
'https://farm2.staticflickr.com/1653/25820730145_4040532d03_o.jpg'])