Repository navigation
Expand file tree
/
Copy pathhtml2pdf.py
More file actions
171 lines (144 loc) · 5.69 KB
/
Copy pathhtml2pdf.py
File metadata and controls
171 lines (144 loc) · 5.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
"""html2pdf — 把单个网页转成 A4 PDF,尽量与浏览器所见一致。
用法:
uv run html2pdf.py <url> [-o out.pdf] [--mode full|content]
--mode full (默认) 桌面宽屏渲染,所见即所得
--mode content 隐藏侧边栏/顶栏等导航元素,只保留正文
核心逻辑为异步实现 (html2pdf_async),供 Web 后端复用同一个浏览器实例;
命令行入口通过 html2pdf() 同步包装调用。
"""
import argparse
import asyncio
import re
import sys
from playwright.async_api import Browser, async_playwright
# 分页修复:避免代码块/图片/表格被拦腰截断;fixed/sticky 元素改为 absolute,
# 防止顶栏在每一页重复出现。
FIX_CSS = """
pre, code, img, table, figure, blockquote {
break-inside: avoid;
}
* {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
}
"""
FIX_JS = """
() => {
for (const el of document.querySelectorAll('*')) {
const s = getComputedStyle(el);
if (s.position === 'fixed' || s.position === 'sticky') {
el.style.position = 'absolute';
}
}
// 展开内部滚动容器,让文档高度等于完整内容高度(否则 PDF 只有一屏)
for (const el of document.querySelectorAll('*')) {
const s = getComputedStyle(el);
if ((s.overflowY === 'auto' || s.overflowY === 'scroll') &&
el.scrollHeight > el.clientHeight) {
el.style.overflow = 'visible';
el.style.height = el.scrollHeight + 'px';
el.style.maxHeight = 'none';
// 祖先链一并放开,避免被外层固定高度卡住
let a = el.parentElement;
while (a && a !== document.documentElement) {
a.style.overflow = 'visible';
a.style.height = 'auto';
a.style.maxHeight = 'none';
a = a.parentElement;
}
}
}
}
"""
# content 模式:隐藏常见文档站点的导航元素 (VitePress / Docsify / GitBook / Docusaurus)
CONTENT_CSS = """
nav, aside, .VPNav, .VPSidebar, .VPLocalNav, .sidebar, .sidebar-links,
.toc, .table-of-contents, .theme-doc-sidebar-container, .navbar,
.gitbook-navigation, header.site-header, .mdl-layout__header, .app-nav {
display: none !important;
}
.VPContent, .VPContent.has-sidebar, .content, main, .theme-default-content,
.markdown-section, article {
margin-left: 0 !important;
padding-left: 16px !important;
padding-right: 16px !important;
max-width: 100% !important;
width: 100% !important;
}
"""
# 滚动 window 和所有内部滚动容器,触发懒加载内容
SCROLL_JS = """
async () => {
const scrollables = [window];
for (const el of document.querySelectorAll('*')) {
const s = getComputedStyle(el);
if ((s.overflowY === 'auto' || s.overflowY === 'scroll') &&
el.scrollHeight > el.clientHeight) {
scrollables.push(el);
}
}
const step = 800;
for (const target of scrollables) {
const getHeight = () => target === window
? document.documentElement.scrollHeight : target.scrollHeight;
const getPos = () => target === window ? window.scrollY : target.scrollTop;
const doScroll = (y) => target === window
? window.scrollTo(0, y) : (target.scrollTop = y);
for (let y = 0; y <= getHeight(); y += step) {
doScroll(y);
await new Promise(r => setTimeout(r, 30));
}
doScroll(0);
}
}
"""
def sanitize_filename(title: str) -> str:
name = re.sub(r'[\\/:*?"<>|]', '_', title).strip()
return name or 'output'
async def html2pdf_async(browser: Browser, url: str, output: str | None, mode: str) -> str:
"""用已有的 browser 实例转换单个页面,返回输出文件路径。"""
context = await browser.new_context(viewport={'width': 1440, 'height': 900})
try:
page = await context.new_page()
await page.emulate_media(media='screen')
await page.goto(url, wait_until='networkidle', timeout=60_000)
# 滚动整页触发懒加载,然后回到顶部
await page.evaluate(SCROLL_JS)
await page.wait_for_timeout(600)
await page.add_style_tag(content=FIX_CSS)
await page.evaluate(FIX_JS)
if mode == 'content':
await page.add_style_tag(content=CONTENT_CSS)
await page.wait_for_timeout(400)
if output is None:
output = sanitize_filename(await page.title()) + '.pdf'
await page.pdf(
path=output,
format='A4',
print_background=True,
margin={'top': '12mm', 'bottom': '12mm', 'left': '12mm', 'right': '12mm'},
)
return output
finally:
await context.close()
def html2pdf(url: str, output: str | None, mode: str) -> str:
"""同步包装:命令行使用,每次自起浏览器。"""
async def _run() -> str:
async with async_playwright() as p:
browser = await p.chromium.launch()
try:
return await html2pdf_async(browser, url, output, mode)
finally:
await browser.close()
return asyncio.run(_run())
def main() -> None:
parser = argparse.ArgumentParser(description='把网页转成 A4 PDF')
parser.add_argument('url', help='要转换的页面 URL')
parser.add_argument('-o', '--output', help='输出 PDF 路径(默认取页面标题)')
parser.add_argument('--mode', choices=['full', 'content'], default='full',
help='full=所见即所得(默认); content=只保留正文')
args = parser.parse_args()
path = html2pdf(args.url, args.output, args.mode)
print(f'已生成: {path}')
if __name__ == '__main__':
sys.exit(main())