Spaces:
Running
Running
import io | |
import os | |
import fitz # PyMuPDF | |
pdf_path_dict = { | |
"old": "src/assets/InvitationTemplateCompressed.pdf", | |
"common": "src/assets/WWEC嘉宾邀请函mini.pdf", | |
"观礼": "src/assets/WWEC列席嘉宾邀请函.pdf", | |
"演讲": "src/assets/WWEC演讲嘉宾邀请函.pdf", | |
"致辞": "src/assets/WWEC演讲嘉宾邀请函.pdf", | |
} | |
# font_path = "src/assets/NotoSansHans-Regular.otf" | |
# other_font_path = "src/assets/SourceHanSansCN-VF-2.otf" | |
# other_font_path = "src/assets/ZhouZiSongTi7000Zi-2.otf" | |
font_path = "src/assets/字魂59号-创粗黑.ttf" | |
other_font_path = "src/assets/FangZhengHeiTiJianTi-1.ttf" | |
# font = fitz.Font(fontfile=font_path) | |
def getInvitationPDF(data): | |
pdf_path = pdf_path_dict[data["category"]] | |
doc = fitz.open(pdf_path) | |
for page in doc: | |
fields = page.widgets() | |
for field in fields: | |
if field.field_name in data: | |
# field.font = font | |
field.field_value = data[field.field_name] | |
field.update() | |
pdfStream = io.BytesIO() | |
doc.save(pdfStream) | |
doc.close() | |
if os.path.exists("src/assets/output"): | |
with open("src/assets/output/output.pdf", 'wb') as f: | |
f.write(pdfStream.getvalue()) | |
return pdfStream | |
def writeInvitationPDF(person): | |
font_size=30 | |
pdf_path = pdf_path_dict[person.category] | |
doc = fitz.open(pdf_path) | |
page = doc.load_page(1) | |
page.insert_font(fontname="name_font", fontfile=font_path) | |
page.insert_font(fontname="f", fontfile=font_path) | |
page.insert_text((145, 80), | |
person.name+person.title, fontname="name_font", fontsize=min(font_size, font_size*5/len(person.name+person.title)), color=(1, 1, 1)) | |
if person.category == "演讲" or person.category == "致辞": | |
page.insert_text((80, 375), | |
person.conference, fontname="f", fontsize=min(font_size, font_size*14/len(person.conference)), color=(1, 1, 1)) | |
pdfStream = io.BytesIO() | |
doc.save(pdfStream) | |
doc.close() | |
if os.path.exists("src/assets/output"): | |
with open("src/assets/output/output.pdf", 'wb') as f: | |
f.write(pdfStream.getvalue()) | |
return pdfStream | |
if __name__ == "__main__": | |
from collections import namedtuple | |
Person = namedtuple('Person', ['name', 'title', 'category', 'conference', 'respond_person']) | |
person = Person(name="周鸿祎", title="先生", category="致辞", conference="8月21日中欧智慧论坛,做主题演讲", respond_person="Eazy") | |
output_path = 'output/output.pdf' | |
# getInvitationPDF(data) | |
writeInvitationPDF(person) | |
# with open(output_path, 'wb') as f: | |
# f.write(pdfStream.getvalue()) |