Generate PDF using python and HTML

Dependencies:

sudo pip3 install pdfkit
sudo apt-get install wkhtmltopdf

Pdfkit and wkhtmltopdf are the packages that you will be required before getting started.

PDF can be generated in 3 ways. One is using a website url, second one is using a html string and the last one is using a html file(optional css file can also be specified in all 3 ways).

In this article we will discuss the third way which is more advanced one and will be most useful for most of our requirements. Below is the program I am going to use to generate the PDF.

import pdfkit
import sys

inputfile = sys.argv[1]
outfile = args.argv[2]

options = {
      "enable-local-file-access": True,
      "enable /var/www/html/": True,
    'page-size': 'Letter',
    'margin-top': '0.75in',
    'margin-right': '0.75in',
    'margin-bottom': '0.75in',
    'margin-left': '0.75in',
    'encoding': "UTF-8",
    'custom-header': [
        ('Accept-Encoding', 'gzip')
    ],
    'cookie': [
        ('cookie-empty-value', '""'),
        ('cookie-name1', 'cookie-value1'),
        ('cookie-name2', 'cookie-value2'),
    ],
    'no-outline': None
}
# Single CSS file
css = 'bootstrap.css'

#pdfkit.from_url('http://google.com', 'out1.pdf')
pdfkit.from_file(inputfile, outfile, options=options, css=css)
#pdfkit.from_string('Hello!', 'out3.pdf')

In the code we can notice at the bottom that we can use a URL, local html file or a plain html string. Also a bootstrap.css file is being used for our styles. Common options that can be used to configure the PDF can also be seen in the above code. For full list of options that can be used read the documentaion here.

Now this code takes two arguments first one is input html file and the other being name of the output pdf that you want to generate into.

More documentaion regarding WKHTMLTOPDF can be read here.

Python program for Generating pdf using html content

Handling special characters in jQuery selectors

When we make dynamic id in Javascript sometimes it may happen that it can contain special characters like @/space/ something which might be difficult to access the element back using the jQuery selector.

So this article will help you manage such special characters so that the Javascript on that page does not break and throw any error for smooth accessing of the web page.

First create a function like below and place it in a common place where you will access it.

function escapeSelector( myid ) {
console.log(myid);
return myid.replace( /[:|.|[|]|,|=|@ ]/g, "\$&" );
}

Notice that the function accepts a parameter id which will escape the special characters using regex and then return it.

Now just call the above function whenver you are using jQuery selector to select that element.

For exmaple:

