将 Word 文档转换为 TIFF 图像格式,在需要以固定版式展示内容时非常实用,例如用于电子表单、演示文稿或印刷出版。TIFF 格式能够完整保留文档的版面和视觉效果。而将 TIFF 图像转换为 Word 文档,则便于在 Word 环境中统一管理、整理和展示图像信息,提高内容的可读性。
本文将介绍如何使用 Spire.Doc for Python 在 Python 程序中实现 Word 文档与 TIFF 图像的相互转换。
本教程需要 Spire.Doc for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。
pip install Spire.Doc
如果您不确定如何安装,请参考:如何在 Windows 中安装 Spire.Doc for Python
在将 Word 文档转换为 TIFF 图像时,我们首先需要使用 Spire.Doc 库加载 Word 文档,并将其中的每一页转换为图像数据流。接着,借助 PIL 库的功能,将这些单独的图像数据流合并为一个完整的多页 TIFF 图像,完成 Word 文档到 TIFF 图像的转换。
使用 Python 将 Word 转换为 TIFF 的步骤如下:
from spire.doc import Document, ImageType
from PIL import Image
from io import BytesIO
# 创建 Document 对象
doc = Document()
# 加载 Word 文档
doc.LoadFromFile("示例.docx")
# 创建一个空列表用于存储 PIL 图像
images = []
# 遍历文档中的每一页
for i in range(doc.GetPageCount()):
# 将指定页转换为图像流
with doc.SaveImageToStreams(i, ImageType.Bitmap) as imageData:
# 将图像流作为 PIL 图像打开
img = Image.open(BytesIO(imageData.ToArray()))
# 将 PIL 图像添加到列表中
images.append(img)
# 将 PIL 图像保存为多页 TIFF 文件
images[0].save("output/Word转TIFF.tiff", save_all=True, append_images=images[1:])
# 释放资源
doc.Dispose()

通过使用 PIL 库,我们可以载入 TIFF 图像并将其逐页拆分为多个独立的 PNG 图像。随后,可利用 Spire.Doc 库将这些 PNG 图像逐页插入到 Word 文档中,实现从 TIFF 到 Word 的转换。
使用 Python 将 TIFF 图像转换为 Word 文档的步骤如下:
import os
from spire.doc import Document, SizeF, FileFormat
from PIL import Image
# 创建 Document 对象
doc = Document()
# 添加一个节
section = doc.AddSection()
# 将页边距设为 0
section.PageSetup.Margins.All = 0.0
# 加载 TIFF 图像
tiff_image = Image.open("output/Word转TIFF.tiff")
temp_files = []
# 遍历 TIFF 中的每一帧
for i in range(tiff_image.n_frames):
# 跳转到当前帧
tiff_image.seek(i)
# 提取当前帧图像
frame_image = tiff_image.copy()
# 将帧图像保存为 PNG 文件
temp_path = f"temp/output_frame_{i}.png"
frame_image.save(temp_path)
temp_files.append(temp_path)
# 添加段落
paragraph = section.AddParagraph()
# 将图像附加到段落中
image = paragraph.AppendPicture(f"temp/output_frame_{i}.png")
# 获取图像宽度和高度
width = image.Width
height = image.Height
# 将页面大小设置为与图像大小相同
section.PageSetup.PageSize = SizeF(width, height)
# 清除临时文件
for temp_file in temp_files:
if os.path.exists(temp_file):
os.remove(temp_file)
# 将文档保存为 Word 文件
doc.SaveToFile("output/TIFF转Word.docx", FileFormat.Docx2019)
# 释放资源
doc.Dispose()
# 清除临时文件
for temp_file in temp_files:
if os.path.exists(temp_file):
os.remove(temp_file)

如果您需要去除生成文档中的评估提示或解除功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
在处理 PDF 文档时,删除注释往往是一个必要步骤。无论是用于 PowerPoint 演示文稿,在问题解决后将最终版本分享给客户,还是为了归档重要资料,清除文档中的注释都有助于文档的整洁与规范。
通过 Spire.PDF for Python,用户可以在不打开 PDF 文档的情况下使用 Python 删除 PDF 文档的注释。只要参考本篇指南操作,你就可以快速清理 PDF 文档中的任意注释。
本教程需要 Spire.PDF for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。
pip install Spire.PDF
如果您不确定如何安装,请参考此教程: 如何在 Windows 中安装 Spire.PDF for Python。
如果你想要从 PDF 文档中删除特定的注释,首先要做的是准确找到要移除的注释对象。然后,借助 Spire.PDF for Python 提供的 Page.AnnotationsWidget.RemoveAt() 方法即可删除该注释。下面是删除 PDF 页面上某个注释的详细步骤:
你可以参考下面的代码示例,它演示了如何删除 PDF 文档中的第一个注释:
from spire.pdf.common import *
from spire.pdf import *
# 创建一个 PdfDocument 类的对象
doc = PdfDocument()
# 加载 PDF 文档
doc.LoadFromFile("/示例文档.pdf")
# 获取 PDF 文档的第一页
page = doc.Pages.get_Item(0)
# 移除 PDF 文档的第一个注释
page.AnnotationsWidget.RemoveAt(0)
# 保存修改后的 PDF 文档
doc.SaveToFile("/删除第一个批注.pdf", FileFormat.PDF)
doc.Close()

