{"id":75743,"date":"2020-01-20T11:56:50","date_gmt":"2020-01-20T06:26:50","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=75743"},"modified":"2024-04-12T14:17:16","modified_gmt":"2024-04-12T08:47:16","slug":"generating-pdfs","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/","title":{"rendered":"Generating PDFs"},"content":{"rendered":"<p>Django is able to output PDF files dynamically using views. This is made possible by the excellent, open-source ReportLab Python PDF library. The advantage of generating PDF files dynamically is that you can create customized PDFs for different purposes \u2013 say, for different users or different pieces of content.<\/p>\n<h3>Install Reportlab<\/h3>\n<p>The ReportLab library is available on PyPI. A user guide (not coincidentally, a PDF file) is also available for download. You can install ReportLab with pip:<br>\n$ pip install reportlab<\/p>\n<p>Test your installation by importing it in the Python interactive interpreter:<br>\n&gt;&gt;&gt; import reportlab<\/p>\n<p>If that command doesn\u2019t raise any errors, the installation worked.<\/p>\n<h3>Write Your View<\/h3>\n<p>The key to generating PDFs dynamically with Django is that the ReportLab API, like the csv library acts on file-like objects, like Django\u2019s HttpResponse. Here\u2019s a Hello World example:<\/p>\n<p>from reportlab.pdfgen import canvas<br>\nfrom django.http import HttpResponse<\/p>\n<p>def some_view(request):<br>\n# Create the HttpResponse object with the appropriate PDF headers.<br>\nresponse = HttpResponse(content_type=&#8217;application\/pdf&#8217;)<br>\nresponse[&#8216;Content-Disposition&#8217;] = &#8216;attachment;<br>\nfilename=&#8221;somefilename.pdf&#8221;&#8216;<\/p>\n<p># Create the PDF object, using the response object as its &#8220;file.&#8221;<br>\np = canvas.Canvas(response)<\/p>\n<p># Draw things on the PDF. Here&#8217;s where the PDF generation happens.<br>\n# See the ReportLab documentation for the full list of functionality.<br>\np.drawString(100, 100, &#8220;Hello world.&#8221;)<\/p>\n<p># Close the PDF object cleanly, and we&#8217;re done.<br>\np.showPage()<br>\np.save()<br>\nreturn response<\/p>\n<p>The code and comments should be self-explanatory, but a few things deserve a mention:<\/p>\n<ul>\n<li>&nbsp;The response gets a special MIME type, application\/pdf. This tells browsers that the document is a PDF file, rather than an HTML file.<\/li>\n<li>The response gets an additional Content-Disposition header, which contains the name of the PDF file. This filename is arbitrary: Call it whatever you want. It\u2019ll be used by browsers in the Save as\u2026 dialogue, etc.<\/li>\n<li>The Content-Disposition header starts with &#8216;attachment; &#8216; in this example. This forces Web browsers to pop-up a dialog box prompting\/confirming how to handle the document even if a default is set on the machine. If you leave off &#8216;attachment;&#8217;, browsers will handle the PDF using whatever program\/plugin they\u2019ve been configured to use for PDFs. Here\u2019s what that code would look like:<br>\nresponse[&#8216;Content-Disposition&#8217;] = &#8216;filename=&#8221;somefilename.pdf&#8221;&#8216;<\/li>\n<li>Hooking into the ReportLab API is easy: Just pass response as the first argument to canvas.Canvas. The Canvas class expects a file-like object, and HttpResponse objects fit the bill.<\/li>\n<li>Note that all subsequent PDF-generation methods are called on the PDF object (in this case, p) \u2013 not on response.<\/li>\n<li>Finally, it\u2019s important to call showPage() and save() on the PDF file.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<h3>Complex PDF\u2019s<\/h3>\n<p>If you\u2019re creating a complex PDF document with ReportLab, consider using the io library as a temporary holding place for your PDF file. This library provides a file-like object interface that is particularly efficient. Here\u2019s the above Hello World example rewritten to use io:<\/p>\n<p>from io import BytesIO<br>\nfrom reportlab.pdfgen import canvas<br>\nfrom django.http import HttpResponse<\/p>\n<p>def some_view(request):<br>\n# Create the HttpResponse object with the appropriate PDF headers.<br>\nresponse = HttpResponse(content_type=&#8217;application\/pdf&#8217;)<br>\nresponse[&#8216;Content-Disposition&#8217;] = &#8216;attachment;<br>\nfilename=&#8221;somefilename.pdf&#8221;&#8216;<\/p>\n<p>buffer = BytesIO()<\/p>\n<p># Create the PDF object, using the BytesIO object as its &#8220;file.&#8221;<br>\np = canvas.Canvas(buffer)<\/p>\n<p># Draw things on the PDF. Here&#8217;s where the PDF generation happens.<br>\n# See the ReportLab documentation for the full list of functionality.<br>\np.drawString(100, 100, &#8220;Hello world.&#8221;)<\/p>\n<p># Close the PDF object cleanly.<br>\np.showPage()<br>\np.save()<\/p>\n<p># Get the value of the BytesIO buffer and write it to the response.<br>\npdf = buffer.getvalue()<br>\nbuffer.close()<br>\nresponse.write(pdf)<br>\nreturn response<\/p>\n<h3>Further Resources<\/h3>\n<ul>\n<li>&nbsp;PDFlib is another PDF-generation library that has Python bindings. To use it with Django, just use the same concepts explained in this article.<\/li>\n<li>Pisa XHTML2PDF is yet another PDF-generation library. Pisa ships with an example of how to integrate Pisa with Django.<\/li>\n<li>HTMLdoc is a command-line script that can convert HTML to PDF. It doesn\u2019t have a Python interface, but you can escape out to the shell using system or popen and retrieve the output in Python.<\/li>\n<\/ul>\n\n\n<p><a href=\"https:\/\/www.vskills.in\/certification\/tutorial\/certified-django-developer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Back to Tutorial<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Django is able to output PDF files dynamically using views. This is made possible by the excellent, open-source ReportLab Python PDF library. The advantage of generating PDF files dynamically is that you can create customized PDFs for different purposes \u2013 say, for different users or different pieces of content. Install Reportlab The ReportLab library is&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[8655],"tags":[8794],"class_list":["post-75743","page","type-page","status-publish","hentry","category-django-web-development","tag-generating-pdfs"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Generating PDFs - Tutorial<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Generating PDFs - Tutorial\" \/>\n<meta property=\"og:description\" content=\"Django is able to output PDF files dynamically using views. This is made possible by the excellent, open-source ReportLab Python PDF library. The advantage of generating PDF files dynamically is that you can create customized PDFs for different purposes \u2013 say, for different users or different pieces of content. Install Reportlab The ReportLab library is...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/\" \/>\n<meta property=\"og:site_name\" content=\"Tutorial\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vskills.in\/\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-12T08:47:16+00:00\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/\",\"name\":\"Generating PDFs - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-20T06:26:50+00:00\",\"dateModified\":\"2024-04-12T08:47:16+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Generating PDFs\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"name\":\"Tutorial\",\"description\":\"Vskills - A initiative in elearning and certification\",\"publisher\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\",\"name\":\"Vskills\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"width\":73,\"height\":55,\"caption\":\"Vskills\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/vskills.in\/\",\"https:\/\/x.com\/vskills_in\",\"https:\/\/www.linkedin.com\/company-beta\/1371554\/\",\"https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Generating PDFs - Tutorial","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/","og_locale":"en_US","og_type":"article","og_title":"Generating PDFs - Tutorial","og_description":"Django is able to output PDF files dynamically using views. This is made possible by the excellent, open-source ReportLab Python PDF library. The advantage of generating PDF files dynamically is that you can create customized PDFs for different purposes \u2013 say, for different users or different pieces of content. Install Reportlab The ReportLab library is...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/","og_site_name":"Tutorial","article_publisher":"https:\/\/www.facebook.com\/vskills.in\/","article_modified_time":"2024-04-12T08:47:16+00:00","twitter_misc":{"Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/","name":"Generating PDFs - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-20T06:26:50+00:00","dateModified":"2024-04-12T08:47:16+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/generating-pdfs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"Generating PDFs"}]},{"@type":"WebSite","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","name":"Tutorial","description":"Vskills - A initiative in elearning and certification","publisher":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization","name":"Vskills","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","width":73,"height":55,"caption":"Vskills"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/vskills.in\/","https:\/\/x.com\/vskills_in","https:\/\/www.linkedin.com\/company-beta\/1371554\/","https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw"]}]}},"_links":{"self":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75743","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/comments?post=75743"}],"version-history":[{"count":4,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75743\/revisions"}],"predecessor-version":[{"id":83370,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75743\/revisions\/83370"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=75743"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=75743"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=75743"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}