避开这些坑!用Python ReportLab生成PDF时字体处理与中文排版的5个关键技巧

避坑指南:Python处理Word转PDF时格式错乱怎么办?(附完整代码示例) 本文深入剖析了Python处理Word转PDF时格式错乱的根源,如字体缺失、表格扭曲和图片漂移,并提供了完整的解决方案。通过结合python-docx、reportlab等库,详细讲解了字体映射、表格精确绘制和图片位置校准等关键技术,附有完整代码示例,帮助开发者构建高保真的批量转换脚本,有效避免商业文档转换中的专业性问题。 阅读详情

避开这些坑!用Python ReportLab生成PDF时字体处理与中文排版的5个关键技巧

如果你曾经尝试用Python的ReportLab库生成一份包含中文内容的PDF报告,大概率经历过那种“代码跑通了,但PDF打开全是方框”的绝望。或者,你费了九牛二虎之力,终于让文字显示出来了,却发现段落缩进乱七八糟,换行位置诡异,表格里的中文挤成一团。这几乎是每个国内开发者在初次接触ReportLab进行PDF自动化生成时,都会踩到的“坑”。

ReportLab本身是一个功能强大、灵活性极高的PDF生成库,但它的设计初衷和默认配置,完全是面向英文等拉丁语系文字的。当它遇到中文这种复杂的表意文字系统时,从字体渲染、字符编码到排版规则,都会出现“水土不服”。网上能找到的教程,大多基于英文场景,把那些代码直接套用到中文上,往往就是各种乱码和错位的开始。

这篇文章,我将结合自己多次在商业项目中用ReportLab生成复杂中文PDF报告(动辄几十页,包含图文、表格、图表)的实战经验,为你梳理出五个最核心、也最容易出问题的关键技巧。这些技巧不是简单的API调用说明,而是深入到字体注册机制、样式继承逻辑、布局计算原理层面的“避坑指南”。掌握了它们,你不仅能解决眼前的中文显示问题,更能建立起一套稳健、可维护的PDF生成框架,从容应对各种复杂的排版需求。

1. 字体注册:超越“SimSun”的稳健策略

一提到ReportLab中文,很多人第一反应就是注册“SimSun”(宋体)。这没错,但仅仅这样做,离“稳健”还差得很远。字体注册是中文PDF生成的基石,这块基石不稳,后面所有精美的排版都是空中楼阁。

1.1 理解TTFont与字体文件路径的“陷阱”

ReportLab通过 pdfmetrics.registerFont(TTFont(...)) 来注册字体。这里的核心是 TTFont 类,它加载的是 .ttf 或 .ttc 字体文件。第一个坑就是字体文件路径。

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

# 常见但脆弱的做法 - 使用相对路径
pdfmetrics.registerFont(TTFont('MySimSun', './fonts/simsun.ttc'))

上面的代码在开发时可能运行良好,但一旦你的脚本被其他模块调用,或者被打包成可执行文件,这个相对路径 ./fonts/simsun.ttc 很可能就失效了,导致 TTFError。更可靠的做法是使用绝对路径,或者通过Python的路径管理工具来定位资源。

import os
from pathlib import Path

# 方法一:使用绝对路径(适合配置固定的环境)
font_path = r'C:\Windows\Fonts\simsun.ttc'  # Windows
# font_path = '/System/Library/Fonts/STHeiti Medium.ttc'  # macOS (注意字体名不同)
# font_path = '/usr/share/fonts/truetype/wqy/wqy-microhei.ttc'  # Linux

# 方法二:基于当前文件定位资源(更灵活)
current_dir = Path(__file__).parent.absolute()
font_path = current_dir / 'assets' / 'fonts' / 'SourceHanSansCN-Regular.ttf'

if font_path.exists():
    pdfmetrics.registerFont(TTFont('MyHeiTi', str(font_path)))
else:
    # 优雅降级:尝试系统字体或提示用户
    raise FileNotFoundError(f"字体文件未找到: {font_path}")

注意:直接使用Windows系统字体目录(如C:\Windows\Fonts)下的文件时,有些字体是.ttc(TrueType Collection,字体集合),一个文件包含多个字重变体。TTFont 可以加载.ttc,但你需要知道具体字体在集合中的索引,或者使用字体家族名。稳妥起见,对于商业项目,我强烈建议将需要用到的字体文件(.ttf)打包到项目资源目录中,避免依赖用户操作系统的字体环境。

1.2 多字重与字体家族管理

一份专业的中文报告,通常需要用到常规体、粗体、甚至斜体来区分标题、强调内容等。在英文中,Helvetica 和 Helvetica-Bold 是独立的字体文件。在中文里,我们同样需要注册多个字重。