var element = $('tr[id^=' + escapeSelector(id) + ').attr("data-filename");

So the above line of code is selecting a particular td element with the id which is now being escaped to handle special characters.

Social rules/conventions that will help you become a better person

  • Don’t call someone more than twice continuously, they might be busy with something. Respect their time by assuming it something very important.
  • If you have borrowed money from someone return it even before they ask you. It shows your integrity and commitment. Same goes with any thing or a gadget that you might have borrowed.
  • Try not to order an expensive dish from the menu when someone else is paying.
  • be nice
  • Always open the door for the person behind you no matter whoever it is.
  • If your friend/colleague pays for any bill in restaurant or cab just try to pay it the next time.
  • Respect others opinions no matter what you think of them.
  • Never interrupt people while they are speaking, let the complete it and hear it out, suggests you are a good listener and willing to listen and understand them.
  • Saying thank you when someone helps you will not make you poorer. Its a way of saying you are thankful to them.
  • Don’t comment on someone’s appearance unless they are very close to you and they don’t feel bad about you talking about it.
  • Treat everyone with same manner no matter who it might be, the CEO or cleaner.
  • When someone is speaking to you, looking into your phone is considered rude. Avoid it.
  • Never swipe left or right on someone else’s phone when they are showing something to you. Respect their privacy.

Set your tp link router as wifi booster

Connect to the router and open the url http://tplinklogin.net/

Enter username and password. Now navigate to Lan Settings under Network and change the IP address of the router that is different from the main router.

Save the changes, wait till the router restarts with new IP.

After the router restarts navigate to wireless security, click on enable WDS briddging. Select channel from main router. To get this information click survey, discover your main router and connect to it. Enter the password of the main router and while you are here note the channel of the main router and enter it in WDS bridging settings under label channel.

Router might restart here, then navigate to wireless security and set password for your 2nd router.

Also click on DHCP and disable DHCP.

Click reboot. Now you will notice that your second router acts as your wifi booster.

Python replace a string from Dictionary/Hash mapping

In a situation where we have a dictionary mapping and want to use the mapping to replace a particular string we can use the below code to do the same.

Have a look at below code:

import re

my_dict = {
    "\u0c1C" : "ja",
    "\u0c15" : "ka"
}

string = "కరజ"


for unicode, roman in my_dict.items():
    string = string.replace(unicode, roman)

print(string)

The above code will replace the string from the dictionary. Note that the dictionary has unicode code points that are mapped to specific values. This code will be useful for natural language processing when we deal with unicode range points.

HTML Forms

HTML forms are used to pass data to a server either using get/post method.

A form can contain input elements like text fields, check-boxes, radio-buttons, submit buttons and more. A form can also contain select lists, text area and label elements.

The <form> tag is used to create an HTML form:

<form>
.
input elements
.
</form>

HTML Forms – The Input Element

The most important form element is the input element.

The input element is used to select user information.

An input element can vary in many ways, depending on the type attribute. An input element can be of type text field, checkbox, password, radio button, submit button, and more.

The most used input types are described below.

Text Fields

Text Fields a one-line input field that a user can enter text into

<input type="text" />

<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>

The above HTML code looks like below in a browser:

Form fields with input type text

Password Field

<form>
Password: <input type="password" name="pwd" />
</form>

The above code will look like below in the browser

Password field in form in browser

Note: The characters in a password field are masked (i.e, shown as asterisks or black dots). 

Radio Buttons

Radio buttons let a user select only one one of a limited number of choices.

<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>

Radio buttons in browser

Checkboxes

Checkboxes let a user select one or more options of a limited number of choices. For example selecting all the vehicles I own while filling a form.

<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car 
</form>

Checkbox in browser

Submit Button

A submit button is used to send form data to a server. The data is sent to the page specified in the form’s action attribute. The api/server defined in the action attribute usually does something with the received input and does generate appropriate response and pass it back to the client/user.

<form name="input" action="html_form_action.php" method="get">
Username: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>

Form submit button in browser

If you type some characters in the text field above and click the “Submit” button, the browser will send your input to a page called “html_form_action.php”. In that page(php) you can access all the data received and process it accordingly.

All html tags explained with a short definition

TagDescription
<!–…–>Defines a comment
<!DOCTYPE> Defines the document type
<a>Defines an anchor
<abbr>Defines an abbreviation
<acronym>Defines an acronym
<address>Defines contact information for the author/owner of a document
<applet>Deprecated. Defines an embedded applet
<area />Defines an area inside an image-map
<b>Defines bold text
<base />Defines a default address or a default target for all links on a page
<basefont />Deprecated. Defines a default font, color, or size for the text in a page
<bdo>Defines the text direction
<big>Defines big text
<blockquote>Defines a long quotation
<body>Defines the document’s body
<br />Defines a single line break
<button>Defines a push button
<caption>Defines a table caption
<center>Deprecated. Defines centered text
<cite>Defines a citation
<code>Defines computer code text
<col />Defines attribute values for one or more columns in a table 
<colgroup>Defines a group of columns in a table for formatting
<dd>Defines a description of a term in a definition list
<del>Defines deleted text
<dfn>Defines a definition term
<dir>Deprecated. Defines a directory list
<div>Defines a section in a document
<dl>Defines a definition list
<dt>Defines a term (an item) in a definition list
<em>Defines emphasized text 
<fieldset>Defines a border around elements in a form
<font>Deprecated. Defines font, color, and size for text
<form>Defines an HTML form for user input
<frame />Defines a window (a frame) in a frameset
<frameset>Defines a set of frames
<h1> to <h6>Defines HTML headings
<head>Defines information about the document
<hr />Defines a horizontal line
<html>Defines an HTML document
<i>Defines italic text
<iframe>Defines an inline frame
<img />Defines an image
<input />Defines an input control
<ins>Defines inserted text
<isindex>Deprecated. Defines a searchable index related to a document
<kbd>Defines keyboard text
<label>Defines a label for an input element
<legend>Defines a caption for a fieldset element
<li>Defines a list item
<link />Defines the relationship between a document and an external resource
<map>Defines an image-map 
<menu>Deprecated. Defines a menu list
<meta />Defines metadata about an HTML document
<noframes>Defines an alternate content for users that do not support frames
<noscript>Defines an alternate content for users that do not support client-side scripts
<object>Defines an embedded object
<ol>Defines an ordered list
<optgroup>Defines a group of related options in a select list
<option>Defines an option in a select list
<p>Defines a paragraph
<param />Defines a parameter for an object
<pre>Defines preformatted text
<q>Defines a short quotation
<s>Deprecated. Defines strikethrough text
<samp>Defines sample computer code
<script>Defines a client-side script
<select>Defines a select list (drop-down list)
<small>Defines small text
<span>Defines a section in a document
<strike>Deprecated. Defines strikethrough text
<strong>Defines strong text
<style>Defines style information for a document
<sub>Defines subscripted text
<sup>Defines superscripted text
<table>Defines a table
<tbody>Groups the body content in a table
<td>Defines a cell in a table
<textarea>Defines a multi-line text input control
<tfoot>Groups the footer content in a table
<th>Defines a header cell in a table
<thead>Groups the header content in a table
<title>Defines the title of a document
<tr>Defines a row in a table
<tt>Defines teletype text
<u>Deprecated. Defines underlined text
<ul>Defines an unordered list
<var>Defines a variable part of a text
<xmp>Deprecated. Defines preformatted text
HTML tags

All the html tags format the text accordingly.

Its up to the developer to use appropriate tag according to the requirement.

Some of the major attributes are explained below that will go with almost every html tag element.

AttributeValueDescription
classclassnameSpecifies a classname for an element(refereed to using . selector)
ididSpecifies a unique id for an element(refereed using # selector )
stylestyle_definitionSpecifies an inline style for an element(inline CSS)
titletooltip_text Specifies extra information about an element (displayed as a tool tip on mouse hover)
Major HTML attributes

C program to add two integers and find their sum

In this C program we are going to take two integer inputs from the user then add it display its sum on the screen.

#include<stdio.h>
int main(){

    //below line declares two integers to add and one integer to store the sum
    int number1, number2, sum;

    //let the user know to enter two integers
    printf("Enter two integers");

    //now let us take the input from the user 
    scanf("%d %d", &number1, &number2);

    //now add the two integers
    sum = number1 + number2;

    //print the sum below
    printf("Sum of %d + %d is %d\n", number1, number2, sum);
    
    return 0;
}

The above code will take inputs from user and add those numbers and display their sum.

The output will look like below

There is a video tutorial doing the same.

Sorting array of objects based on values which are strings in Javascript

Let us assume we have a JSON array of objects that contain some key value pairs. We might want to compare it with similar JSON array to find out whether both are same or not. To do this we might want to sort the array first and then compare as the order of key value pairs might be different.

Lets say we have following json arrays and we want to sort them to compare them.

var json_array1 = [
    {
        "Name" : "Lenovo",
        "Year" : 1985
    },
    {
        "Name" : "HP",
        "Year" : 1986
    },
    {
        "Name" : "HCL",
        "Year" : 1987
    },
    {
        "Name" : "Dell",
        "Year" : 1974
    }
]

var json_array2 = [
    {
        "Name" : "HP",
        "Year" : 1986
    },
    {
        "Name" : "HCL",
        "Year" : 1987
    },
    {
        "Name" : "Lenovo",
        "Year" : 1985
    },
    {
        "Name" : "Dell",
        "Year" : 1974
    }
]

Now to sort them we use the below code to sort them. Notice that we might want to sort it by the Key-Value pair Name.

json_array1.sort((a, b) => {
    let fa = a.Name.toLowerCase(),
        fb = b.Name.toLowerCase();

    if (fa < fb) {
        return -1;
    }
    if (fa > fb) {
        return 1;
    }
    return 0;
});

The above code will return the sorted array of JSON array sorted by the key value pair Name. Notice that we can also sort by using the key value pair Year in that case we don’t need to convert to lowercase since it is a integer type.

Ubuntu Apache add reverse proxy to avoid port number visibility | NodeJS

When we create APIs using nodejs we often enable them to run on particular port number. It is all fine until we move into production environment where we don’t want our port number to visible to our clients while we are making the server request calls using the APIs.

So a solution would be to mask our port number and let apache handle the request and redirect the request to that server internally without revealing the port number. For this we need to edit the apache configuration like following.

Open the file /etc/apache2/sites-enabled/000-default.conf using any editor and add the following lines under or above the directory tag. Note that if you are using SSL for your site i.e https enabled then you have to edit the file /etc/apache2/sites-enabled/000-default-le-ssl.conf to make it work properly for https enabled sites.

<Location /query-api-0.3.1>
ProxyPass http://localhost:3099/query-api-0.3.1
ProxyPassReverse http://localhost:3099/query-api-0.3.1
Order allow,deny
Allow from all
</Location>

Reverse Proxy exmaple in apache

Then save the file and restart apache and try to run the API request without the port number.