I am trying to export my html page into pdf using Pisa library in django, But I have problems with arabic characters when I get the pdf output
i visit this site https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/
here my code
from .utils import render_to_pdf #created in step 4
class GeneratePdf(View):
def get(self, request, *args, **kwargs):
tar= u"محاولة"
data = {'dem1': dem1,'dem2':dem2,'tar':tar}
pdf = render_to_pdf('pdf2.html', data)
return HttpResponse(pdf, content_type='application/pdf')
here the template
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html"; charset=UTF-8">
<style type='text/css'>
#font-face {
font-family: "DejaVuSansMono";
src: url("/static/fonts/DejaVuSansMono.ttf");
}
body { font-family: DejaVuSansMono; }
</style>
</head>
<body>
<p>محاولة الكتابة باللغة العربية</p>
<p>here the variable = {{tar}}</p>
</body>
</html>
i have symbols in place of arabic characters
Related
i recently started my django course online nad getting some problem.
i am not able to use my variable which i passed from index.html to about.html.
but in about.html it is not shown up.
.py file code :
from django .http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request , 'index.html')
def about(request):
t1 = print(request.GET.get('text' , 'default'))
return render(request , 'about.html' , t1)
index.html file code:
<!DOCTYPE html>
<html>
<head>
<title>template</title>
</head>
<body>
<h1> hello everyone </h1>
<form action="/about" , method="get">
<textarea name="text" style="margin: 0px; width: 1245px; height: 171px;"></textarea>
<input type="submit" name="OK">
</form>
</body>
</html>
about.html file code :
<!DOCTYPE html>
<html>
<head>
<title>template</title>
</head>
<body>
<h1>you typed {{t1}}</h1>
</form>
</body>
</html>
print(..) does not return anything. You can pass the variable to the context, for example:
def about(request):
return render(
request ,
'about.html' ,
{'t1': request.GET.get('text' , 'default')}
)
Following this, I've created html to pdf converter and it works fine with english language, but I have some russian symbols that I cannot decode. Instead of normal russian words I get:
тут должен быть текÑ■Ñ
template:
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>MC-report</title>
</head>
<body>
<div style="align:center"> тут должен быть текст {{ today }}</div>
</body>
</html>
I have same code (plus some code just to get needed data) as in this manual, instead of playing with html.encode and template:
pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) #for decoding data, not template text
None of cp1251/2/866 and UTF-8 won't work
add to your html (Alice-Regular.ttf) is Russian fonts
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
#font-face {
font-family: "Alice-Regular";
src: url("/fonts/Alice-Regular.ttf") format("truetype");
}
body {
font-family: "Alice-Regular";
font-size: 20px
}
</style>
I'm trying to build a small web app. A simple price scraper. I'm trying to piece it together into a web app without success.
Here's my working piece of python code I have, that returns the price of the specific item which is :
918193-012
Basically the idea is : a user would input a stock code of a product, and in return, on the same page/or the other page, he would receive the price for that product. Any advices are appreciated.
import requests
from bs4 import BeautifulSoup
import subprocess
url = f'https://www.tennis.fr/catalogsearch/result/?q=918193-012'
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
capturedPrice = soup.findAll('p', class_="special-price")[0].text
capturedPrice = capturedPrice.strip('0')
capturedPrice = capturedPrice.strip()
print(capturedPrice[35:])
Here's my app.py
from flask import Flask, jsonify, render_template, request
from bs4 import BeautifulSoup
import subprocess
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
An here's: the index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto+Mono&display=swap" >
<style>
body {
font-family: 'Roboto Mono', monospace;
}
* {
box-sizing: border-box;
}
form.example input[type=text] {
padding: 10px;
font-size: 17px;
border: 1px solid grey;
float: left;
width: 80%;
background: #f1f1f1;
}
form.example button {
float: left;
width: 20%;
padding: 10px;
background: #2196F3;
color: white;
font-size: 17px;
border: 1px solid grey;
border-left: none;
cursor: pointer;
}
form.example button:hover {
background: #0b7dda;
}
form.example::after {
content: "";
clear: both;
display: table;
}
</style>
</head>
<body>
<center>
<h1>Find the best prices</h1>
<p><h4>Stock code to test: 918193-012</h3></p>
<form class="example" action="" style="margin:auto;max-width:500px">
<input type="text" placeholder="Stock code" name="">
<button type="submit"><i class="fa fa-search"></i></button>
</form>
</center>
</body>
</html>
You want to extract Input-Information from your HTML Site. A possible solution would be to use a form:
app.py:
from flask import Flask
from flask_wtf import FlaskForm
from flask import render_template
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
app = Flask(__name__)
class InputForm(FlaskForm):
input = StringField('Input',validators=[DataRequired()]
submit = SubmitField('Search for Price')
#app.route('/')
def index():
form = InputForm()
if form.validate_on_submit():
result = form.input.data
return render_template("index.html", result=result, form=form)
else:
return render_template("index.html",form=form)
if __name__=="__main__":
app.run(debug=True)
You can change the StringField to IntegerField if you want to, thats on you.
Next step would be to add sth to your #app.route:
Ofcourse you need to add some code to your HTML Site to pass the Search-Value to the Web App.
instead of your normal html button you need to pass the form:
<!DOCTYPE html>
<html>
<head>
##your css stuff##
<style>
</style>
</head>
<body>
<center>
<h1>Find the best prices</h1>
<p><h4>Stock code to test: 918193-012</h3></p>
{{ form.input(class="form-control") }}
{{ form.submit(class="btn") }}
{% if result == #yourvalue# %}
#your printed data#
{% else %}
{% endif %}
</center>
</body>
</html>
in this example bootstrap is used for design but thats changable the way you want it
I hope my text was understandable
Edit 1:
You use an if statement inside the html site if you want to use just one html file. With my example you pass the result to the html with the render_template line.
I was having trouble exporting images in an html file as pdf, a similar solution exists here.
The html is being rendered properly on the server. I verified it by cross checking it on a url.
but while trying to download/render the pdf **i get a pdf but which is blank, also it says error in the third line of the download function in views.py
Here is what i tried:
html file:
<html>
<head>
<link href="{{ STATIC_URL }}css/certificate.css" rel="stylesheet"
type="text/css" />
</head>
<body>
<div class="certificate_container">
<div class="statictext">
<p>{{ name }}</p>
</div>
</div>
</body>
<html>
css file:
body{margin:0px; padding:0px;}
.certificate_container{ width:792px; height:612px; background:url("../images/certificate.gif") no-repeat;}
.statictext{width:400px; margin:0px auto; padding-top:240px; height:30px; text-align:center; font:bold 14px Arial, Helvetica, sans-serif; color:#333;}
views.py:
#relevant imports
from reportlab.pdfgen import canvas
import xhtml2pdf.pisa as pisa
import cStringIO as StringIO
def download(request):
html = render_to_string("certificate.html", { 'pagesize' : 'A4', }, context_instance=RequestContext(request))
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(), dest=result, link_callback=fetch_resources )
if not pdf.err:
return HttpResponse(result.getvalue(), mimetype='application/pdf')
return HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))
def fetch_resources(uri, rel):
path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, ""))
return path
def home(request):
return render(request, 'certificate.html', {'name':'user1'} )
The urls have been taken care of properly.
I later found, this could not be achieved using the above tech stack, hence i tried getting a template image and used PIL to modify it based on context. And that worked.
When I try to view the template I created the development server shows the template html file as if it were plain text. Basically the web page shows what is in my template .html file. I know something is working because when I pass the render_to_response function the dictionary of arguments and try to display the variable I passed I it renders that part correctly. Here is an example of the problem.
This is the template file:
<b>Hello</b>
Then the output source code is the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title></title>
<meta name="Generator" content="Cocoa HTML Writer">
<meta name="CocoaVersion" content="1038.35">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Courier}
</style>
</head>
<body>
<p class="p1"><b>Hello</b></p>
</body>
</html>
And the screen just shows:
<b>Hello</b>
Any ideas on how to make my template render as if it were an html file would be appreciated.
I don't know how you're outputting the html file into your template, but, if you're doing something like this in your template
{{ my_template }}
to render the my_template string variable that you're passing to render_to_response
you just need to use the safe filter
{{ my_template|safe }}
this won't html-encode your string, and the html will render propery into your page