# 注册一个完整的中文字体家族
font_dir = Path('./fonts')
pdfmetrics.registerFont(TTFont('SourceHanSansCN', font_dir / 'SourceHanSansCN-Regular.ttf'))
pdfmetrics.registerFont(TTFont('SourceHanSansCN-Bold', font_dir / 'SourceHanSansCN-Bold.ttf'))
# 注意:很多中文字体没有真正的斜体(Italic),通常用常规体或忽略。
# pdfmetrics.registerFont(TTFont('SourceHanSansCN-Italic', font_dir / 'SourceHanSansCN-Italic.ttf'))

# 在样式中使用
styles = getSampleStyleSheet()
title_style = styles['Heading1']
title_style.fontName = 'SourceHanSansCN-Bold'  # 标题用粗体

body_style = styles['Normal']
body_style.fontName = 'SourceHanSansCN'  # 正文用常规体

这里有一个高级技巧:ReportLab的 Paragraph 样式支持 fontName,但不直接支持CSS那样的 font-weight 属性。这意味着,如果你在段落文本中使用了 <b> 标签,ReportLab会尝试寻找一个名为 [当前字体名]-Bold 的已注册字体。所以,如果你注册了 'MyFont' 和 'MyFont-Bold',那么在 Paragraph 中使用 <b>加粗</b> 时,加粗部分会自动切换到 'MyFont-Bold'。确保你的粗体字体注册名是 基础字体名-Bold 这个格式,这个机制才会生效。

1.3 字体回退与异常处理

即使你注册了字体,也可能因为字体文件损坏、字符缺失(某些生僻字)导致渲染失败。一个健壮的系统应该有回退机制。

def safe_register_font(primary_font_name, primary_font_path, fallback_font_name='SimSun', fallback_font_path=None):
    """
    安全注册字体,提供回退方案。
    """
    registered_fonts = pdfmetrics.getRegisteredFontNames()
    
    try:
        if primary_font_name not in registered_fonts:
            pdfmetrics.registerFont(TTFont(primary_font_name, primary_font_path))
            print(f"主字体 {primary_font_name} 注册成功。")
        else:
            print(f"主字体 {primary_font_name} 已注册。")
    except Exception as e:
        print(f"警告:注册主字体 {primary_font_name} 失败: {e}")
        # 尝试注册回退字体
        if fallback_font_path and fallback_font_name not in registered_fonts:
            try:
                # 通常SimSun在Windows系统中广泛存在,作为最后保障
                pdfmetrics.registerFont(TTFont(fallback_font_name, fallback_font_path))
                print(f"已注册回退字体 {fallback_font_name}。")
                return fallback_font_name
            except:
                # 如果连回退字体都失败,尝试使用ReportLab内置的CID字体(对中文支持有限)
                print("严重错误:无法注册任何中文字体。PDF中文将无法显示。")
                return 'Helvetica' # 最终回退到英文
        return fallbac
免费实现PDF双语对照翻译:Python自动化方案与排版保持技巧 PDF作为跨平台文档格式,其核心价值在于稳定的版式呈现。传统翻译工具常因无法解析PDF内部结构,导致翻译后格式错乱、图文丢失。通过Python生态中的pdfplumber、PyMuPDF等库,可以精准提取文本、样式及位置信息,结合百度翻译等免费API进行智能翻译,再利用reportlab或WeasyPrint进行版式重构,最终实现排版不变的双语对照PDF生成。这一技术方案在学术文献、技术手册、法律合同等需要精准对照的场景中具有重要应用价值,有效解决了格式解析与内容翻译的协同难题。 阅读详情

相关推荐

Python PDF处理全栈指南:文本提取、OCR识别与智能编辑

PDF作为最广泛使用的文档格式,其本质是包含文本指令或图像对象的复合结构。理解PDF类型(文字型/扫描型/混合型)是自动化处理的前提,决定应采用纯文本解析、布局感知提取还是OCR识别等不同技术路径。PyPDF4、pypdf适用于高效提取结构化字段;pdfplumber擅长还原复杂表格与多栏排版;pymupdf结合easyocr可攻克扫描件与图像型PDF;而混合型PDF需构建智能路由Pipeline。这些技术已深度应用于财务票据批量处理、法律文书关键信息抽取、高校科研论文数据挖掘等真实场景,显著提升非结构化文

weixin_34109408的博客 448

Python自动化处理PDF和Word文档实战指南

PDF和Word文档自动化是办公提效的核心技术,其本质在于对文档结构的理解与程序化操控。基于Open XML标准和PDF规范,Python通过pypdf、python-docx等库实现文本提取、页面合并、样式控制与跨格式兼容等关键能力。这些技术不依赖AI模型,却能显著降低重复性人工操作成本,在合同管理、采购单处理、教务归档等场景中具备极强落地性。本文聚焦真实办公环境中的高频痛点——扫描件识别盲区、中文乱码、图片变形、书签丢失与密码安全,提供经Windows 11+Python 3.11+Office 365

