Created
April 24, 2024 17:38
-
-
Save mtanco/22e85fd2db77edd1d3d5203cad7bce74 to your computer and use it in GitHub Desktop.
Render files as pdfs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from h2o_wave import main, app, Q, ui | |
import os | |
from docx import Document | |
from openpyxl import load_workbook | |
from reportlab.pdfgen import canvas | |
from reportlab.lib.pagesizes import letter | |
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle | |
from reportlab.lib import colors | |
# from msgpy import MSG | |
@app('/') | |
async def serve(q: Q): | |
q.page["meta"] = ui.meta_card( | |
box="", | |
layouts=[ | |
ui.layout( | |
breakpoint="l", | |
zones=[ | |
ui.zone("content", direction="row", size="1"), | |
] | |
) | |
] | |
) | |
files = ["data/This is a fake document.docx", "data/fake.xlsx"] | |
for i in range(len(files)): | |
local_pdf_url = convert_to_pdf(files[i]) | |
wave_url, = await q.site.upload([local_pdf_url]) | |
os.remove(local_pdf_url) | |
q.page[f"card_{i}"] = ui.frame_card( | |
box="content", | |
title="", | |
path=wave_url | |
) | |
await q.page.save() | |
def convert_to_pdf(input_file): | |
file_name, file_extension = os.path.splitext(input_file) | |
pdf_file_name = file_name + ".pdf" | |
if file_extension.lower() == ".docx": | |
doc = Document(input_file) | |
pdf_canvas = canvas.Canvas(pdf_file_name, pagesize=letter) | |
for paragraph in doc.paragraphs: | |
pdf_canvas.drawString(50, 750, paragraph.text) | |
pdf_canvas.showPage() | |
pdf_canvas.save() | |
elif file_extension.lower() == ".xlsx": | |
wb = load_workbook(input_file) | |
pdf = SimpleDocTemplate(pdf_file_name, pagesize=letter) | |
story = [] | |
for sheet_name in wb.sheetnames: | |
sheet = wb[sheet_name] | |
data = [] | |
for row in sheet.iter_rows(values_only=True): | |
data.append(row) | |
table = Table(data) | |
table.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey), | |
('TEXTCOLOR', (0, 0), (-1, 0), colors.black), | |
('ALIGN', (0, 0), (-1, -1), 'CENTER'), | |
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), | |
('BOTTOMPADDING', (0, 0), (-1, 0), 12), | |
('BACKGROUND', (0, 1), (-1, -1), colors.beige), | |
('GRID', (0, 0), (-1, -1), 1, colors.black)])) | |
story.append(table) | |
pdf.build(story) | |
elif file_extension.lower() == ".pdf": | |
pass | |
# elif file_extension.lower() == ".msg": | |
# msg = MSG(input_file) | |
# text_content = msg.body | |
# pdf = SimpleDocTemplate(pdf_file_name, pagesize=letter) | |
# story = [text_content] | |
# pdf.build(story) | |
else: | |
raise ValueError("Unsupported file format") | |
return pdf_file_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment