- First of we need to install the PDFKIT using the below command on terminal.
- pip install pdfkit
- you can visit this link for more information : https://pypi.python.org/pypi/pdfkit
- We perform the two usecase of this.
- Generate the PDF from URL. In This u just need to pass the URL and name of the file as below.
- pdfkit.from_url('https://pypi.python.org/pypi/pdfkit', 'pdfkit.pdf')
- Same thing u can perfom to convert the file as like
- pdfkit.from_file('yourfile.html', 'anyname.pdf')
- Now Generate the pdf from String. Suppose you are integrating some third party software, so they provide the document in base64 formart. So First you can convert them from base64 to binary , store them into varible and then pass to pdfkit to convert in pdf.
- pdfkit.from_string('binarystrinf', 'anyname.pdf')
- If You want to store the pdf in variable then pass the False instead of the filename.
- You can pass the option as third parameter to format the pdf , which include the margintop, paper size etc.
- So like wise this u can generate the pdf from different source and apply the options.
Code
# Import the library
import pdfkit
# Generate PDF from URL
pdfkit.from_url('https://pypi.python.org/pypi/pdfkit', 'demo1.pdf')
# Convert base64 to binary and then generate the pdf.
import binascii
base64string = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4='
binarystring = binascii.a2b_base64(base64string)
pdfkit.from_string(binarystring, 'demo2.pdf')
# Store pdf in variable pass the second argument as 'False'
stored_pdf = pdfkit.from_string(binarystring, False)
# Pass the options to format the pdf
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_string(binarystring, 'demo3.pdf', options=options)
Comments
Post a Comment