如果你想一次性清除 PDF 页面上的所有注释,可以使用 Spire.PDF for Python 提供的 AnnotationsWidget.Clear() 方法。本章节将通过详细的指南和代码示例演示怎样高效地通过 Python 来完成这个任务。
批量移除 PDF 文档某页上的所有注释的具体步骤如下:
下方的代码示例展示了怎样移除 PDF 文档第一页上的所有注释:
from spire.pdf.common import *
from spire.pdf import *
# 创建一个 PdfDocument 类的对象
doc = PdfDocument()
# 加载 PDF 文档
doc.LoadFromFile("/示例文档.pdf")
# 移除第一页的所有注释
doc.Pages.get_Item(0).AnnotationsWidget.Clear()
# 保存修改后的 PDF 文档
doc.SaveToFile("/删除第一页批注.pdf", FileFormat.PDF)
doc.Close()

想要在 Python 中删除 PDF 文档的所有注释,你需要先遍历每一页并获取其上的注释集合,然后遍历集合中的每一条注释,以此确保所有注释都被清除。 本节将介绍如何完成这一操作,并提供详细步骤和示例代码,帮助你轻松清理 PDF 文档中的所有注释内容。
删除 PDF 文档中所有注释的详细步骤:
下方的代码示例展示了如何删除一个 PDF 文档中的所有注释:
from spire.pdf.common import *
from spire.pdf import *
# 创建一个 PdfDocument 类的对象
doc = PdfDocument()
# 加载 PDF 文档
doc.LoadFromFile("/示例文档.pdf")
# 遍历所有页面
for i in range(doc.Pages.Count):
# 获取当前页面
page = doc.Pages.get_Item(i)
# 删除当前页面上的所有注释
page.AnnotationsWidget.Clear()
# 保存修改后的 PDF 文档
doc.SaveToFile("/删除所有批注.pdf", FileFormat.PDF)
doc.Close()

如果您需要去除生成文档中的评估提示或解除功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
编辑 Excel 文档涉及多种操作,如输入和格式化文本、应用公式、生成可视化图表,以及整理数据以便更清晰地展示信息和支持数据分析。能够以编程方式编辑 Excel 文档,是提升数据管理能力的重要技能。
本文将介绍如何使用 Spire.XLS for Python 通过 Python 代码编辑现有的 Excel 文档。
此教程需要 Spire.XLS for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。
pip install Spire.XLS
如果您不确定如何安装,请参考: 如何在 Windows 中安装 Spire.XLS for Python
在 Python 中处理 Excel 文件时,高效地读取和写入数据是一项关键任务,广泛应用于数据分析、报告生成等场景。Spire.XLS for Python 通过提供 CellRange.Value 属性,极大地简化了这一过程。开发者可以通过此属性轻松获取单元格的值或重新赋值。
以下是在 Python 中读取和写入 Excel 文件的步骤:
from spire.xls import Workbook
# 创建一个 Workbook(工作簿)对象
workbook = Workbook()
# 加载一个 Excel 文件
workbook.LoadFromFile("示例.xlsx")
# 获取指定的工作表
worksheet = workbook.Worksheets.get_Item(0)
# 获取指定的单元格
cell = worksheet.Range.get_Item("A10")
# 读取单元格的值
cellValue = cell.Value
# 判断单元格的值是否为 "Department"
if cellValue == "总运营费用":
# 更新单元格的值
cell.Value = "合计"
# 将工作簿保存为另一个文件
workbook.SaveToFile("output/编辑Excel文件.xlsx")
# 释放资源
workbook.Dispose()

格式化 Excel 文档对于生成专业且易于阅读的报告至关重要。Spire.XLS for Python 在 CellRange 类中提供了丰富的 API,帮助开发者灵活地管理各种格式设置,例如调整字体样式、选择单元格颜色、设置文本对齐方式以及修改行高和列宽。
以下是在 Python 中应用单元格样式和格式的步骤:
from spire.xls import Workbook, Color, HorizontalAlignType, VerticalAlignType
# 创建一个 Workbook(工作簿)对象
workbook = Workbook()
# 加载一个 Excel 文件
workbook.LoadFromFile("示例.xlsx")
# 获取指定的工作表
worksheet = workbook.Worksheets.get_Item(0)
# 获取工作表中所有已分配的单元格区域
allocatedRange = worksheet.AllocatedRange
# 遍历所有行
for rowNum in range(0, allocatedRange.RowCount):
if rowNum == 0:
# 为表头行应用背景色
allocatedRange.Rows.get_Item(rowNum).Style.Color = Color.get_Black()
# 更改表头行的字体颜色
allocatedRange.Rows.get_Item(rowNum).Style.Font.Color = Color.get_White()
else:
# 为其他行应用交替的背景色
if rowNum % 2 == 1:
allocatedRange.Rows.get_Item(rowNum).Style.Color = Color.get_LightGray()
else:
allocatedRange.Rows.get_Item(rowNum).Style.Color = Color.get_White()
# 水平居中对齐文本
allocatedRange.Rows.get_Item(rowNum).HorizontalAlignment = HorizontalAlignType.Center
# 垂直居中对齐文本
allocatedRange.Rows.get_Item(rowNum).VerticalAlignment = VerticalAlignType.Center
# 设置行高
allocatedRange.Rows.get_Item(rowNum).RowHeight = 20
# 遍历所有列
for columnNum in range(0, allocatedRange.ColumnCount):
if columnNum > 0:
# 设置列宽或自动列宽
allocatedRange.Columns.get_Item(columnNum).ColumnWidth = 20
#allocatedRange.AutoFitColumns()
# 将工作簿保存为另一个文件
workbook.SaveToFile("output/设置Excel单元格格式.xlsx")
# 释放资源
workbook.Dispose()

