Convert html to pdf django

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Convert HTML to pdf with django using phantomjs

License

ianvieira/django-pdf-generator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Convert HTML to pdf with django using phantomjs

  • Python (2.7) (Need to be tested for 3.x)
  • Django (1.10, 1.9) (Need to be tested for previous versions)
  • PhantomJS

pip install django_pdf_generator

Add pdf_generator to your INSTALLED_APPS setting.

INSTALLED_APPS = ( . 'pdf_generator', )

Add the pdf_generator urls below to your main urls.py

urlpatterns = [ . url(r'^pdf-generator/', include('pdf_generator.urls', namespace='pdf_generator')), .

Put phantomjs binary on your path or set the path manually in your settings using PHANTOMJS_BIN_PATH settings (see below).

Generate a PDF with PDFGenerator class

Generate a pdf from an url

from pdf_generator.generators import PDFGenerator pdf = PDFGenerator(url="https://github.com/charlesthk/django-pdf-generator",

Save it to the database using PdfDoc models :

pdf.save( filename='pdf_generator', title="pdf_generator on github", description="Convert HTML to pdf with django using phantomjs")

Get the PDF as a Django ContentFile named ‘my_pdf_file.pdf’ :

pdf_content_file = pdf.get_content_file('my_pdf_file') # Return a Django HttpResponse with the PDF Attached named 'my_pdf_file.pdf': return pdf.get_http_response('my_pdf_file')

Return a Django HttpResponse with the PDF Attached named ‘my_pdf_file.pdf’:

return pdf.get_http_response('my_pdf_file')

Generate a pdf just like Django render function :

url(r'^invoice$', views.invoice, name='invoice'),
from pdf_generator.renderers import render_pdf def invoice(request): """ Render an invoice The invoice.pdf file is returned """ return render_pdf('invoice', request, 'front/invoice.html')

Juste add ?html=1 to the url to view the HTML instead of getting the pdf file.

The PDFGenerator class accepts the following arguments :

  • url [required]
  • paperformat [Required] default to ‘A4’, examples: «5in7.5in», «10cm20cm», «A4», «Letter»
  • zoom [Optional] default to 1.
  • script [Optional] default to DEFAULT_RASTERIZE_SCRIPT, defines which render script to use.
  • temp_dir [Optional] default to DEFAULT_TEMP_DIR, defines which temp dir to use.

Model used for saving PDF

When using save(filename, title=», description=») method of PDFGenerator , the following model is used:

class PdfDoc(models.Model): """ Store each generated pdf """ title = models.CharField(verbose_name=_("Title"), max_length=255, blank=True) description = models.TextField(verbose_name=_("Description"), blank=True) document = models.FileField(verbose_name=_("Document PDF"), upload_to=pdf_settings.UPLOAD_TO) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, verbose_name=_('Creation')) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name=_('Update')) 

Add your settings to your main django settings file. The settings are set by default to :

Define the directory or the function to be used when saving PDFs, default to pdfs .

Define the path to Phantomjs binary, default to phantomjs .

Define which render_script to use by default, default to rasterize.js inside the package.

Define the directory to use for temporarily generated pdf by PhantomJS. default to pdf_temp .

Define the directory to use for temporarily generated HTML files by PhantomJS. default to pdf_temp .

If you are having issues, please let us know or submit a pull request.

The project is licensed under the MIT License.

About

Convert HTML to pdf with django using phantomjs

Источник

How to create a PDF from HTML in Django

Carlos Delgado

Learn how to create PDF files in Django from HTML using wkhtmltopdf.

How to create a PDF from HTML in Django

Unlike PHP, there are not a lot of available libraries to create PDFs from HTML in Python, however it is not unsupported. In this article, you’ll learn how to create PDFs using wkhtmltopdf in Django.

wkhtmltopdf is a command-line tool to render HTML into PDF and various image formats using the Qt WebKit rendering engine. These run entirely «headless» and do not require a display or display service.

Requirements

You need wkhtmltopdf available in your system and accessible in the command prompt.

  • Windows: you can download an installer for each architecture (x86 and x64) in the installation area. Although you can change the path of the wkhtmltopdf executable later in the code, is recommendable to have wkhtmltopdf accesible as an environment variable on your system. You can read how to create environment variables in windows in this article.
  • Debian/Ubuntu: You can install the distribution from wkhtmltopdf directly in the console using the following command :
$ sudo apt-get install wkhtmltopdf

