Thursday 9 July 2015

Converting rml file to pdf

RML->PDF

PDF generation using reportlab's rml file


What is RML?
RML is the Report Markup Language - a member of the XML family of languages, and the XML dialect used by rml2pdf to produce documents in Adobe's Portable Document Format (PDF).RML documents can be written automatically by a program or manually using any word processor that can output text files (e.g. using a "Save as Text" option from the save menu). Since RML documents are basic text files, they can be created on the fly by scripts in Python, Perl, or almost any other language. RML makes creating documents in PDF as simple as creating a basic web page - RML is as easy to write as HTML, and uses "tags" just like HTML. It is much easier than trying to write PDF programmatically.
User guide for rml can be found here.


Installation:
 You will have to download and install reportlab plus. You can find the installation steps here.


(Assuming that you have already created a django app)

Now consider the case that I have an xml file which I need to convert to pdf. For that first you will have to create an rml file depending upon your need and save with .rml extension.

RML sample files can be found here.

In views.py import the required modules.


from rlextra.rml2pdf import rml2pdf
import xml.etree.ElementTree as ElementTree
from xml.dom import minidom



Next we write a function to obtain the rml file. The function at first extracts data from the xml file (as dict) the pass it on to the rml through context. Finally the function returns an rml in the specified encoded format  .


def getRML():
    xmldict = {}
    tree = ElementTree.parse('path to your xml file')
    root = tree.getroot()
    xmldict = XmlDictConfig(root)
    t = Template(open('path your rml file').read())
    c = Context({"xmldata": xmldict}) 
    rml = t.render(c)
    #django templates are unicode, and so need to be encoded to utf-8
    return rml.encode('utf16')


Last step is the pdf generation process.


class ConvertView(View):
   

    def get(self, request, *args, **kwargs):
        rml = getRML()
        buf = cStringIO.StringIO()
        
        #create the pdf
        rml2pdf.go(rml, outputFileName='output.pdf')
        buf.reset()
        pdfData = buf.read()
        
        #send the response
        response = HttpResponse(mimetype='application/pdf')
        response.write(pdfData)
        response['Content-Disposition'] = 'attachment; filename=output.pdf'
        return response


Now in urls.py :

from app.views import ConvertView

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^convert/$', ConvertView.as_view(), name="convert2pdf"),
      
)

Finally call the 'convert' url to obtain the pdf document.

Wednesday 8 July 2015

PDF generation using easy pdf

PDF generation using jspdf

 

PDF generation using easy pdf


Easy pdf is a pdf rendering django package. You can install it with the following command:


$ pip install django-easy-pdf
$ pip install "xhtml2pdf>=0.0.6" "reportlab>=2.7,<3"
 
Easy pdf documentation can be found here

Now in your views.py file:


import easy_pdf
from easy_pdf.views import PDFTemplateView 



class MyView(PDFTemplateView):
     template_name = "converter.html"
     pdf_filename = "Output.pdf"


    def post(self, request, args, kwargs):
          objects = MyReport.objects.all()           
          context = { 'objects'  : objects}
          return  easy_pdf.rendering.render_to_pdf_response(request,  self.template_name, context, filename='Output.pdf', encoding=u'utf-8', **kwargs)


Now in urls.py :

from app.views import MyView

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^convert/$', MyView.as_view(), name="convert2pdf"),
      
)

Finally call the 'convert' url to obtain the pdf document.

PDF generation using jspdf

PDF generation using jspdf

Python and PDF generation


PDF generation using python is one of the trickiest task that I have recently encountered. So today I want list all the possible ways that one can convert an HTML to pdf using python (Django framework).

Let start from basic before going on to Python lets check one of the simplest way to generate pdf using jspdf.

PDF generation using jspdf

For jspdf to work, first of all you will have to link all the required js files to the html.

      
  <script type="text/javascript" src="jspdf/jspdf.js"></script>  
  <script type="text/javascript" src="jspdf/jspdf.plugin.addimage.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.cell.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.from_html.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.ie_below_9_shim.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.javascript.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.sillysvgrenderer.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.split_text_to_size.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.standard_fonts_metrics.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.PLUGINTEMPLATE.js"></script> 
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
 

Now give the content (you want to convert to pdf) an id as shown below:


<body>
  <div id="target">
     (your content goes here........) 
  </div>  
  <div>
     <a href="javascript:void(0)" id="cmd">generate PDF</a>
  </div>
</body>
       

Next for the script part:

  
  <script type="text/javascript">
      $(document).ready(function(){

          var specialElementHandlers = {
              '#editor': function (element,renderer) {
                  return true;
              }
          };
          $('#cmd').click(function () {
              var doc = new jsPDF();
              var source = $('#target').html();
              var specialElementHandlers = {
                  '#bypassme': function (element, renderer) {
                      return true;
                  }
              };
              doc.fromHTML(source, 0.5, 0.5, {
                  'width': 75,'elementHandlers': specialElementHandlers
              });
              doc.output("dataurlnewwindow");
          });
      });
  </script>
 

Thats all Folks!!!