Excel 的查找与替换功能可以帮助用户快速定位电子表格中的特定文本并用新内容替换,非常适合数据修正与更新场景。使用 Spire.XLS for Python,可以通过 Worksheet.FindString() 方法高效地定位包含特定字符串的单元格,随后利用 CellRange.Value 属性轻松替换其值。
以下是在 Python 中查找并替换 Excel 文本的步骤:
from spire.xls import Workbook
# 创建一个 Workbook(工作簿)对象
workbook = Workbook()
# 加载 Excel 文件
workbook.LoadFromFile("示例.xlsx")
# 获取第一个工作表
worksheet = workbook.Worksheets[0]
# 定义要查找的原始运营费用名称
original_names = ["广告", "呆帐", "现金折扣", "配送成本", "折旧", "会费与订阅费", "保险", "其他", "总运营费用"]
# 定义对应的替换名称
replacement_names = ["广告(国内)", "坏账", "现金优惠", "物流费用", "设备折旧", "会员订阅费用", "商业保险", "杂项支出", "合计运营费用"]
# 遍历每个原始名称
for i in range(0, len(original_names)):
# 查找包含当前原始名称的单元格
cell = worksheet.FindString(original_names[i], False, False)
# 如果找到,替换为对应的新名称
if cell:
cell.Value = replacement_names[i]
# 将修改后的工作簿保存到新的文件
workbook.SaveToFile("output/查找替换Excel文本.xlsx")
# 释放资源
workbook.Dispose()

除了基本的文件操作外,Spire.XLS for Python 还支持多种高级功能。例如,可以使用 CellRange.Formula 属性在单元格中插入公式,实现实时计算与数据分析。同时,还可以通过 Worksheet.Charts.Add() 方法向工作表添加图表,以直观展示数据。
以下是在 Python 中添加公式和图表的步骤:
from spire.xls import Workbook, HorizontalAlignType, ExcelChartType
# 创建一个 Workbook对象
workbook = Workbook()
# 加载 Excel 文件
workbook.LoadFromFile("示例.xlsx")
# 获取第一个工作表
worksheet = workbook.Worksheets[0]
# 获取所有已分配的单元格区域
allocatedRange = worksheet.AllocatedRange
# 遍历所有行(不包括最后一行“总运营费用”)
for rowNum in range(0, allocatedRange.RowCount - 1):
if rowNum == 0:
# 在 G1 单元格写入标题
worksheet.Range[rowNum + 1, 7].Text = "差额百分比"
worksheet.Range[rowNum + 1, 7].Style.Font.IsBold = True
worksheet.Range[rowNum + 1, 7].Style.HorizontalAlignment = HorizontalAlignType.Center
else:
# 在 G2 到 G8 单元格添加公式 (差额 / 估算金额)
worksheet.Range[rowNum + 1, 7].Formula = f"=D{rowNum + 1}/B{rowNum + 1}"
worksheet.Range[rowNum + 1, 7].Style.NumberFormat = "0.00%"
# 添加一个簇状柱形图
chart = worksheet.Charts.Add(ExcelChartType.ColumnClustered)
# 设置图表数据范围(不包括最后一行“总运营费用”)
chart.DataRange = worksheet.Range["A1:D8"]
chart.SeriesDataFromRange = False
# 设置图表位置
chart.LeftColumn = 1
chart.TopRow = 10
chart.RightColumn = 8
chart.BottomRow = 23
# 设置并格式化图表标题
chart.ChartTitle = "各部门季度运营费用"
chart.ChartTitleArea.Size = 13
chart.ChartTitleArea.IsBold = True
# 保存文件
workbook.SaveToFile("output/添加公式和图表到Excel.xlsx")
# 释放资源
workbook.Dispose()