Warning! The version in debian/ubuntu repos have reduced functionality (because it compiled without the wkhtmltopdf QT patches), such as adding outlines, headers, footers, TOC etc. To use these options you should install static binary from wkhtmltopdf site or you can use this script .

Implementation

Now that we have wkhtmltopdf available in our environment, we just need to use it! however, instead of handling console commands by yourself, use PDFKit to create PDFs easily in Django. PDFKit is a python wrapper to convert Html to pdf using the WebKit rendering engine (wkhtmltopdf) and qt, you can visit the repository in Github for more information.

Include the PDFKit library into your Django project using the following command :

As wkhtmltopdf does the hard work for you, the use of PDFKit is really simple and cover almost all the use cases :

#import pdfkit into your class import pdfkit # Generate PDF from a web URL (maybe only from your project) pdfkit.from_url('http://google.com', 'out.pdf') # Generate PDF from a html file. pdfkit.from_file('file.html', 'out.pdf') # Generate PDF from a plain html string. pdfkit.from_string('Hello!', 'out.pdf') # Save the PDF in a variable myPdf = pdfkit.from_url('http://google.com', False)

And you are basically generating PDFs on the fly easily and quick.

Examples

It’s easy to generate PDFs with Django and PDFKit, checkout the following examples:

Save PDF on the server

To save a PDF locally, use any method and provide the path and filename where the file should be saved as second parameter.

import pdfkit from django.http import HttpResponse def index(request): pdf = pdfkit.from_url("http://ourcodeworld.com", "ourcodeworld.pdf") return HttpResponse("Everything working good, check out the root of your project to see the generated PDF.") 

The previous example will create a PDF in the root of your Django project.

Return PDF as response

You can retrieve directly a file from PDFKit without saving it in your system, just provide False as the destination parameter.

You can use the following snippet to return a PDF as response :

import pdfkit from django.http import HttpResponse def index(request): # Use False instead of output path to save pdf to a variable pdf = pdfkit.from_url('http://ourcodeworld.com', False) response = HttpResponse(pdf,content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="ourcodeworld.pdf"' return response

If you navigate to the route with this function, the browser will start to download the PDF generated by the controller.

Generate PDF from a project route

You can generate a PDF from a route (it need to be obviously registered) of your project and use the pdf.from_url method.

import pdfkit from django.http import HttpResponse def template(request): # Returns some HTML as response return HttpResponse("

Hello World

") def pdf(request): # Create a URL of our project and go to the template route projectUrl = request.get_host() + '/template' pdf = pdfkit.from_url(projectUrl, False) # Generate download response = HttpResponse(pdf,content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="ourcodeworld.pdf"' return response

The pdf output will be a document with Hello World! as content.

Note: alternatively, instead of create a request to an endpoint of your project, you can render a template in a variable as html and then use the pdfkit.from_string method.

Other settings

Custom wkhtmltopdf path

If you want to modify the path where wkhtmltopdf is located, you can change it with the configuration method of pdfkit :

config = pdfkit.configuration(wkhtmltopdf='/opt/bin/wkhtmltopdf')) pdfkit.from_string("

Hello World

", output_file, configuration=config)

PDF Settings

You can specify all wkhtmltopdf options. You can drop ‘–’ in option name. If option without value, use None , False or » for dict value:

options = < 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8", 'no-outline': None >pdfkit.from_url('http://google.com', 'out.pdf', options=options)

wkhtmltopdf Output

By default, PDFKit will show all wkhtmltopdf output:

wkhtmltopdf output

If you dont want it, you need to set the quiet option in the configuration of the method that you use:

options = < 'quiet': '' >pdfkit.from_url('google.com', 'out.pdf', options=options)

Basic troubleshooting

There are 2 know common issues while you use PDFKit in Python:

IOError — No wkhtmltopdf executable found

This error occurs because there’s no wkhtmltopdf distribution in your system. In case that you’ve already installed, it’s probably not available as a command in the console. Open your system console and verify if the wkhtmltopdf command exists.

IOError — Command Failed

Something went wrong with wkhtmltopdf and the operation couldn’t be achieved. Try executing the plain command in the console and check for any possible error (the webpage doesn’t exists, the file doesn’t exists etc.).

Carlos Delgado

Carlos Delgado

Senior Software Engineer at EPAM Anywhere. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Источник

Читайте также:  Расширение php curl ubuntu
Оцените статью