Postgresql functions as backend (p.4: html to pdf …)

Oleg Zech
1 min readJan 5, 2021

--

Yep, Python is at it again…

Why to keep your PDF’s as bytea and suffer with editing them (if thats even possible)?

Store it as a HTML in the table, on INSERT/UPDATE generate pdf and save to disk and keep only the file URL in the DB (saves ton of time on replication)

txt : string to convert
filename: save as …
folder: target folder

I created a custom type to accommodate the result - and to explain how to handle returns from python functions.

create type type_text2pdf as
(
url text,
file bytea
);
create function sm_text2pdf
(txt text, filename text, folder text
) returns type_text2pdf
language
plpython3u
as
$$
import pdfkit
import os
t,f = args[0],args[1]
fn='/files/'+folder+'/'+f
r=pdfkit.from_string(t,fn)
in_file=open(fn,"rb")
data=in_file.read()
return fn, data
$$;

And usage:

/*
select * from sm_text2pdf($$<html>yay!</html>$$,'a.pdf','docs');
*/

PDF will be saved as/files/docs/a.pdf

Function will return file URL and file itself

--

--