如果您需要去除生成文档中的评估提示或解除功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
Spire.Presentation 10.4.6 已发布。该版本支持在PPT表格的单元格中插入公式以及读取 Shape 的 CustomerData 数据。此外,一些在转换 PPT 到 PDF、SVG,以及打开文档时出现的问题也已成功被修复。详情请查看下文。
新功能:
Presentation ppt = new Presentation();
ppt.LoadFromFile(inputFile);
List dataList = ppt.Slides[0].Shapes[1].CustomerDataList;
Console.WriteLine(dataList.Count);
for(int i = 0; i < dataList.Count; i++)
{
string name = dataList[i].Name;
string content = dataList[i].XML;
File.WriteAllText(outputFile + name, content);
}
// 创建PPT文档
Presentation presentation = new Presentation();
Double[] widths = new double[] { 100, 100, 150, 100, 100 };
Double[] heights = new double[] { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 };
// 添加表格
ITable table = presentation.Slides[0].Shapes.AppendTable(presentation.SlideSize.Size.Width / 2 - 275, 90, widths, heights);
String[,] dataStr = new String[,]{
{"Name", "Capital", "Continent", "Area", "Population"},
{"Venezuela", "Caracas", "South America", "912047", "19700000"},
{"Bolivia", "La Paz", "South America", "1098575", "7300000"},
{"Brazil", "Brasilia", "South America", "8511196", "150400000"},
{"Canada", "Ottawa", "North America", "9976147", "26500000"},
{"Chile", "Santiago", "South America", "756943", "13200000"},
{"Colombia", "Bagota", "South America", "1138907", "33000000"},
{"Cuba", "Havana", "North America", "114524", "10600000"},
{"Ecuador", "Quito", "South America", "455502", "10600000"},
{"Paraguay", "Asuncion","South America", "406576", "4660000"},
{"Peru", "Lima", "South America", "1285215", "21600000"},
{"Jamaica", "Kingston", "North America", "11424", "2500000"},
{"Mexico", "Mexico City", "North America", "1967180", "88600000"}
};
// 在表格中添加数据
for (int i = 0; i < 13; i++)
for (int j = 0; j < 5; j++)
{
//Fill the table with data
table[j, i].TextFrame.Text = dataStr[i, j];
//Set the Font
table[j, i].TextFrame.Paragraphs[0].TextRanges[0].LatinFont = new TextFont("Arial Narrow");
}
// 设置对齐方式
for (int i = 0; i < 5; i++)
{
table[i, 0].TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Center;
}
string latexMathCode = @"x^{2}+\sqrt{x^{2}+1}=2";
table[2, 3].TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexMathCode);
// 设置表格样式
table.StylePreset = TableStylePreset.LightStyle3Accent1;
// 保存结果文件
presentation.SaveToFile("Output.pptx", FileFormat.Pptx2010);
问题修复:
https://www.e-iceblue.cn/Downloads/Spire-Presentation-NET.html
在 Excel 工作簿中,工作表名称可以作为区分不同数据集的唯一标识。对于包含多个工作表的大型 Excel 文件,了解每个工作表的名称有助于快速定位特定类型的数据存储位置。本文将介绍如何使用 Spire.XLS for Python 通过简单的 Python 代码获取 Excel 文件中的工作表名称。
此教程需要 Spire.XLS for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。
pip install Spire.XLS
如果您不确定如何安装,请参考: 如何在 Windows 中安装 Spire.XLS for Python
开发者可以通过 Worksheet.Name 属性获取单个工作表的名称。若要获取 Excel 文件中所有工作表的名称(包括隐藏工作表),可遍历工作簿中的每个工作表,并通过该属性依次读取。具体步骤如下:
from spire.xls import Workbook
# 指定输入和输出文件路径
inputFile = "示例.xlsx"
outputFile = "output/获取工作表名.txt"
# 创建一个 Workbook 实例
workbook = Workbook()
# 加载 Excel 文件
workbook.LoadFromFile(inputFile)
# 创建一个列表来存储工作表名称
names = []
# 遍历每个工作表
for sheet in workbook.Worksheets:
# 获取每个工作表的名称并添加到列表中
names.append(sheet.Name)
# 写入到文本文件中
with open(outputFile, "w", encoding="utf-8") as file:
file.write("\n".join(names))

如果只需获取 Excel 文件中隐藏工作表的名称,开发者可以先遍历所有工作表,判断是否为隐藏状态,然后通过 Worksheet.Name 属性读取隐藏工作表的名称。具体步骤如下:
from spire.xls import Workbook, WorksheetVisibility
# 指定输入和输出文件路径
inputFile = "示例.xlsx"
outputFile = "output/获取隐藏工作表名.txt"
# 创建一个 Workbook 实例
workbook = Workbook()
# 加载 Excel 文件
workbook.LoadFromFile(inputFile)
# 创建一个列表来存储工作表名称
names = []
# 遍历每个工作表
for sheet in workbook.Worksheets:
# 检测隐藏的工作表
if sheet.Visibility == WorksheetVisibility.Hidden:
# 获取隐藏工作表的名称并添加到列表中
names.append(sheet.Name)
# 写入到文本文件中
with open(outputFile, "w", encoding="utf-8") as file:
file.write("\n".join(names))