weixin_34284188的博客 373

reportlab 使用中文报错 reportlab.pdfbase.ttfonts.TTFError: Not a recognized TrueType font

请确保使用的是TrueType或OpenType字体文件,并且字体文件没有损坏。另外,请确保使用的字体文件与您的操作系统兼容,因为有些字体文件可能只适用于特定的操作系统。如果您使用的是Windows操作系统,可以尝试使用simsun.ttc字体文件而不是simsun.ttf字体文件注册字体。在使用reportlab中注册字体时,需要使用TrueType字体文件(.ttf)或OpenType字体文件(.otf)。我切换为使用 simsun.ttc 就没有问题了,window系统 ,附上下载链接。

三维点云技术探索 2251

libharu实战:用C/C++轻量生成PDF文档与中文字体集成指南

在C/C++服务端或嵌入式环境中,程序化生成PDF常面临依赖重、体积大、中文支持难等痛点。PDF作为一种结构化文档格式,本质由页面、字体、内容流等对象组成,而轻量级C库libharu恰好提供了直接操作这些对象的底层能力。它仅依赖zlib和libpng,静态库体积小巧,适合资源受限场景。通过理解其坐标系统、字体注册与内容流绘制原理,开发者可以像操作画布一样生成报告、清单和票据。从编译接入到核心API调用,再到中文字体嵌入与自动排版,本文梳理了使用libharu高效产出PDF的完整路径,并给出了规避常见坑点的工

weixin_33984032的博客 405

基于 LSTM 的船舶轨迹预测,单步预测

基于 LSTM 的船舶轨迹预测,单步预测

fyuhao的博客 1万+

实战指南:基于华为Ascend NPU的大模型W8A8量化调优与精度提升

本文提供了一份基于华为Ascend NPU进行大模型W8A8量化的实战调优指南。详细介绍了从环境搭建、使用msmodelslim框架进行基础量化,到通过离群值抑制、校准集优化和量化回退等关键技术提升精度的全流程。旨在帮助开发者在华为NPU硬件上实现模型推理的显著加速,同时有效控制精度损失。

weixin_29227425的博客 279

Bertopic库安装(二)

Bertopic库安装

weixin_43392789的博客 4898

ESP32-CAM与Thonny的完美搭配:从烧录到通信的完整流程

本文详细介绍了如何将ESP32-CAM与Thonny IDE完美结合,从固件烧录到通信测试的完整流程。通过硬件连接、MicroPython固件烧录、Thonny环境配置以及摄像头功能开发等步骤,帮助开发者快速搭建高效的物联网开发环境,实现图像采集与无线通信功能。

tomato的博客 1136

simulink中无迹卡尔曼(UKF)模块使用

simulink的UKF模块简单说明

qq_41059950的博客 2830

基于毫米波雷达的智能风扇算法设计与实现

摘要:本文设计了一种基于毫米波雷达的智能风扇控制系统,采用FMCW雷达实现人体目标的精准检测与定位。系统通过距离FFT、速度FFT、CFAR检测和AoA估计构建完整的信号处理链路,并针对风扇叶片干扰设计了基于自相关函数的抗干扰算法。创新性地提出了人在开机、多人优先送风、摇头追踪等控制策略。研究采用MATLAB完成全链路算法仿真验证,并在STM32平台上实现实物系统。实验表明,该系统可实现0.15m测距精度和±60°方位角覆盖,有效解决了传统风扇的能源浪费和用户体验问题。本文提供了完整的MATLAB仿真代码和

huanghm88的专栏 407

【图像去噪】论文复现:灵感源自MAE!进一步解决BSN的局限性,破坏真实噪声的空间相关性!AMSNet的Pytorch源码复现,跑通源码,原理详解!

论文题目:Asymmetric Mask Scheme for Self-Supervised Real Image Denoising —— 自监督真实图像去噪的非对称掩码方案【图像去噪】论文精读:Asymmetric Mask Scheme for Self-Supervised Real Image Denoising(AMSNet)AMSNet是基于PyTorch Lightning CLI深度学习框架编写的,比较适合复杂的大型任务,复用很方便,但是安装和环境配置问题太多。

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 550

LabVIEW实现TCP通信

在本节中,我们将简要探讨TCP通信的基础知识,并以工业物联网平台TLINK中的云端设备数据发布设计为例,详细阐述在互联网环境下TCP客户端应用程序设计的基本方法。

不脱发的程序猿 1971

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

上一篇: Ansible 离线部署实战:从依赖打包到集群配置
下一篇: ERPNext V15安装全攻略:从Frappe-Bench配置到模块扩展
Zewei Chu
博客等级 码龄10年 54粉丝 1661原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址