CI / check (push) Failing after 15m48s
Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
134 lines
3.6 KiB
Python
134 lines
3.6 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""PDF 工具(Apache-2.0 友好依赖)
|
||
|
||
- 文本提取:PyPDF2(BSD-3-Clause)
|
||
- 页面渲染:pypdfium2(Apache-2.0,内置 PDFium BSD-3-Clause)
|
||
- 图像保存:Pillow(HPND)
|
||
|
||
用于替代原 PyMuPDF(AGPL/商业双许可),避免开源许可证冲突。
|
||
"""
|
||
import io
|
||
from pathlib import Path
|
||
|
||
|
||
def _as_stream(source):
|
||
if isinstance(source, (bytes, bytearray)):
|
||
return io.BytesIO(bytes(source)), True
|
||
return str(source), False
|
||
|
||
|
||
def _open_pdf(source):
|
||
from PyPDF2 import PdfReader
|
||
stream, own = _as_stream(source)
|
||
try:
|
||
return PdfReader(stream), None
|
||
finally:
|
||
if own:
|
||
pass
|
||
|
||
|
||
def page_count(source) -> int:
|
||
reader, _ = _open_pdf(source)
|
||
try:
|
||
return len(reader.pages)
|
||
finally:
|
||
try:
|
||
stream = getattr(reader, "stream", None)
|
||
if stream is not None:
|
||
stream.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def extract_text(source) -> str:
|
||
"""提取 PDF 全部文字;没有文字层时返回空字符串。"""
|
||
reader, _ = _open_pdf(source)
|
||
try:
|
||
parts = []
|
||
for page in reader.pages:
|
||
try:
|
||
parts.append(page.extract_text() or "")
|
||
except Exception:
|
||
parts.append("")
|
||
return "\n".join(parts)
|
||
finally:
|
||
try:
|
||
stream = getattr(reader, "stream", None)
|
||
if stream is not None:
|
||
stream.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def render_page_png(source, page_index: int = 0, scale: float = 1.6) -> bytes:
|
||
"""把指定页渲染为 PNG 字节。"""
|
||
import pypdfium2 as pdfium
|
||
stream, own = _as_stream(source)
|
||
pdf = pdfium.PdfDocument(stream)
|
||
try:
|
||
if page_index < 0 or page_index >= len(pdf):
|
||
raise IndexError("页码超出范围")
|
||
page = pdf[page_index]
|
||
try:
|
||
bitmap = page.render(scale=scale)
|
||
try:
|
||
image = bitmap.to_pil()
|
||
buf = io.BytesIO()
|
||
image.save(buf, format="PNG")
|
||
return buf.getvalue()
|
||
finally:
|
||
try:
|
||
bitmap.close()
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
try:
|
||
page.close()
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
try:
|
||
pdf.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def render_pages_png(source, scale: float = 2.0, max_pages: int = None) -> list:
|
||
"""批量渲染页面为 PNG 字节列表;max_pages 为空则全部渲染。"""
|
||
import pypdfium2 as pdfium
|
||
stream, own = _as_stream(source)
|
||
pdf = pdfium.PdfDocument(stream)
|
||
result = []
|
||
try:
|
||
total = len(pdf)
|
||
limit = total if not max_pages else min(total, max_pages)
|
||
for i in range(limit):
|
||
page = pdf[i]
|
||
try:
|
||
bitmap = page.render(scale=scale)
|
||
try:
|
||
image = bitmap.to_pil()
|
||
buf = io.BytesIO()
|
||
image.save(buf, format="PNG")
|
||
result.append(buf.getvalue())
|
||
finally:
|
||
try:
|
||
bitmap.close()
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
try:
|
||
page.close()
|
||
except Exception:
|
||
pass
|
||
return result
|
||
finally:
|
||
try:
|
||
pdf.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def is_pdf(path) -> bool:
|
||
return str(path).lower().endswith(".pdf")
|