如果您需要去除生成文档中的评估提示或解除功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
在处理 PDF 文件时,常常会遇到一些无用的空白页。这些页面不仅影响阅读体验,还可能导致文件体积增大,甚至在打印时造成纸张浪费。为了提升 PDF 文档的专业性和实用性,查找并删除其中的空白页面是一个十分必要的操作。
本文将介绍如何结合 Spire.PDF for Python 库与 Pillow 图像处理库,通过 Python 精准识别并删除空白页,无论是完全空白的页面,还是看似无内容、实则隐藏着白色文本、水印等不可见元素的 “伪空白页”。
本方案需依赖两个核心 Python 库,功能分工明确:
通过 Python 包管理器 pip,可一键完成两个库的安装,命令如下:
pip install Spire.PDF Pillow
Spire.PDF 库自带 PdfPageBase.IsBlank() 方法,能快速判断页面是否为 “完全空白”(无任何可见或隐藏元素)。但对于包含白色文本、透明水印、隐形背景图等隐藏内容的 “伪空白页”,该方法无法精准识别。
为确保检测准确性,本方案采用双重验证策略:
PdfPageBase.IsBlank() 方法快速识别完全空白的页面,提升处理效率;Pillow 库分析图像像素 — 若所有像素均为白色,则判定为 “伪空白页”。⚠️ 重要提示:如果在 PDF 转图片的过程中未使用有效许可证,生成的图片会出现评估水印,可能影响空白页检测结果。因此请先点击申请临时许可证,以确保功能正常使用。
按照以下步骤实现 PDF 空白页的检测与删除:
1. 定义图像空白检测函数
编写自定义函数 is_blank_image(),利用 Pillow 库的像素分析能力,判断 PDF 页面转换后的图像是否为空白(即所有像素均为白色)。
2. 加载 PDF 文档
通过PdfDocument.LoadFromFile()方法加载需要处理的 PDF 文件。
3. 遍历并检测所有页面
反向遍历 PDF 所有页面,避免删除页面时出现索引错乱问题。对每个页面执行双重验证:
PdfPageBase.IsBlank() 返回 True,直接删除该页面;False,则通过 PdfDocument.SaveAsImage() 方法将页面转为图像,调用 is_blank_image() 函数分析像素。若判定为空白图像,删除对应 PDF 页面。4. 保存结果PDF
最后,通过 PdfDocument.SaveToFile() 方法将删除空白页后的 PDF 文件保存到指定路径,完成整个处理流程。
Python 示例代码:
import io
from spire.pdf import PdfDocument
from PIL import Image
# 应用License Key
from spire.pdf .common import License as pdfLicense
# 应用License Key
pdfLicense.SetLicenseKey("License-Key")
# 自定义方法:判断图片是否为空白(所有像素是否都为白色)
def is_blank_image(image):
# 转换为 RGB 模式再获取像素
img = image.convert("RGB")
# 获取所有像素点集合,判断是否全为白色
white_pixel = (255, 255, 255)
return all(pixel == white_pixel for pixel in img.getdata())
# 加载 PDF 文档
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# 倒序遍历每页,避免因删除影响索引
for i in range(pdf.Pages.Count - 1, -1, -1):
page = pdf.Pages.get_Item(i)
# 判断当前页面是否为完全空白
if page.IsBlank():
# 若为完全空白,直接将其从文档中删除
pdf.Pages.RemoveAt(i)
else:
# 将当前页面转换为图片
with pdf.SaveAsImage(i) as image_data:
image_bytes = image_data.ToArray()
pil_image = Image.open(io.BytesIO(image_bytes))
# 判断图片是否为空白
if is_blank_image(pil_image):
# 若为空白图片,从文档中删除图片对应的PDF页面
pdf.Pages.RemoveAt(i)
# 保存结果 PDF
pdf.SaveToFile("删除空白页面.pdf")
pdf.Close()

