Skip to content

Commit 2665775

Browse files
Remove pango dependency (#271)
* Removed wasyprint(and pango) dependency as we are defaulting to xhtml2pdf library now. * Documentation changes. * Ruff fixes.
1 parent cd0639e commit 2665775

11 files changed

Lines changed: 82 additions & 40 deletions

File tree

docs/gh_pages/docs/config.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ Notes:
2323

2424
- `format`: Specifies the format of generated reports. Available options include 'pdf'.
2525
- `renderer`: Specifies the rendering engine for generating reports. Options include 'weasyprint', 'xhtml2pdf'.
26+
Note: If you put renderer as `weasyprint`, then you need to install Pango. Follow [these instructions](./installation.md#pre-requisites) for the same.
2627
- `outputDir`: Defines the directory where generated reports will be saved.
2728

2829
### Classifier

docs/gh_pages/docs/development.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ The following instructions are **tested on Mac OSX and Linux (Debian).**
99

1010
### Prerequisites
1111

12-
Install the following prerequisites. This is needed for PDF report generation.
12+
Install the following prerequisites. This is needed for PDF report generation,
13+
14+
if you have put `weasyprint` as renderer in the config.yaml
1315

1416
#### Mac OSX
1517

@@ -23,6 +25,11 @@ brew install pango
2325
sudo apt-get install libpango-1.0-0 libpangoft2-1.0-0
2426
```
2527

28+
### Install weasyprint library
29+
```sh
30+
pip install weasyprint
31+
```
32+
2633
## Build, Install and Run
2734

2835
Fork and clone the pebblo repo. From within the pebblo directory, create a python virtual-env, build pebblo package (in `wheel` format), install and run.

docs/gh_pages/docs/installation.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
> Please note that Pebblo requires Python version 3.9 or above to function optimally.
55
66
### Pre-requisites
7+
Install the following prerequisites. This is needed for PDF report generation,
8+
if you have put `weasyprint` as renderer in the config.yaml
79

810
#### Mac OSX
911

@@ -17,6 +19,11 @@ brew install pango
1719
sudo apt-get install libpango-1.0-0 libpangoft2-1.0-0
1820
```
1921

22+
### Install weasyprint library
23+
```sh
24+
pip install weasyprint
25+
```
26+
2027
### Pebblo Server
2128

2229
```

pebblo/app/config/service.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@
88
from fastapi import FastAPI, Response
99
from fastapi.staticfiles import StaticFiles
1010

11+
from pebblo.app.exceptions.exception_handler import exception_handlers
1112
from pebblo.app.routers.local_ui_routers import local_ui_router_instance
1213
from pebblo.app.routers.redirection_router import redirect_router_instance
13-
from pebblo.app.exceptions.exception_handler import exception_handlers
1414

1515
with redirect_stdout(StringIO()), redirect_stderr(StringIO()):
1616
from pebblo.app.routers.routers import router_instance

pebblo/app/exceptions/exception_handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1+
from fastapi import Request
12
from fastapi.exceptions import HTTPException
23
from fastapi.responses import RedirectResponse
3-
from fastapi import Request
44

55

66
async def not_found_error(request: Request, exc: HTTPException):

pebblo/app/service/service.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def _write_pdf_report(self, final_report):
4040
f"/{load_id}/{CacheDir.REPORT_FILE_NAME.value}"
4141
)
4242
full_file_path = get_full_path(current_load_report_file_path)
43-
report_obj.generate_report(
43+
_, _ = report_obj.generate_report(
4444
data=final_report,
4545
output_path=full_file_path,
4646
format_string=report_format,
@@ -53,13 +53,16 @@ def _write_pdf_report(self, final_report):
5353
f"/{CacheDir.REPORT_FILE_NAME.value}"
5454
)
5555
full_file_path = get_full_path(current_app_report_file_path)
56-
report_obj.generate_report(
56+
status, result = report_obj.generate_report(
5757
data=final_report,
5858
output_path=full_file_path,
5959
format_string=report_format,
6060
renderer=renderer,
6161
)
62-
logger.info(f"PDF report generated, please check path : {full_file_path}")
62+
if not status:
63+
logger.error(f"PDF report is not generated. {result}")
64+
else:
65+
logger.info(f"PDF report generated, please check path : {full_file_path}")
6366

6467
def _upsert_loader_details(self, app_details):
6568
"""

pebblo/reports/html_to_pdf_generator/generator_functions.py

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,37 @@
44

55
import os
66

7-
from weasyprint import CSS, HTML
8-
from xhtml2pdf import pisa
9-
107

118
# Creates PDF from template using weasyprint
129
def weasyprint_pdf_converter(source_html, output_path, search_path):
1310
"""PDF generator function for weasyprint renderer"""
14-
base_url = os.path.dirname(os.path.realpath(__file__))
15-
html_doc = HTML(string=source_html, base_url=base_url)
16-
return html_doc.write_pdf(
17-
target=output_path, stylesheets=[CSS(search_path + "/index.css")]
18-
)
11+
try:
12+
from weasyprint import CSS, HTML
13+
14+
base_url = os.path.dirname(os.path.realpath(__file__))
15+
html_doc = HTML(string=source_html, base_url=base_url)
16+
result = html_doc.write_pdf(
17+
target=output_path, stylesheets=[CSS(search_path + "/index.css")]
18+
)
19+
return True, result
20+
except ImportError:
21+
error = """Could not import weasyprint package. Please install weasyprint and Pango to generate report using weasyprint.
22+
Follow documentation for more details - https://daxa-ai.github.io/pebblo/installation"
23+
"""
24+
return False, error
25+
except Exception as e:
26+
return False, e
1927

2028

2129
# Creates PDF from template using xhtml2pdf
2230
def xhtml2pdf_pdf_converter(source_html, output_path, _):
2331
"""PDF generator function for xhtml2pdf renderer"""
24-
with open(output_path, "w+b") as result_file:
25-
pisa_status = pisa.CreatePDF(src=source_html, dest=result_file)
26-
result_file.close()
27-
return pisa_status.err
32+
try:
33+
from xhtml2pdf import pisa
34+
35+
with open(output_path, "w+b") as result_file:
36+
pisa_status = pisa.CreatePDF(src=source_html, dest=result_file)
37+
result_file.close()
38+
return True, pisa_status.err
39+
except Exception as e:
40+
return False, e

pebblo/reports/html_to_pdf_generator/report_generator.py

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33
"""
44

55
import datetime
6+
import time
67
from decimal import Decimal
78

89
import jinja2
910

1011
from pebblo.reports.enums.report_libraries import library_function_mapping
11-
import time
12+
from pebblo.reports.libs.logger import logger
1213

1314

1415
def date_formatter(date_obj):
@@ -30,21 +31,28 @@ def get_file_size(size):
3031

3132

3233
def convert_html_to_pdf(data, output_path, template_name, search_path, renderer):
33-
"""Convert HTML Template to PDF by embedding JSON data"""
34-
template_loader = jinja2.FileSystemLoader(searchpath=search_path)
35-
template_env = jinja2.Environment(loader=template_loader)
36-
template = template_env.get_template(template_name)
37-
current_date = (
38-
datetime.datetime.now().strftime("%B %d, %Y") + " " + time.localtime().tm_zone
39-
)
40-
source_html = template.render(
41-
data=data,
42-
date=current_date,
43-
datastores=data["dataSources"][0],
44-
findingDetails=data["dataSources"][0]["findingsDetails"],
45-
loadHistoryItemsToDisplay=data["loadHistory"]["history"],
46-
dateFormatter=date_formatter,
47-
getFileSize=get_file_size,
48-
)
49-
pdf_converter = library_function_mapping[renderer]
50-
pdf_converter(source_html, output_path, search_path)
34+
try:
35+
"""Convert HTML Template to PDF by embedding JSON data"""
36+
template_loader = jinja2.FileSystemLoader(searchpath=search_path)
37+
template_env = jinja2.Environment(loader=template_loader)
38+
template = template_env.get_template(template_name)
39+
current_date = (
40+
datetime.datetime.now().strftime("%B %d, %Y")
41+
+ " "
42+
+ time.localtime().tm_zone
43+
)
44+
source_html = template.render(
45+
data=data,
46+
date=current_date,
47+
datastores=data["dataSources"][0],
48+
findingDetails=data["dataSources"][0]["findingsDetails"],
49+
loadHistoryItemsToDisplay=data["loadHistory"]["history"],
50+
dateFormatter=date_formatter,
51+
getFileSize=get_file_size,
52+
)
53+
pdf_converter = library_function_mapping[renderer]
54+
status, result = pdf_converter(source_html, output_path, search_path)
55+
return status, result
56+
except Exception as e:
57+
logger.error(e)
58+
return False, ""

pebblo/reports/reports.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,15 @@ def generate_report(
3232
search_path = os.path.join(os.path.dirname(__file__), "templates/")
3333
try:
3434
template_name = template_renderer_mapping[renderer]
35-
convert_html_to_pdf(
35+
status, result = convert_html_to_pdf(
3636
data,
3737
output_path,
3838
template_name=template_name,
3939
search_path=search_path,
4040
renderer=renderer,
4141
)
42+
return status, result
43+
4244
except KeyError as e:
4345
logger.error(
4446
"Renderer %s not supported. Please use supported renderers: "
@@ -48,5 +50,7 @@ def generate_report(
4850
ReportLibraries.XHTML2PDF,
4951
e,
5052
)
53+
return False, ""
5154
else:
5255
logger.error("Output file format %s not supported", format)
56+
return False, ""

pyproject.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,6 @@ dependencies = [
115115
"jinja2>=3.1.3",
116116
"tqdm",
117117
"xhtml2pdf==0.2.15",
118-
"weasyprint==60.2",
119118
]
120119

121120
# List additional groups of dependencies here (e.g. development

0 commit comments

Comments
 (0)