数据表生成:按需和批量 PDF 创建
本文介绍了我们如何生成产品数据表 PDF,包括按需生成(用户请求时)和批量生成(为热门产品预生成)。
问题:创建产品数据表
每个产品都需要一份专业的 PDF 数据表,包含:
-
产品名称和图片
-
按类别分组的技术规格
-
公司品牌和联系信息
-
优化布局(单页、均衡分栏)
每次请求都生成 PDF 速度很慢(每个 PDF 约 2 秒)。预生成全部 65,000 个 SKU 会浪费存储空间和时间。
解决方案:混合方案
我们使用两种生成方式:
按需生成:用户请求时生成 PDF(首次)
批量生成:为热门产品预生成 PDF(每晚)
按需生成
URL 结构
/ds/<sku>.pdf
/ds/<sku>
两个 URL 生成相同的 PDF。
请求流程
@web.route("/ds/<sku>.pdf")
def datasheet(sku: str):
# Validate SKU
# ... (implementation details omitted)
生成过程
步骤 1:获取产品数据
# Product name
name = expand_sku(sku)
# ... (implementation details omitted)
步骤 2:均衡分栏
将特性分布到 3 列中以均衡行数:
# Calculate lines per feature group
all_groups = []
for heading, f_items in features.items():
# ... (implementation details omitted)
步骤 3:计算图片高度
# Main image height (proportional to aspect ratio)
with Image.open(main_image_path) as img:
main_width, main_height = img.size
# ... (implementation details omitted)
步骤 4:计算间隔
将页脚推至页面底部:
available_height = 25.0 # cm
content_height = total_image_height + text_height_cm
spacer_height = max(0, available_height - content_height)
步骤 5:渲染 HTML
html = render_template(
"datasheet.html",
sku=sku,
# ... (implementation details omitted)
步骤 6:生成 PDF
options = {
"page-size": "A4",
"enable-local-file-access": None,
"load-error-handling": "ignore",
"load-media-error-handling": "ignore",
"no-stop-slow-scripts": None
}
pdf_data = pdfkit.from_string(html, options=options)
步骤 7:仅保留第一页
reader = PdfReader(BytesIO(pdf_data))
if len(reader.pages) > 1:
writer = PdfWriter()
writer.add_page(reader.pages[0])
output = BytesIO()
writer.write(output)
pdf_data = output.getvalue()
性能
生成时间:每个 PDF 约 2 秒
缓存:无缓存(始终最新)
优势:始终与最新产品数据保持同步
批量生成
目的
为热门产品预生成 PDF,以减少按需生成的负载。
脚本位置
scripts/utils/generate_datasheets.py
跟踪变更
我们跟踪 productdb.json 中与每个 SKU 相关的部分的变更:
def get_sku_productdb_hash(sku: str) -> str:
"""Get hash of productdb sections relevant to this SKU."""
with open(PRODUCTDB_PATH, "r") as f:
# ... (implementation details omitted)
优先级排序
我们按请求频率对 SKU 进行优先级排序:
def load_popular_skus() -> List[str]:
"""Load popular SKUs from access logs."""
try:
# ... (implementation details omitted)
生成策略
def batch_generate():
# Load hash cache
hash_cache = load_hash_cache()
# ... (implementation details omitted)
调度
批量生成通过 cron 每晚运行:
0 2 * * * cd /home/ubuntu/manage && python scripts/utils/generate_datasheets.py
存储
本地:/home/ubuntu/web-static/ds/<sku>.pdf
S3:s3://thinvent-web-static/ds/<sku>.pdf
CDN:通过 CloudFront 分发
模板结构
数据表模板使用 3 列布局:
<div class="container">
<!-- Header with logo and product name -->
<div class="header">
<img src="/s/logo.png">
<h1>{{ name }}</h1>
</div>
<!-- Main image -->
<img src="{{ images[0][1] }}" style="width: 9.5cm">
<!-- Thumbnails (up to 4) -->
<div class="thumbnails">
{% for name, url in images[1:5] %}
<img src="{{ url }}" style="width: 4.5cm">
{% endfor %}
</div>
<!-- Features in 3 columns -->
<div class="features">
<div class="column">
{% for heading, items in features1 %}
<h3>{{ heading }}</h3>
{% for name, value in items.items() %}
<div><strong>{{ name }}:</strong> {{ value }}</div>
{% endfor %}
{% endfor %}
</div>
<div class="column">
<!-- features2 -->
</div>
<div class="column">
<!-- features3 -->
</div>
</div>
<!-- Spacer to push footer down -->
<div style="height: {{ spacer_height }}cm"></div>
<!-- Footer with contact info -->
<div class="footer">
<p>www.thinvent.in | sales@thinvent.in | +91-124-4343177</p>
</div>
</div>
配置
常量控制布局:
DATASHEET_COLUMN_COUNT = 3
DATASHEET_HEADING_LINE_WEIGHT = 2 # Lines per heading
DATASHEET_FEATURE_NAME_MAX_LEN = 30 # Chars before wrapping
DATASHEET_FEATURE_VALUE_CHARS_PER_LINE = 40 # Chars per line
PDF_PAGE_SIZE = "A4"
集成点
产品页面
链接到数据表:
<a href="/ds/{{ sku }}.pdf" target="_blank">Download Datasheet</a>
Google Shopping
数据表链接在产品 Feed 中:
<g:product_detail>
<g:section_name>Datasheet</g:section_name>
<g:attribute_name>PDF</g:attribute_name>
<g:attribute_value>https://www.thinvent.in/ds/{{ sku }}.pdf</g:attribute_value>
</g:product_detail>
邮件营销
数据表作为附件添加到报价邮件中。
错误处理
无效 SKU
if not check_sku(sku):
abort(422, description="Product not found.")
生成失败
try:
pdf_data = generate_datasheet_pdf(sku)
if pdf_data is None:
abort(500, description="PDF generation failed.")
except Exception as e:
logger.error(f"PDF generation failed for {sku}: {e}")
abort(500, description="PDF generation failed.")
图片缺失
try:
with Image.open(image_path) as img:
width, height = img.size
except Exception:
# Use default dimensions
width, height = 800, 600
参考资料
库
相关文章
总结
数据表生成采用混合方案:
按需生成:
-
用户请求时生成
-
始终最新
-
无存储浪费
-
每个 PDF 约 2 秒
批量生成:
-
预生成热门产品
-
跟踪 productdb 变更
-
按请求频率优先级排序
-
每晚 cron 任务
流程:
-
获取产品数据(名称、图片、特性、描述)
-
将特性均衡分配到 3 列
-
计算图片高度
-
渲染 HTML 模板
-
使用 pdfkit 生成 PDF
-
仅保留第一页
存储:
-
本地:
/home/ubuntu/web-static/ds/ -
S3:
s3://thinvent-web-static/ds/ -
CDN:CloudFront 分发
这种混合方案在新鲜度(按需生成)和性能(批量预生成)之间取得平衡。