Q1:PDF 文件中的“空白页”具体指什么?
本方案定义的空白页包含两类:① 完全无任何内容的纯空白页;② 包含白色文本、透明水印、隐形背景等不可见元素的 “伪空白页”。双重验证策略可同时检测这两类页面。
Q2:不使用 Spire.PDF 许可证能运行吗?
可以运行,但 PDF 转图像时会生成评估水印,可能导致 “伪空白页” 检测误判(水印像素会被判定为非白色)。建议申请免费临时许可证用于测试,确保检测准确性。
Q3:Spire.PDF 支持哪些 Python 版本?
Spire.PDF for Python 兼容 Python 3.7 及以上版本,且需搭配 Pillow 库(无特殊版本限制,最新版本即可)。
Q4:可以只检测空白页而不删除吗?
完全可以。只需删除或注释掉 pdf.Pages.RemoveAt(i) 代码行,使用 print() 或日志记录功能列出检测到的空白页,以便进一步查看。
删除 PDF 中的冗余空白页,是优化文档可读性、压缩文件体积、提升专业呈现效果的关键操作。借助 Spire.PDF for Python 的 PDF 解析能力与 Pillow 的图像处理优势,本方案能精准解决各类空白页问题,且代码简洁易修改。
无论是处理扫描件、生成报告、整理文档用于打印,还是批量优化 PDF 文件,这套 Python 方案都能高效完成空白页清理,助力提升文档处理效率。
检索和替换 Word 文档中的字体是文档设计中的重要环节。通过调整字体,用户可以为文档增添新风格,提升文档的美观性和可读性。同时,掌握字体修改的方法,也可以增加文档的吸引力。 为了助力高效完成这一任务,本文将以 Spire.Doc for Java 为例,详细介绍如何获取或替换 Word 文档的字体,轻松实现文档风格的统一和优化。
首先,您需要在 Java 程序中添加 Spire.Doc.jar 文件作为依赖项。JAR 文件可以从此链接下载。如果您使用 Maven,则可以将以下代码添加到项目的 pom.xml 文件中,从而轻松地在应用程序中导入 JAR 文件。
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>14.9.5</version>
</dependency>
</dependencies>
要检索 Word 文档中的字体信息,你需要遍历文档的各个部分,包括节、段落以及它们的子对象。然后判断这些子对象是否是 TextRange 的实例。如果是,就可以通过 TextRange 类的方法提取字体相关的信息,如字体名称和字号。
以下是在 Java 中检索 Word 文档字体信息的基本步骤:
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;
import java.awt.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// 自定义 FontInfo 类用以存储字体信息
class FontInfo {
private String name;
private Float size;
public FontInfo() {
this.name = ";
this.size = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getSize() {
return size;
}
public void setSize(Float size) {
this.size = size;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof FontInfo)) return false;
FontInfo other = (FontInfo) obj;
return name.equals(other.getName()) && size.equals(other.getSize());
}
}
public class GetFontInfo {
// 将字符串写入到 txt 文件的方法
public static void writeAllText(String filename, String[] text) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
for (String s : text) {
writer.write(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
ArrayList<FontInfo> fontInfos = new ArrayList<>();
StringBuilder fontInformations = new StringBuilder();
// 创建一个 Document 类的对象
Document document = new Document();
// 加载 Word 文档
document.loadFromFile("示例文档.docx");
// 遍历文档中的所有节
for (int i = 0; i < document.getSections().getCount(); i++) {
Section section = document.getSections().get(i);
// 遍历节中的段落
for (int j = 0; j < section.getBody().getParagraphs().getCount(); j++) {
Paragraph paragraph = section.getBody().getParagraphs().get(j);
// 遍历每一个子对象
for (int k = 0; k < paragraph.getChildObjects().getCount(); k++) {
DocumentObject obj = paragraph.getChildObjects().get(k);
if (obj instanceof TextRange) {
TextRange txtRange = (TextRange) obj;
// 获取字体的名称和字号
String fontName = txtRange.getCharacterFormat().getFontName();
Float fontSize = txtRange.getCharacterFormat().getFontSize();
// 获取字体的颜色
Color color = txtRange.getCharacterFormat().getTextColor();
String textColor = String.format("RGB(%d,%d,%d)", color.getRed(), color.getGreen(), color.getBlue());
// 保存字体信息
FontInfo fontInfo = new FontInfo();
fontInfo.setName(fontName);
fontInfo.setSize(fontSize);
if (!fontInfos.contains(fontInfo)) {
fontInfos.add(fontInfo);
String str = String.format("字体:%s、字号:%.2f、颜色:%s%n", fontInfo.getName(), fontInfo.getSize(), textColor);
fontInformations.append(str);
}
}
}
}
}
// 将字体信息写入到 txt 文件中
writeAllText("获取字体信息.txt", fontInformations.toString().split("\n"));
// 释放资源
document.dispose();
}
}

在获取到指定文本范围的字体名称后,你可以通过调用 TextRange.getCharacterFormat().setFontName() 方法,轻松将其替换为其它字体。此外,你还可以使用 TextRange 类中对应的方法,来调整字体大小和文本颜色。
下方是在 Java 中替换 Word 文档中指定字体的具体步骤:
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;
public class ReplaceFont {
public static void main(String[] args) {
// 创建一个 Document 类的实例
Document document = new Document();
// 加载 Word 文档
document.loadFromFile("/示例文档.docx");
// 遍历文档中的节
for (int i = 0; i < document.getSections().getCount(); i++) {
// 获取当前节
Section section = document.getSections().get(i);
// 遍历节中的所有段落
for (int j = 0; j < section.getBody().getParagraphs().getCount(); j++) {
// 获取当前段落
Paragraph paragraph = section.getBody().getParagraphs().get(j);
// 遍历段落中的每一个子对象
for (int k = 0; k < paragraph.getChildObjects().getCount(); k++) {
// 获取子对象
DocumentObject obj = paragraph.getChildObjects().get(k);
// 判断子对象是否为 TextRange
if (obj instanceof TextRange) {
// 获取这个 TextRange
TextRange txtRange = (TextRange) obj;
// 获取字体的名称
String fontName = txtRange.getCharacterFormat().getFontName();
// 判断字体名称是否为 Microsoft JhengHei
if ("Microsoft JhengHei".equals(fontName)) {
// 使用新字体替换该字体
txtRange.getCharacterFormat().setFontName("KaiTi");
}
}
}
}
}
// 保存修改后的文档
document.saveToFile("/替换 Word 字体.docx", FileFormat.Docx);
document.dispose();
}
}

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
在企业应用中,无论是生成报告、合同还是个性化信函,程序化创建 Word 文档都是常见需求。Spire.Doc for .NET 提供了无需依赖 Microsoft Office 的 C# Word 文档处理解决方案。
本文将探讨两种基于模板生成文档的有效方法:
Spire.Doc for .NET 是一款专业的 Word 文档处理 API,可帮助开发者实现多样化的文档操作功能。主要特性包括:
该库特别适用于需要保证一致性和效率的企业级文档自动化生成场景。
开始前,请从我们的官方网站下载 Spire.Doc for .NET,或通过 NuGet 包管理器使用以下命令进行安装:
PM> Install-Package Spire.Doc
Spire.Doc 库中的 Document.Replace 方法可用于查找替换 Word 文档中的特定文本,实现基于模板的动态文档生成。
通过替换文本生成Word文档的步骤如下:
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace CreateWordByReplacingPlaceholders
{
class Program
{
static void Main(string[] args)
{
// 初始化一个新的 Document 对象
Document document = new Document();
// 加载模板 Word 文件
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\template.docx");
// 字典用于保存占位符及其替换内容
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "#name#", "张三" },
{ "#gender#", "男" },
{ "#birthdate#", "1990年3月20日" },
{ "#address#", "金盆岭街道" },
{ "#city#", "长沙" },
{ "#province#", "湖南" },
{ "#postal#", "410000" },
{ "#country#", "中国" }
};
// 用相应的值替换文档中的占位符
foreach (KeyValuePair<string, string> kvp in replaceDict)
{
document.Replace(kvp.Key, kvp.Value, true, true);
}
// 图像文件的路径
String imagePath = "C:\\Users\\Administrator\\Desktop\\portrait.png";
// 用图像替换照片占位符
ReplaceTextWithImage(document, "#photo#", imagePath);
// 保存修改后的文档
document.SaveToFile("ReplacePlaceholders.docx", FileFormat.Docx);
// 释放资源
document.Dispose();
}
// 方法用于用图像替换文档中的占位符
static void ReplaceTextWithImage(Document document, String stringToReplace, String imagePath)
{
// 从指定路径加载图像
Image image = Image.FromFile(imagePath);
DocPicture pic = new DocPicture(document);
pic.LoadImage(image);
// 在文档中查找占位符
TextSelection selection = document.FindString(stringToReplace, false, true);
// 获取找到的文本范围
TextRange range = selection.GetAsOneRange();
int index = range.OwnerParagraph.ChildObjects.IndexOf(range);
// 插入图像并移除占位符文本
range.OwnerParagraph.ChildObjects.Insert(index, pic);
range.OwnerParagraph.ChildObjects.Remove(range);
}
}
}

