weasyprint does not load flask images - python

Hello friends I have a code to generate pdf with weasyprint from flask and it turns out that it works and generates the pdf but the html that I am rendering has two images and it does not render them for me I have the following code:
from weasyprint import HTML
image = "/static/images/logo-ori.png"
name = "Pepito perez"
print_html = render_template('cert/certificado.html', img=image)
Up to this point the image renders sim problem but when I go to convert it to pdf it no longer renders it
cert = os.path.join(url_direct, "certificado.pdf")
pdf = HTML(string=print_html)
pdf.write_pdf(cert)
The pdf is stored on the server which is what I want to do and with flask I redirect to start I hope they can help me I was reviewing how to use flask-weasyprint but I cannot store the pdf on the server I hope they can help me with either of the two. Thank you in advance Thank you

Related

Weasyprint doesn't render images (Python)

I am writing a python script that generates a html file out of some images and svg files, which later should be converted into a pdf file.
For the conversion I am using weasyprint, but for some reason it doesnt render the images, only the according alt-text.
Here is a screenshot of the html file rendered in Chrome:
But the generated pdf looks like this:
Here is the code that should generate the pdf:
html = HTML(filename="path/to/file")
html.write_pdf("path/to/output/file")
And here is the according html file:
<img src="C:/Users/jonas/Documents/Dev/PythonLabel/bin/LABEL_SVG.svg" alt="SVG of Label" />
<div class="sn-number">3253343345</div>
<img class="qr-code" src="C:/Users/jonas/Documents/Dev/PythonLabel/bin/qrcode.png" alt="qrcode" />
I dont know what causes the problem, but Firefox isnt able to render the images either, but Chrome and Brave manage to do so. Maybe both problems have a similar reason.
So I managed to get it to work, but its not a pretty solution.
I figured out, that weasyprint was able to get images and SVGs from actual webpages like stackoverflow. So I made a little flask app that would only serve the one html file, and after the PDF was created I just stopped the flask server.
from flask import Flask
from multiprocessing import Process
app = Flask(
__name__, static_folder=path/to/static/folder)
#app.route("/")
def home():
with open(path/to/html, "r") as f:
html = "".join(f.readlines())
return html
def start_server():
app.run()
if __name__ == "__main__":
server = Process(target=start_server)
server.start()
sleep(4)
print("Generating PDF...")
html = HTML(
"http://localhost:5000").write_pdf(path/to/output/file)
server.terminate()
server.join()

Django serve a PDF document loaded from Mongodb

I am storing PDF documents in MongoDB; base64 encoded. I want to serve these PDFs from a view function. I'm hoping to eventually embed them into an HTML embed element or Iframe. For now, I'm just trying to get this to work.
Similar questions:
django PDF FileResponse "Failed to load PDF document." (OP forgot to call .seek on the buffer)
Django FileResponse PDF - pdf font changes in frontend - (Django DRF and React.js) (no answer yet)
how to display base64 encoded pdf? (answers don't involved Django)
Here is my view:
def pdf(request, pdf_id):
document = mongo_db_client.get_document(pdf_id) # uses a find_one query, returns a cursor on the document
pdf = base64.b64decode(document.read())
print(f"pdf type: {type(pdf)}")
print(f"pdf length: {len(pdf)}")
# We save the PDF to the filesystem to check
# That at least that works:
with open("loaded_pdf.pdf", "wb") as f:
f.write(pdf)
# See: https://docs.djangoproject.com/en/4.0/howto/outputting-pdf/
_buffer = io.BytesIO(pdf)
p = canvas.Canvas(_buffer)
p.showPage()
p.save()
_buffer.seek(0)
return FileResponse(_buffer, content_type='application/pdf')
The output of this is that I am able to view the PDF saved to the filesystem and the print output is:
pdf type: <class 'bytes'>
pdf length: 669764
Now, for one of the PDFs that I have, I can open the URL and view it in the browser. For another PDF that I have, it fails to load in the browser, showing only the PDF title. In both cases, the PDF saved to the filesystem and I can view it there without error.
Any ideas?

Uploading image using pyimgur to imgur, using images link

I was interested in uploading images to the imgur API. In the docs to upload the image
import pyimgur
CLIENT_ID = "Your_applications_client_id"
PATH = "A Filepath to an image on your computer"
im = pyimgur.Imgur(CLIENT_ID)
uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur")
print(uploaded_image.title)
print(uploaded_image.date)
print(uploaded_image.url)
print(uploaded_image.link)
I am curious if someone knows how to instead of using a path( have the image saved locally), just have a link to a image to upload to imgur. I feel like it exists due to the fact with the GUI website you can enter a picture link and can then upload.
Thank you for the help.
The Imgur.upload_image() method takes a url argument, simply pass it a URL of an image to add:
uploaded_image = im.upload_image(url=URL_OF_IMAGE, title="Uploaded with PyImgur")
You must either provide a path or a URL, but not both.
See the upload_image() documentation for all arguments it accepts:
Upload the image at either path or url.
path – The path to the image you want to upload.
url – The url to the image you want to upload.

HTML to PDF conversion in app engine python

My website has a lot of dynamically generated HTML content and I would like to give my website users a way to save the data in PDF format. Any ideas on how it can be done? I tried xhtml2pdf library but I couldn't get it to work. I even tried reportlibrary but we have to enter the PDF details manually. Is there any library which converts HTML content to PDF and works on app engine?
You need to copy all dependencies into your GAE project folder:
html5lib
reportlab
six
xhtml2pdf
Then you can use it like this:
from xhtml2pdf import pisa
from cStringIO import StringIO
content = StringIO('html goes here')
output = StringIO()
pisa.log.setLevel('DEBUG')
pdf = pisa.CreatePDF(content, output, encoding='utf-8')
pdf_data = pdf.dest.getvalue()
Some useful info that I googled just for you:
http://www.prahladyeri.com/2013/11/how-to-generate-pdf-in-python-for-google-app-engine/
https://github.com/danimajo/pineapple_pdf

Upload file through url in django

I'm currently creating an app thats supposed to take a input in form of a url (here a PDF-file) and recognize this as a PDF and then upload it to a tmp folder i have on a server.
I have absolutely no idea how to proceed with this. I've already made a form which contains a FileField which works perfectly, but when it comes to urls i have no clue.
Thank you for all answers, and sorry about the lacking english skills.
The first 4 bytes of a pdf file are %PDF so you could just download the first 4 bytes from that url and compare them to %PDF. If it matches, then download the whole file.
Example:
import urllib2
url = 'your_url'
req = urllib2.urlopen(url)
first_four_bytes = req.read(4)
if first_four_bytes == '%PDF':
pdf_content = urllib2.urlopen(url).read()
# save to temp folder
else:
# file is not PDF

Categories

Resources