Spire.Doc中的 BookmarksNavigator 类专门用于管理 Word 文档中的书签,该类提供了定位书签和替换书签内容的方法。
通过替换书签内容生成Word文档的步骤如下:
using Spire.Doc;
using Spire.Doc.Documents;
namespace CreateWordByReplacingBookmarkContent
{
class Program
{
static void Main(string[] args)
{
// 初始化一个 Document 对象并加载模板
Document document = new Document();
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\template.docx");
// 定义书签名称及其替换值
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "name", "Tech Innovations Inc." },
{ "year", "2015" },
{ "headquarter", "美国,纽约" },
{ "history", "Tech Innovations Inc. 由一群工程师和企业家创立,他们的愿景是彻底改变技术行业。" +
"公司最初专注于软件开发,后来将业务范围扩展到人工智能和云计算解决方案。" }
};
// 创建一个 BookmarksNavigator 来管理文档中的书签
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
// 用相应的值替换每个书签的内容
foreach (KeyValuePair<string, string> kvp in replaceDict)
{
bookmarkNavigator.MoveToBookmark(kvp.Key); // 导航到书签
bookmarkNavigator.ReplaceBookmarkContent(kvp.Value, true); // 替换内容
}
// 保存修改后的文档
document.SaveToFile("ReplaceBookmarkContent.docx", FileFormat.Docx2013);
// 释放资源
document.Dispose();
}
}
}

两种方法都提供了有效的从模板生成Word文档的方式,但有重要差异:
1.文本替换法:
2.书签替换法:
此外,Spire.Doc for .NET 还支持邮件合并功能,这为从模板动态生成文档提供了另一种强大的方式。该功能特别适用于批量创建个性化文档,例如套用信函或报告,这些文档的数据通常来自数据库或其他结构化数据源。
如果您需要去除生成文档中的评估提示或解除功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
Spire.Doc for JavaScript 13.4.0 现已正式发布。最新版本支持了许多新功能,例如在 Word 文档中添加各种类型的图表。详情请阅读以下内容。
新功能:
例如添加条形图:
// Load word document
let document = wasmModule.Document.Create();
// Add a section to the document
let section = document.AddSection();
// Add a paragraph to the section and append text to it
section.AddParagraph().AppendText("Bar chart.");
// Add a new paragraph to the section
let newPara = section.AddParagraph();
// Append a bar chart shape to the paragraph with specified width and height
let chartShape = newPara.AppendChart(wasmModule.ChartType.Bar, 400.0, 300.0);
let chart = chartShape.Chart;
// Get the title of the chart
let title = chart.Title;
// Set the text of the chart title
title.Text = "My Chart";
// Show the chart title
title.Show = true;
// Overlay the chart title on top of the chart
title.Overlay = true;
// Save the document to the specified path
const outputFileName = "AppendBarChart.docx";
document.SaveToFile({
fileName: outputFileName,
fileFormat: wasmModule.FileFormat.Docx2013,
});
//Open a Word document
let document = wasmModule.Document.Create();
let section = document.AddSection();
//Add a new paragraph
let para = section.AddParagraph();
//add a svg file to the paragraph
let svgPicture = para.AppendPicture({imgFile: inputSVGFileName});
//Set svg's width
svgPicture.Width = 200;
//Set svg's height
svgPicture.Height = 200;
// Save the document
const outputFileName = "AddSvg.docx";
document.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx });
//open document
let document = wasmModule.Document.Create();
document.LoadFromFile(inputFileName);
//embedded images list.
let images = [];
for (let i = 0; i < document.Sections.Count; i++) {
let section = document.Sections.get(i);
for (let j = 0; j < section.Body.ChildObjects.Count; j++) {
let objInSec = section.Body.ChildObjects.get(j);
if (objInSec.DocumentObjectType == wasmModule.DocumentObjectType.Paragraph) {
for (let k = 0; k < objInSec.ChildObjects.Count; k++) {
let objInPara = objInSec.ChildObjects.get(k);
if (objInPara.DocumentObjectType == wasmModule.DocumentObjectType.Picture) {
images.push(objInPara.ImageBytes)
}
}
} else if (objInSec.DocumentObjectType == wasmModule.DocumentObjectType.Table) {
let table = objInSec;
for (let i = 0; i < table.Rows.Count; i++) {
let row = table.Rows.get(i);
for (let j = 0; j < row.Cells.Count; j++) {
let cell = row.Cells.get(j);
for (let k = 0; k < cell.Paragraphs.Count; k++) {
let paragraph = cell.Paragraphs.get_Item(k);
for (let a = 0; a < paragraph.ChildObjects.Count; a++) {
let para = paragraph.ChildObjects.get(a);
if (para.DocumentObjectType == wasmModule.DocumentObjectType.Picture) {
images.push(para.ImageBytes)
}
}
}
}
}
}
}
}
//save images
for (let i = 0; i < images.length; i++) {
let outFile = "Image-" + i + ".png";
const modifiedFile = new Blob([images[i]], { type: 'image/png'});
downloadItems.value.push({
name: outFile,
url: URL.createObjectURL(modifiedFile)
});
}
// Dispose of the document object to free resources
document.Dispose();
//Create Word document.
let document = wasmModule.Document.Create();
//Load the file from disk.
document.LoadFromFile(inputFileName);
//Set the watermark as null to remove the text and image watermark.
document.Watermark = null;
// Save the document to the specified path
const outputFileName = "RemoveImageWatermark.docx";
document.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
//Create Word document.
let document = wasmModule.Document.Create();
//Load the file from disk.
document.LoadFromFile(inputFileName);
//Set the watermark as null to remove the text and image watermark.
document.Watermark = null;
// Save the document to the specified path
const outputFileName = "RemoveTextWatermark.docx";
document.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
//Create a document
let document = wasmModule.Document.Create();
//Load the document from disk.
document.LoadFromFile(inputFileName);
//Set the build-in Properties.
document.BuiltinDocumentProperties.Title = "Document Demo Document";
document.BuiltinDocumentProperties.Author = "James";
document.BuiltinDocumentProperties.Company = "e-iceblue";
document.BuiltinDocumentProperties.Keywords = "Document, Property, Demo";
document.BuiltinDocumentProperties.Comments = "This document is just a demo.";
//Set the custom properties.
let custom = document.CustomDocumentProperties;
custom.Add("e-iceblue", true);
custom.Add("Authorized By", "John Smith");
custom.Add("Authorized Date", wasmModule.DateTime.get_Today());
custom.Add("Age", 13);
custom.Add("price", 25.4);
// Save the document to the specified path
const outputFileName = "SetDocumentProperties.docx";
document.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
//Create Word document.
let document = wasmModule.Document.Create();
//Load the file from disk.
document.LoadFromFile(inputFileName);
//Create a new section
let section = document.Sections.get(0);
// Set the top gutter option to true for the section's page setup.
section.PageSetup.IsTopGutter = true;
// Set the width of the gutter in points (100f).
section.PageSetup.Gutter = 100;
// Save the document to the specified path
const outputFileName = "SetGutterPosition.docx";
document.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
https://www.e-iceblue.cn/Downloads/Spire-DOC-Javascript.html
Spire.Doc 13.4.4 已发布。本次更新增强了 Word 到 PDF 的转换功能。此外,许多已知问题也在该版本中成功修复,如使用 Document.Clone() 后获取不到 TextBox 的问题。详情请阅读以下内容。
问题修复: