Spire.Presentation for Java 10.10.2 现已发布。本次更新新增支持将 Markdown 转换为 PPTX 文件,以及将 SVG 转换为 Shape,同时增强了 PPT 转 PDF 的转换功能。此外,本次更新还修复了一些已知问题,例如添加的 LaTeX 公式渲染不正确的问题。详情如下:
新功能:
Presentation pt = new Presentation();
pt.loadFromFile("input.md", FileFormat.Markdown);
pt.saveToFile("output.pptx", FileFormat.PPTX_2013);
pt.dispose();
Presentation ppt = new Presentation();
ppt.loadFromFile("input.pptx");
for (int i = 0; i < ppt.getSlides().getCount(); i++)
{
ppt.getSlides().get(i).getShapes().addFromSVGAsShapes("in.svg");
}
ppt.saveToFile("output.pptx", FileFormat.PPTX_2013);
ppt.dispose();
问题修复:
https://www.e-iceblue.cn/Downloads/Spire-Presentation-JAVA.html
Spire.Presentation 10.10.1 现已发布,此更新引入了设置音频淡入和淡出持续时间的功能,以及裁剪音频的能力。以下是详细信息:
新功能:
// New Append Audio
Presentation pres = new Presentation();
FileStream from_stream = File.OpenRead(inputFile);
RectangleF audioRect = new RectangleF(50, 50, 100, 100);
IAudio audio = pres.Slides[0].Shapes.AppendAudioMedia(from_stream, audioRect);
// Set the duration of the starting fade for 13s
audio.FadeInDuration = 13000f;
// Set the duration of the ending fade for 40s
audio.FadeOutDuration = 10000f;
pres.SaveToFile(outputFile, FileFormat.Pptx2013);
// Retrieve existing documents
FileStream from_stream = File.OpenRead(inputFile);
Presentation presentation = new Presentation();
presentation.LoadFromStream(from_stream, FileFormat.Auto);
foreach (IShape shape in presentation.Slides[0].Shapes)
{
if (shape is IAudio)
{
IAudio audio = shape as IAudio;
// Set the duration of the starting fade for 13s
audio.FadeInDuration = 13000f;
// Set the duration of the ending fade for 20s
audio.FadeOutDuration = 20000f;
}
}
presentation.SaveToFile(outputFile, FileFormat.Pptx2013);
// New Append Audio
Presentation pres = new Presentation();
FileStream from_stream = File.OpenRead(inputFile);
RectangleF audioRect = new RectangleF(50, 50, 100, 100);
IAudio audio = pres.Slides[0].Shapes.AppendAudioMedia(from_stream, audioRect);
// Set the start trimming time 8 seconds
audio.TrimFromStart = 8000f;
// Set the end trimming time 13 seconds
audio.TrimFromEnd = 13000f;
pres.SaveToFile(outputFile, FileFormat.Pptx2013);
// Retrieve existing documents
FileStream from_stream = File.OpenRead(inputFile);
Presentation presentation = new Presentation();
presentation.LoadFromStream(from_stream, FileFormat.Auto);
foreach (IShape shape in presentation.Slides[0].Shapes)
{
if (shape is IAudio)
{
IAudio audio = shape as IAudio;
// Set the start trimming time 8 seconds
audio.TrimFromStart = 8000f;
// Set the end trimming time 13 seconds
audio.TrimFromEnd = 13000f;
}
}
presentation.SaveToFile(outputFile, FileFormat.Pptx2013);
https://www.e-iceblue.cn/Downloads/Spire-Presentation-NET.html

在 Python 中处理数据时,将 TXT 文本文件转换为 CSV 是数据分析、报表生成或跨应用共享数据的常见需求。TXT 文件通常存储非结构化的纯文本,直接处理较为繁琐,而 CSV 文件能将数据组织成行和列,更便于分析和处理。本文将详细介绍如何使用 Python 实现 TXT 文件转 CSV,包括单文件转换、批量转换以及处理不同分隔符的技巧。
CSV(逗号分隔值)文件是一种基于文本的简单文件格式,用于存储表格数据。每一行表示一条记录,行内的值用逗号、制表符或自定义分隔符分隔。
CSV 文件具有以下优势:
在实际应用中,CSV 文件可用来存储联系人信息、销售数据、日志数据等结构化数据,便于后续处理和分析。
Spire.XLS for Python是一个功能强大的库,不仅支持创建和编辑 Excel 文件,还能高效操作 CSV 文件,且无需安装 Microsoft Excel。借助 Spire.XLS,开发者可以轻松实现 TXT 转 CSV、数据写入、表格格式处理、公式计算以及批量文件操作等任务。

你可以运行以下命令直接从 PyPI 安装该库:
pip install Spire.XLS
如果需要安装指导,请参考如何安装 Spire.XLS for Python。
将单个TXT文本文件转换为 CSV 非常简单,只需以下几个步骤即可完成:
示例代码:
下面的代码示例展示如何使用 Python 导出 TXT 文本文件为 CSV:
from spire.xls import *
# 读取 TXT 文件
with open("data.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
# 处理每行数据(按空格分割,可根据需要更改分隔符)
processed_data = [line.strip().split() for line in lines]
# 创建 Excel 工作簿
workbook = Workbook()
# 获取第一个工作表
sheet = workbook.Worksheets[0]
# 将处理后的数据写入工作表
for row_num, row_data in enumerate(processed_data):
for col_num, cell_data in enumerate(row_data):
sheet.Range[row_num + 1, col_num + 1].Value = cell_data
# 将工作表保存为 CSV 文件(UTF-8 编码)
sheet.SaveToFile("Txt转Csv.csv", ",", Encoding.get_UTF8())
# 释放工作簿资源
workbook.Dispose()
TXT 转 CSV 输出结果:

如果你还希望将 TXT 文件转换为 Excel 文件,可参考教程如何使用 Python 将 TXT 转 Excel。
如果你有多个文本文件需要自动转换为 CSV,可以遍历文件夹中的所有 .txt 文件,并逐一转换。
以下代码演示如何在 Python 中批量将多个 TXT 文件转换为 CSV:
import os
from spire.xls import *
# TXT 文件所在文件夹
input_folder = "txt_files"
output_folder = "csv_files"
# 如果输出文件夹不存在,则创建
os.makedirs(output_folder, exist_ok=True)
# 单个 TXT 文件转换函数
def convert_txt_to_csv(file_path, output_path):
with open(file_path, "r", encoding="utf-8") as f:
lines = f.readlines()
processed_data = [line.strip().split() for line in lines if line.strip()]
workbook = Workbook()
sheet = workbook.Worksheets[0]
for row_num, row_data in enumerate(processed_data):
for col_num, cell_data in enumerate(row_data):
sheet.Range[row_num + 1, col_num + 1].Value = cell_data
sheet.SaveToFile(output_path, ",", Encoding.get_UTF8())
workbook.Dispose()
print(f"已转换 '{file_path}' -> '{output_path}'")
# 遍历文件夹中所有 TXT 文件并转换
for filename in os.listdir(input_folder):
if filename.lower().endswith(".txt"):
input_path = os.path.join(input_folder, filename)
output_name = os.path.splitext(filename)[0] + ".csv"
output_path = os.path.join(output_folder, output_name)
convert_txt_to_csv(input_path, output_path)
在将文本文件转换为 CSV 时,不同文本文件可能存在格式差异或潜在错误,以下技巧可帮助你更高效地处理各种场景。
并非所有文本文件都使用空格分隔值。如果 TXT 文件使用制表符、逗号或其他字符,可调整 split() 函数以匹配分隔符:
processed_data = [line.strip().split('\t') for line in lines]
processed_data = [line.strip().split(',') for line in lines]
processed_data = [line.strip().split('|') for line in lines]
这样可以确保数据在写入 CSV 前正确拆分为列。
读取或写入文件时,使用 try-except 捕获潜在错误,可增强脚本稳健性,避免意外崩溃:
try:
# 你的代码
except Exception as e:
print("错误:", e)
提示:使用清晰的错误信息提示便于理解问题所在。
有些 TXT 文件可能包含空行,可在处理时过滤空行,避免在 CSV 中生成空行:
processed_data = [line.strip().split() for line in lines if line.strip()]
本文介绍了如何使用 Spire.XLS for Python 在 Python 中将 TXT 文本文件转换为 CSV。通过这些方法,你可以轻松处理文本数据,使其适合分析、报表和共享。Spire.XLS 不仅支持单文件转换,还能实现批量处理,并可灵活应对不同分隔符和文本格式。
如果你在 Python TXT 转 CSV 转换过程中遇到问题或需要技术支持,可访问我们的支持论坛获取帮助。
A1: 可以。Spire.XLS for Python 独立于 Excel,可直接创建和导出 CSV 文件。
A2: 使用循环读取文件夹中的所有 TXT 文件,并对每个文件应用转换逻辑。教程中提供了可直接使用的 Python 批量转换示例。
A3: 在处理过程中过滤空行,并检查列数一致性,以避免输出 CSV 中出现错误或空行。
A4: 可根据 TXT 文件中的分隔符调整 split() 函数--制表符 (\t)、逗号或其他自定义字符,然后再写入 CSV。

在企业应用、报表系统或财务工具的开发中,生成规范、专业的 PDF 文档是常见需求。与其在代码中硬编码布局,不如使用模板来提高开发效率。模板不仅能加快开发进程,还能确保品牌视觉与文档格式的一致性。
本文将介绍如何使用 Spire.PDF for .NET 在 C# 中通过 HTML 模板 或 预设 PDF 模板 生成 PDF 文档,无论是需要动态布局还是快速替换占位符,都能灵活应对。
本文目录
Spire.PDF for .NET 是一款功能强大的 PDF 操作库,允许 .NET 开发者无需依赖 Adobe Acrobat 即可创建、读取、编辑和转换 PDF 文档。该库提供全面的 API 接口,适用于生成报表、发票、证书及其他 PDF 格式文件,非常适合在 C# 应用中进行自动化文档处理。
与本教程相关的主要功能包括:
要在 C# 项目中通过模板生成 PDF,首先需将 Spire.PDF 引入项目中。对于 HTML 转 PDF 的场景,Spire.PDF 依赖外部渲染引擎(Qt WebEngine 或 Google Chrome)。本文以 Qt WebEngine为例。
步骤 1:安装 Spire.PDF
在 Visual Studio 的 NuGet 包管理器中运行以下命令:
Install-Package Spire.PDF
或从官方网站下载 Spire.PDF 安装包,并将 DLL 文件手动导入项目。
步骤 2:下载并配置 Qt 插件
根据系统下载对应的 Qt WebEngine 插件:
解压文件后可获得插件目录,例如:C:\plugins-windows-x64\plugins
在 C# 代码中注册插件路径:
HtmlConverter.PluginPath = @"C:\plugins-windows-x64\plugins";
HTML 模板非常适合需要表格、页眉页脚或复杂样式布局(如发票、报表)的文档。
步骤 1:构建带占位符的 HTML 模板
可在 HTML 中添加双花括号包裹的动态字段,例如:
<h1>发票</h1>
<p>发票编号: {{INVOICE_NUMBER}}</p>
<p>日期: {{INVOICE_DATE}}</p>
<p><strong>姓名: </strong> {{CUSTOMER_NAME}}</p>
步骤 2:使用运行时数据替换占位符
以下是一个生成发票 PDF 的完整示例代码:
using Spire.Additions.Qt;
using System.Drawing;
using Spire.Pdf.Graphics;
namespace CreatePdfFromHtmlTemplate
{
class Program
{
static void Main(string[] args)
{
// 带有占位符变量的HTML模板
string htmlTemplate = @"
<!DOCTYPE html>
<html lang=""zh"">
<head>
<meta charset=""UTF-8"">
<meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
<title>发票</title>
<style>
body {
font-family: ""SimHei"", ""黑体"", Tahoma, sans-serif;
margin: 40px auto;
padding: 20px;
max-width: 800px;
font-size: 20px;
}
h1 {
text-align: right;
font-size: 40px;
letter-spacing: 2px;
color: #222;
margin: 0 0 30px 0;
}
.invoice-header, .invoice-footer {
margin-bottom: 50px;
}
.invoice-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 3px solid #444;
padding-bottom: 10px;
}
.invoice-details {
margin: 20px 0;
padding: 15px;
background: #f5f5f5;
border-radius: 6px;
}
.invoice-details h2 {
font-size: 20px;
margin-bottom: 10px;
color: #444;
}
.info p {
margin: 2px 0;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 15px;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
th {
background-color: #efefef;
font-weight: 600;
}
tbody tr:nth-child(even) {
background: #f9f9f9;
}
.total {
margin-top: 20px;
text-align: right;
font-size: 15px;
}
.total p {
margin: 5px 0;
}
.total p span {
display: inline-block;
width: 120px;
}
.grand-total {
font-size: 18px;
font-weight: bold;
border-top: 2px solid #444;
margin-top: 10px;
padding-top: 10px;
}
.invoice-footer {
text-align: center;
font-size: 18px;
color: #666;
margin-top: 50px;
padding-top: 10px;
}
</style>
</head>
<body>
<div class=""invoice-header"">
<div>
<h2>公司名称</h2>
<p>123 商业街<br>重庆, 中国</p>
</div>
<div>
<h1>发票</h1>
<p>发票编号: {{INVOICE_NUMBER}}<br>日期: {{INVOICE_DATE}}</p>
</div>
</div>
<div class=""invoice-details"">
<h2>账单寄送至</h2>
<div class=""info"">
<p><strong>姓名:</strong> {{BILLER_NAME}}</p>
<p><strong>地址:</strong> {{BILLER_ADDRESS}}</p>
<p><strong>邮箱:</strong> {{BILLER_EMAIL}}</p>
</div>
</div>
<table>
<thead>
<tr>
<th>描述</th>
<th>数量</th>
<th>单价</th>
<th>行总计</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ITEM_DESCRIPTION}}</td>
<td>{{ITEM_QUANTITY}}</td>
<td>{{ITEM_UNIT_PRICE}}</td>
<td>{{ITEM_TOTAL}}</td>
</tr>
<!-- 这里可以添加更多行 -->
</tbody>
</table>
<div class=""total"">
<p><span>小计:</span> {{SUBTOTAL}}</p>
<p><span>税 ({{TAX_RATE}}%):</span> {{TAX}}</p>
<p class=""grand-total""><span>总计:</span> {{TOTAL}}</p>
</div>
<div class=""invoice-footer"">
<p>感谢您的惠顾!</p>
<p>如有任何疑问,请联系我们 该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。</p>
</div>
</body>
</html>
";
// 发票的样本数据 - 与模板占位符匹配的键值对
Dictionary<string, string> invoiceData = new Dictionary<string, string>()
{
{ "INVOICE_NUMBER", "12345" },
{ "INVOICE_DATE", "2025-08-25" },
{ "BILLER_NAME", "张三" },
{ "BILLER_ADDRESS", "重庆市新北街123号" },
{ "BILLER_EMAIL", "zhangsan@ example.com" },
{ "ITEM_DESCRIPTION", "咨询服务" },
{ "ITEM_QUANTITY", "10" },
{ "ITEM_UNIT_PRICE", "$100" },
{ "ITEM_TOTAL", "$1000" },
{ "SUBTOTAL", "$1000" },
{ "TAX_RATE", "5" },
{ "TAX", "$50" },
{ "TOTAL", "$1050" }
};
// 用实际数据值填充HTML模板
string populatedInvoice = PopulateInvoice(htmlTemplate, invoiceData);
// 指定生成的PDF输出文件路径
string outputFile = "HtmlToPdf.pdf";
// 指定HTML转换器的插件路径(QT插件)
string pluginPath = @"C:\plugins-windows-x64\plugins";
// 设置HTML到PDF转换所需的插件路径
HtmlConverter.PluginPath = pluginPath;
// 使用指定设置将HTML字符串转换为PDF
HtmlConverter.Convert(
populatedInvoice,
outputFile,
true, // 启用JavaScript
100000, // 超时(毫秒)
new SizeF(595, 842), // A4纸大小(595x842点)
new PdfMargins(20), // 四周20点边距
LoadHtmlType.SourceCode // 从源代码字符串加载HTML
);
}
// 辅助方法: 用数据字典中的实际值替换模板占位符
private static string PopulateInvoice(string template, Dictionary<string, string> data)
{
string result = template;
foreach (var entry in data)
{
result = result.Replace("{{" + entry.Key + "}}", entry.Value);
}
return result;
}
}
}
实现原理
输出结果:

有时设计团队会提供带有占位符(如 {PROJECT_NAME})的静态 PDF 模板。通过简单的文本替换即可将这些模板快速填充成正式文档。
示例:填充项目报告模板
using Spire.Pdf;
using Spire.Pdf.Texts;
using static Spire.Pdf.Texts.PdfTextReplaceOptions;
namespace GeneratePdfFromPdfTemplate
{
class Program
{
static void Main(string[] args)
{
// 创建一个PdfDocument对象
PdfDocument doc = new PdfDocument();
// 加载一个PDF文件
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Template.pdf");
// 创建一个PdfTextReplaceOptions对象并指定选项
PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();
textReplaceOptions.ReplaceType = ReplaceActionType.WholeWord; // 替换类型设置为整词替换
// 获取特定页面
PdfPageBase page = doc.Pages[0];
// 基于页面创建一个PdfTextReplacer对象
PdfTextReplacer textReplacer = new PdfTextReplacer(page);
textReplacer.Options = textReplaceOptions;
// 旧字符串和新字符串的字典
Dictionary<string, string> replacements = new Dictionary<string, string>()
{
{ "{PROJECT_NAME}", "新网站开发" },
{ "{PROJECT_NO}", "2023-001" },
{ "{PROJECT MANAGER}", "爱丽丝·约翰逊" },
{ "{PERIOD}", "2023年第三季度" },
{ "{START_DATE}", "2023年7月1日" },
{ "{END_DATE}", "2023年9月30日" }
};
// 遍历字典进行文本替换
foreach (var pair in replacements)
{
textReplacer.ReplaceText(pair.Key, pair.Value);
}
// 将文档保存为另一个PDF文件
doc.SaveToFile("FromPdfTemplate.pdf");
doc.Close();
}
}
}
实现原理
限制说明: 此方法仅适用于短文本(如姓名、编号、日期等)的替换。对于多行文本或动态扩展的内容,它的效果不佳,因为PDF不会自动重新排版文本。对于较大的内容块,请使用HTML或Word模板。
输出结果:

Spire.PDF 支持更多文本替换设置,请参考:在 C# 中替换 PDF 文档中的文本
选择合适的模板类型
占位符设计
测试与验证
模板管理
可以。对于复杂 HTML、CSS 或现代 JavaScript,建议使用 ChromeHtmlConverter 类,它能生成更精确的 PDF。
?详见教程:使用 ChromeHtmlConverter 将 HTML 转换为 PDF
PDF 布局固定,替换文本不会自动重排。当新文本过长可能溢出,过短则留白。适用于可预测的字段内容(如姓名、日期等)。对于多行文本或动态内容,可使用 HTML 或 Word 模板,或借助 Spire.PDF 的绘图 API 直接绘制新文本块。
Spire.PDF 主要用于 PDF 操作,如需根据 Word 模板生成PDF,可使用 Spire.Doc for .NET 替换 Word 模板内容,然后再保存为 PDF。
这样即可轻松添加公司 Logo、水印或电子签名。
使用 Spire.PDF 在 C# 中基于模板生成 PDF,是提升文档自动化效率的理想方式。无论选择 HTML 模板还是现有 PDF 模板,开发者都能轻松创建内容准确、版面统一、外观专业的文件。通过在开发流程中引入模板机制,不仅能显著减少重复性工作,还能确保品牌风格与格式的一致性。
在实施过程中,合理选择模板类型、规范占位符设计,并在部署前充分测试真实数据,能够帮助你获得更稳定的输出效果。随着项目的深入,还可以结合 Spire.PDF 的高级功能,如数字签名、加密与批注等,实现更安全、更智能的文档处理方案。
通过这一方法,你的团队将能够在保证质量与一致性的同时,大幅提升 PDF 文档的生成速度与管理效率,从而让自动化办公与报告生成更加高效、可控。
如果您需要去除生成文档中的评估提示或解除功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
在当今的数据驱动时代,Python 开发者经常需要将列表(一种基本的 Python 数据结构)转换为 Excel 电子表格。Excel 作为各行业通用的数据展示、报告生成与信息共享工具,无论是生成业务报告、准备分析数据,还是与非技术人员协作,掌握将 Python 列表导出为 Excel 的高效方法都至关重要。
虽然像 pandas 这样的轻量级库可以处理基本的导出操作,但 Spire.XLS for Python 提供了对 Excel 格式、样式及文件生成的完全控制,且无需依赖 Microsoft Excel。本文将探讨如何使用该库将各种列表结构转换为 Excel,包含详细的代码示例和最佳实践。
Python 中的列表在存储结构化或非结构化数据方面非常灵活,但 Excel 具有以下优势:
无论是销售数据、用户信息还是调研结果,将 Python 列表写入 Excel 都能让数据更易访问、更显专业。
1. 通过 pip 安装(最便捷方式):
打开终端 / 命令提示符,执行以下命令:
pip install Spire.XLS
2. 支持的功能与格式:
该库兼容.xls(Excel 97-2003)和.xlsx(Excel 2007 及以上)格式,可自定义 Excel 样式(如加粗标题、调整列宽、设置颜色),满足生产环境下的文件生成需求。
3. 免费License申请:
若需体验完整功能(无水印、无数据量限制),可点击此链接申请 30 天免费试用许可证。
对于基本的一维列表,您可以遍历列表项并将它们写入单个列或行中的连续单元格。 以下示例将文本列表转换为单个列。如果需要转换数值列表,您可以在保存前设置数字格式。
from spire.xls import *
from spire.xls.common import *
# 创建 Workbook 对象
workbook = Workbook()
# 清除默认工作表
workbook.Worksheets.Clear()
# 添加一个新工作表
worksheet = workbook.Worksheets.Add("简单列表")
# 准备待导出的一维列表(示例:产品列表)
data_list = ["鼠标", "键盘", "显示器", "音响", "硬盘"]
# 将列表数据写入Excel单元格(从第1行、第1列开始)
for index, value in enumerate(data_list):
worksheet.Range[index + 1, 1].Value = value
# 设置列宽以提高可读性
worksheet.Range[1, 1].ColumnWidth = 15
# 保存工作簿
workbook.SaveToFile("简单列表.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
如果您需要将列表导出到单个行,可以使用以下代码:
for index, value in enumerate(data_list):
worksheet.Range[1, index + 1].Value = value
输出结果:

嵌套列表(二维列表)表示含行 / 列结构的表格数据,非常适合直接转换为 Excel 表格。下面我们将一个包含员工数据(姓名、年龄、部门)的嵌套列表导出为 Excel 表格,并优化标题样式。
from spire.xls import *
from spire.xls.common import *
# 创建一个Workbook对象
workbook = Workbook()
# 清除默认工作表
workbook.Worksheets.Clear()
# 添加一个新工作表
worksheet = workbook.Worksheets.Add("员工数据")
# 嵌套列表(行:[姓名、年龄、部门])
employee_data = [
["姓名", "年龄", "部门"], # 标题行
["Alexander", 30, "人力资源"],
["Bob", 28, "技术"],
["Charlie", 35, "市场"],
["Diana", 29, "财务"]
]
# 将嵌套列表写入 Excel
for row_idx, row_data in enumerate(employee_data):
for col_idx, value in enumerate(row_data):
# 区分数据类型
if isinstance(value, int):
worksheet.Range[row_idx + 1, col_idx + 1].NumberValue = value
else:
worksheet.Range[row_idx + 1, col_idx + 1].Value = value
# 格式化标题行
worksheet.Range["A1:C1"].Style.Font.IsBold = True
worksheet.Range["A1:C1"].Style.Color = Color.get_Yellow()
# 设置列宽
worksheet.Range[1, 1].ColumnWidth = 10
worksheet.Range[1, 2].ColumnWidth = 6
worksheet.Range[1, 3].ColumnWidth = 15
# 保存工作簿
workbook.SaveToFile("二维列表.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
关键说明:
isinstance(value, int) 判断数值类型,用 NumberValue 赋值,避免 Excel 将 “年龄” 识别为文本。输出结果:

扩展建议:若需进一步优化表格,可使用 Spire.XLS 的其他功能,如添加单元格边框、设置条件格式或应用其他格式选项。
字典列表在 Python 中常用于存储带有标签字段的结构化数据(如 API 返回数据、数据库查询结果)。本示例将字典列表(如客户记录)导出为 Excel,并实现标题自动提取、列宽自适应。
from spire.xls import *
from spire.xls.common import *
# 创建一个Workbook对象
workbook = Workbook()
# 清除默认工作表
workbook.Worksheets.Clear()
# 添加一个新工作表
worksheet = workbook.Worksheets.Add("客户数据")
# 准备字典列表(每个字典对应一条客户数据,键为字段名)
customers = [
{"ID": 101, "姓名": "张xx", "邮箱": "zhang@ example.com"},
{"ID": 102, "姓名": "王xx", "邮箱": "wang@ example.com"},
{"ID": 103, "姓名": "李xx", "邮箱": "li@ example.com"}
]
# 自动提取标题
headers = list(customers[0].keys())
# 将标题写入第1行
for col, header in enumerate(headers):
worksheet.Range[1, col + 1].Value = header
worksheet.Range[1, col + 1].Style.Font.IsBold = True # 标题加粗
# 写入数据行
for row, customer in enumerate(customers, start=2): # 从第2行开始
for col, key in enumerate(headers):
value = customer[key]
if isinstance(value, (int, float)):
worksheet.Range[row, col + 1].NumberValue = value
else:
worksheet.Range[row, col + 1].Value = value
# 自动调整列宽
worksheet.AutoFitColumn(2)
worksheet.AutoFitColumn(3)
# 保存文件
workbook.SaveToFile("字典列表.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
核心优势:
AutoFitColumn 自动适配文字长度,解决 “文字截断” 问题;。输出结果:

NumberValue 赋值,避免 Excel 将其识别为文本(导致无法求和、排序)。Worksheet.AutoFitColumn() 替代手动设置列宽,尤其适合文本长度不固定的场景(如邮箱、备注)。Workbook.Dispose(),避免内存泄漏。通过 Python 将列表转换为 Excel 表格是数据处理的核心技能。Spire.XLS 能轻松创建精致、可用于生产环境的文件。无论是处理简单列表、嵌套数据还是字典,上述示例都能根据不同场景需求进行调整。若需进一步扩展功能(如添加 Excel 图表、公式、冻结窗格),可参考 Spire.XLS 官方文档。
答:pandas 非常适合快速、基础的导出,但格式控制能力弱(难调整字体、颜色、边框)。而 Spire.XLS 更适合精细化导出,支持:
答:在 SaveToFile 中使用 ExcelVersion 参数:
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2016)
workbook.SaveToFile("output.xls", ExcelVersion.Version97to2003)
答:针对不同数据类型,需使用对应的赋值属性:
.Text.NumberValue.DateTimeValue.BooleanValue答:创建 Workbook 时,Spire.XLS for Python 会生成默认工作表。因此,如果不使用 Workbook.Worksheets.Clear() 清除它们,最终 Excel 文件会包含额外的空工作表。
答:确认使用 1-based 索引(Excel 行 / 列从 1 开始,而非 Python 的 0 开始,以及数据类型是否与预期格式匹配。另外,确认在释放工作簿之前已保存文件。
纯文本(.txt)文件因简洁通用被广泛使用,但无法支持字体、表格、图片等格式;而 Word(.docx)文件虽具备丰富的排版能力,却难以直接用于文本分析、索引等场景。本文将详细介绍如何通过 Spire.Doc for Java(一款轻量级 Word 处理库),快速实现 TXT 文本文件与 Word 的双向转换。
相比其他 Java 文档处理工具,Spire.Doc for Java 在格式转换场景中具备显著优势:
要使用 Spire.Doc for Java 顺利完成 TXT 文本到 Word 的转换,您需要先从其官方下载页面下载该库,并将 Spire.Doc.jar 文件作为依赖项添加到 Java 程序中。
若项目使用 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>
TXT 转 Word 的核心逻辑是:通过 Document 类加载 TXT 文件,再以 Word 格式保存。整个过程只需几行代码即可完成,且支持自定义输出路径。
核心API说明
Document:核心类,用于在内存中表示 Word 文档。loadFromFile():通过内部解析器读取 TXT 内容,并将其封装到单个 Word 章节中,同时应用默认字体和页边距。saveToFile():调用该方法时,Spire.Doc 会自动将纯文本转换为 .docx 文件,本质是生成符合 OpenXML 格式的结构化 Word 文档。以下是分步代码示例:
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class ConvertTextToWord {
public static void main(String[] args) {
// 创建 Document 对象
Document txt = new Document();
// 加载 .txt 文本文件
txt.loadFromFile("介绍.txt");
// 将文件保存为 Word 格式
txt.saveToFile("TXT转Word.docx", FileFormat.Docx);
// 释放资源
txt.dispose();
}
}
转换结果:

扩展技巧:
将 TXT 文本文件转换为 DOC/DOCX 格式后,您可以根据需求进一步自定义文档格式。为简化这一过程,Spire.Doc for Java 提供了内置接口来编辑文本属性,如修改字体颜色、插入脚注、添加文字和图片水印等。
除了 TXT 转 Word,Spire.Doc for Java 还支持将 DOC/DOCX 文件转换为 TXT 格式,便于从格式丰富的 Word 文档中提取纯文本。该功能在以下场景中尤为实用:剥离格式和布局以获取简洁的原始内容,例如用于文本分析、搜索索引、归档,或导入仅支持纯文本的其他系统。
实现逻辑与 TXT 转 Word 类似,仅需修改保存格式:
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class ConvertWordtoText {
public static void main(String[] args) {
// 创建 Document 对象
Document doc = new Document();
// 加载 Word 文件
doc.loadFromFile("示例.docx");
// 将文档保存为 TXT 格
doc.saveToFile("Word转文本.txt", FileFormat.Txt);
// 释放资源
doc.dispose();
}
}
转换结果:

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请联系销售获取有效期 30 天的临时许可证。
使用 Spire.Doc for Java 实现 TXT 与 Word 的双向转换,具有速度快、准确性高的特点,且无需安装 Microsoft Word。这对于开发报表、文档生成或文件转换工具的 Java 开发者来说尤为实用。若需进一步探索Spire.Doc的功能(如Word表格操作、邮件合并),可参考官方文档。

在 Python 开发中,处理表格数据是非常常见的任务,而 Pandas 是最常用的数据处理和分析库。开发者经常需要将 Pandas DataFrame 导出到 Excel,以便进行报告、团队协作或进一步的数据分析。虽然 Pandas 提供了 to_excel 方法进行基本导出,但如果需要创建格式丰富和含图表的专业 Excel 报表,则需要借助专业Excel库。
本教程介绍如何在Python中使用 Spire.XLS for Python 库将单个或多个 Pandas DataFrame 写入到 Excel,并实现灵活的格式化与可视化设置。
虽然 Pandas 提供了基本的 Excel 导出功能,但它主要用于数据输出而非 Excel 文件处理,对格式设置、样式应用和图表生成等高级功能的支持有限。相比之下,Spire.XLS 是一个专为 Excel 文件创建与操作而设计的专业库,能够提供更灵活、更全面的控制。使用 Spire.XLS,开发者可以:
在导出 Pandas DataFrame 到 Excel 之前,请确保已安装pandas与Spire.XLS库:
pip install pandas spire.xls
这些库允许你将 DataFrame 导出到 Excel,并自定义格式、插入图表和生成结构化布局。
导出单个 DataFrame 到 Excel 是最常见的场景。使用 Spire.XLS,不仅可以导出 DataFrame,还可以格式化标题、设置单元格样式,并添加图表,让你的报表看起来更加专业。
具体实现步骤如下:
首先,需要创建一个 DataFrame。以下是一个示例DataFrame,你可以将其替换为自己的数据。
import pandas as pd
from spire.xls import *
# 创建一个示例 DataFrame
df = pd.DataFrame({
'姓名': ['张伟', '李娜', '王强'], # 员工姓名
'部门': ['人事部', '财务部', '技术部'], # 部门
'月薪': [8000, 9500, 12000] # 月薪
})
接下来,创建一个新的 Excel 工作簿,并获取第一个工作表。给工作表命名为 "员工信息",便于理解和管理。
# 创建新工作簿
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "员工信息" # 给工作表命名
将列标题写入 Excel 第一行,并加粗字体,同时设置浅灰色背景,使表格整洁、易于阅读。
# 写入列标题
for colIndex, colName in enumerate(df.columns, start=1):
cell = sheet.Range[1, colIndex]
cell.Text = colName
cell.Style.Font.IsBold = True # 设置标题加粗
cell.Style.Color = Color.get_LightGray() # 设置浅灰色背景
将 DataFrame 中的每一行数据写入 Excel。对于数字数据,使用 NumberValue 属性,让 Excel 能够识别并用于计算和绘图;对于文本数据,则使用 Text 属性。
# 写入数据行
for rowIndex, row in enumerate(df.values, start=2):
for colIndex, value in enumerate(row, start=1):
cell = sheet.Range[rowIndex, colIndex]
if isinstance(value, (int, float)):
cell.NumberValue = value # 数字使用 NumberValue
else:
cell.Text = str(value) # 文本使用 Text
为数据区域添加外部和内部边框,并让列宽自动适应内容长度,使 Excel 表格更加美观、像专业报表。
# 应用边框并自动调整列宽
usedRange = sheet.AllocatedRange
usedRange.BorderAround(LineStyleType.Thin, Color.get_Black()) # 外边框
usedRange.BorderInside(LineStyleType.Thin, Color.get_Black()) # 内边框
usedRange.AutoFitColumns() # 自动调整列宽
图表能够帮助快速理解数据趋势。在本示例中,我们创建一个柱状图,用于比较各员工月薪。
# 添加图表
chart = sheet.Charts.Add()
chart.ChartType = ExcelChartType.ColumnClustered # 设置柱状图
chart.DataRange = sheet.Range["A1:C4"] # 图表数据范围
chart.SeriesDataFromRange = False
chart.LeftColumn = 5 # 图表左侧位置
chart.TopRow = 1 # 图表上方位置
chart.RightColumn = 10 # 图表右侧位置
chart.BottomRow = 16 # 图表底部位置
chart.ChartTitle = "员工月薪对比" # 图表标题
chart.ChartTitleArea.Font.Size = 12
chart.ChartTitleArea.Font.IsBold = True
最后,将工作簿保存到指定位置。
# 保存 Excel 文件
workbook.SaveToFile("员工信息报表.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
生成结果:
Excel文件生成后,你可以对其进行进一步处理,例如将其转换为 PDF,方便分享:
workbook.SaveToFile("员工信息报表.pdf", FileFormat.PDF)
关于转换的详细设置,可查阅教程:Python 将 Excel 转为 PDF。
在生成 Excel 报表时,经常需要将多个数据集放在不同的工作表中。使用 Spire.XLS,每个 DataFrame 可以写入独立工作表,使相关数据清晰有序,便于分析。
具体实现步骤如下:
在导出前,创建两个 DataFrame:一个包含员工信息,另一个包含产品信息。每个 DataFrame 对应一个工作表。
import pandas as pd
from spire.xls import *
# 示例 DataFrame
df1 = pd.DataFrame({'姓名': ['张伟', '李娜'], '年龄': [28, 32]})
df2 = pd.DataFrame({'产品': ['笔记本电脑', '手机'], '价格': [7500, 3200]})
# 将 DataFrame 与对应工作表名绑定
dataframes = [
(df1, "员工信息"),
(df2, "产品信息")
]
这里 dataframes 是一个元组列表,将每个 DataFrame 与其对应的工作表名称关联起来。
创建一个新的工作簿,用于存放DataFrame数据。新工作簿默认包含三个工作表。
# 创建新工作簿
workbook = Workbook()
使用循环遍历列表中的 DataFrame,将每个数据集写入单独的工作表。同时为数据区域添加边框。
for i, (df, sheet_name) in enumerate(dataframes):
if i < workbook.Worksheets.Count:
sheet = workbook.Worksheets[i]
else:
sheet = workbook.Worksheets.Add()
sheet.Name = sheet_name
# 写入标题并设置字体加粗和背景颜色
for colIndex, colName in enumerate(df.columns, start=1):
cell = sheet.Range[1, colIndex]
cell.Text = colName
cell.Style.Font.IsBold = True
cell.Style.Color = Color.get_LightGray()
sheet.Columns[colIndex - 1].ColumnWidth = 15
# 写入数据行
for rowIndex, row in enumerate(df.values, start=2):
for colIndex, value in enumerate(row, start=1):
cell = sheet.Range[rowIndex, colIndex]
if isinstance(value, (int, float)):
cell.NumberValue = value
else:
cell.Text = str(value)
# 添加边框
usedRange = sheet.AllocatedRange
usedRange.BorderAround(LineStyleType.Thin, Color.get_Black())
usedRange.BorderInside(LineStyleType.Thin, Color.get_Black())
将Excel文件保存到指定位置。
workbook.SaveToFile("员工与产品信息.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
生成结果:

在实际工作中,有时并不希望新建 Excel 文件,而是需要将新的数据写入已有的工作簿。使用 Spire.XLS,可以轻松实现这一需求:只需加载现有工作簿,添加新的工作表或访问目标工作表,然后按照与新建工作簿相同的逻辑写入 DataFrame 数据。
以下代码展示了如何将一个Pandas DataFrame写入到现有Excel表格:
import pandas as pd
from spire.xls import *
workbook = Workbook()
workbook.LoadFromFile("员工与产品信息.xlsx")
new_df = pd.DataFrame({
'区域': ['华北', '华南', '华东', '西南'],
'销售额': [120000, 150000, 130000, 110000]
})
new_sheet = workbook.Worksheets.Add("区域销售")
# 写入标题
for colIndex, colName in enumerate(new_df.columns, start=1):
cell = new_sheet.Range[1, colIndex]
cell.Text = colName
cell.Style.Font.IsBold = True
cell.Style.Color = Color.get_LightGray()
new_sheet.Columns[colIndex - 1].ColumnWidth = 15
# 写入数据
for rowIndex, row in enumerate(new_df.values, start=2):
for colIndex, value in enumerate(row, start=1):
cell = new_sheet.Range[rowIndex, colIndex]
if isinstance(value, (int, float)):
cell.NumberValue = value
else:
cell.Text = str(value)
# 保存
workbook.SaveToFile("员工产品区域信息.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
生成结果:

除了基础导出外,还可以对导出过程进行自定义,以满足特定报表需求。例如,可以选择导出特定列,或者决定是否包含DataFrame索引,从而让 Excel 文件更加整洁、易读。
在实际场景中,很多时候并不需要导出 DataFrame 中的所有列。通过只导出需要的列,可以让 Excel 报表内容更加简洁,同时避免无关信息干扰阅读。
下面示例演示如何只导出姓名和部门两列:
import pandas as pd
from spire.xls import *
# 创建示例 DataFrame
df = pd.DataFrame({
'姓名': ['张伟', '李娜', '王强'],
'部门': ['人事部', '财务部', '技术部'],
'月薪': [8000, 9500, 12000]
})
# 指定需要导出的列
columns_to_export = ['姓名', '部门']
# 创建新的工作簿并获取第一个工作表
workbook = Workbook()
sheet = workbook.Worksheets[0]
# 写入标题行
for colIndex, colName in enumerate(columns_to_export, start=1):
sheet.Range[1, colIndex].Text = colName
# 写入数据行
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
for colIndex, value in enumerate(row, start=1):
sheet.Range[rowIndex, colIndex].Text = value
# 保存 Excel 文件
workbook.SaveToFile("选择列.xlsx")
workbook.Dispose()
默认情况下,DataFrame 的索引不会导出到 Excel。但在一些报表中,行号或索引对数据分析非常重要。此时,可以手动将索引写入工作表,使每一行都有明确标识。
下面示例展示如何在导出特定列的同时包含索引:
# 写入索引标题
sheet.Range[1, 1].Text = "索引"
# 写入索引数值(数字)
for rowIndex, idx in enumerate(df.index, start=2):
sheet.Range[rowIndex, 1].NumberValue = idx
# 写入其他列标题,从第二列开始
for colIndex, colName in enumerate(columns_to_export, start=2):
sheet.Range[1, colIndex].Text = colName
# 写入数据行
for rowIndex, row in enumerate(df[columns_to_export].values, start=2):
for colIndex, value in enumerate(row, start=2):
if isinstance(value, (int, float)):
sheet.Range[rowIndex, colIndex].NumberValue = value
else:
sheet.Range[rowIndex, colIndex].Text = str(value)
# 保存 Excel 文件
workbook.SaveToFile("包含索引.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
本文介绍了在 Python 中使用 Spire.XLS 将 Pandas DataFrame 导出到 Excel 的多种方法。通过示例可以看到,除了基础的数据导出外,还可以实现标题样式设置、数据格式化、向现有工作簿写入数据,以及选择特定列或包含索引等操作。这些方法让数据分析和报表生成过程更加灵活,使开发者能够更好地控制导出内容和展示效果,以适应不同的应用场景和业务需求。
答: 可以使用 Spire.XLS 或类似库将 DataFrame 写入 Excel 文件。这样不仅可以导出数据,还可以自定义表头样式、单元格格式以及添加图表等,使报表更专业。
答: 可以。通过 Spire.XLS,可以将多个 DataFrame 写入同一个工作簿的不同工作表中,从而将相关数据整合在一个文件里,便于管理和分析。
答: 可以将表头字体加粗、设置背景颜色,调整列宽和行高,数字使用 NumberValue 属性保存,以便 Excel 识别和计算。这些设置能让 Excel 报表看起来更规范、易读。
答: 可以。Spire.XLS 支持柱状图、折线图等多种图表类型,图表可以直接绑定 DataFrame 的数据,帮助快速展示数据趋势或对比分析。
答: 不需要。Spire.XLS 可以在 Python 中独立创建和格式化 Excel 文件,无需依赖 Excel 软件本身。
答: 可以。导出时可以指定需要的列,也可以选择是否包含索引,从而生成更简洁、针对性更强的报表。
Spire.Barcode for Java 5.2.0现已发布。该版本成功修复了两个在扫描条码图片时出现的问题。详情请查阅以下内容。
问题修复:

在现代应用程序中处理 PDF 文档是一个常见需求。无论是构建文档管理系统、ASP.NET Web 服务,还是桌面查看器应用,您可能在某些时候需要将 PDF 页面显示为图像。与其嵌入完整的 PDF 查看器,不如直接将 PDF 页面转换为 JPG 图像,这样就可以在支持图像的地方使用它们。
在本指南中,我们将逐步介绍如何使用 Spire.PDF for .NET 将 PDF 文件转换为 JPG 图像 。我们将涵盖转换单个页面的基础知识、处理多个页面、调整分辨率和质量、将图像保存到流中,甚至批量转换整个 PDF 文件夹。
阅读完本文后,您将清晰了解如何在 .NET 项目中实现 PDF 到图像的转换。
目录
Spire.PDF for .NET 是一款专业的 .NET PDF 组件库,使开发人员能够在 .NET 应用程序中创建、读取、编辑、转换和打印 PDF 文档。该库特别提供了高质量的 PDF 转图片功能,支持包括 JPG/JPEG、PNG、BMP、TIFF、SVG 和 EMF 在内的多种图片格式,能够满足不同场景下的输出需求。
安装方法
在开始将 PDF 转换 JPG 前,请确保已安装 Spire.PDF 库。您可以通过 Visual Studio 的 NuGet 包管理控制台轻松安装:
Install-Package Spire.PDF
或者,在 Visual Studio 中打开 NuGet 包管理器,搜索 Spire.PDF,然后点击安装。除此以外,您也可以从官网下载Spire.PDF for .NET,并手动添加 DLL 引用。
在 Spire.PDF 中,SaveAsImage() 方法是实现 PDF 转换为图像的核心接口。
方法重载1
Image SaveAsImage(int pageIndex, PdfImageType imageType)
方法重载2
Image SaveAsImage(int pageIndex, PdfImageType imageType, int dpiX, int dpiY)
支持的 PdfImageType 值
大多数开发人员在导出为 JPG 时使用 Bitmap。
以下示例展示如何将 PDF 的第一页转换为 JPG 图像:
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing.Imaging;
using System.Drawing;
namespace ConvertSpecificPageToJpg
{
class Program
{
static void Main(string[] args)
{
// 创建 PdfDocument 对象
PdfDocument doc = new PdfDocument();
// 加载示例 PDF 文档
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
// 将特定页面转换为位图图像
Image image = doc.SaveAsImage(0, PdfImageType.Bitmap);
// 将图像保存为 JPG 文件
image.Save("ToJPG.jpg", ImageFormat.Jpeg);
doc.Dispose();
}
}
}
效果图:

除了 JPG 以外,Spire.PDF 支持将 PDF 转换为多种其他图像格式,如 PNG、BMP、SVG 和 TIFF。有关详细信息,请参考教程:使用 C# 将PDF 转换为图片
转换所有页面
以下循环遍历所有页面,将每个页面转换为图像,并将其保存到磁盘,文件名中包含页码。
for (int i = 0; i < doc.Pages.Count; i++)
{
Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
string fileName = string.Format("Output\\ToJPG-{0}.jpg", i);
image.Save(fileName, ImageFormat.Jpeg);
}
转换特定范围的页面
要转换特定范围的页面(例如,页面 2 到 4),可以按如下方式修改 for 循环:
for (int i = 1; i <= 3; i++)
{
Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
string fileName = string.Format("Output\\ToJPG-{0}.jpg", i);
image.Save(fileName, ImageFormat.Jpeg);
}
默认的输出分辨率可能无法满足打印或精细分析的需求。您可以通过以下方式精确设置 DPI:
Image image = doc.SaveAsImage(0, PdfImageType.Bitmap, 300, 300);
image.Save("ToJPG.jpg", ImageFormat.Jpeg);
分辨率选择建议:
需要注意的是,提高 DPI 会获得更清晰的图像,但相应地会增加内存占用和文件大小。
除了直接保存到磁盘,您还可以将输出图像存储到内存流中,这在以下场景中特别实用:
using (MemoryStream ms = new MemoryStream())
{
pdf.SaveAsImage(0, PdfImageType.Bitmap, 300, 300).Save(ms, ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
}
通过这种方式,JPG 图像将以字节数组形式保存在内存中,方便进行后续处理。
当需要批量处理多个 PDF 文档时,可以使用以下转换方案:
string[] files = Directory.GetFiles("InputPDFs", "*.pdf");
foreach (string file in files)
{
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(https://cdn.e-iceblue.cn/file);
for (int i = 0; i < doc.Pages.Count; i++)
{
Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
string fileName = Path.GetFileNameWithoutExtension(file);
image.Save($"Output\\{fileName}-Page{i + 1}.jpg", ImageFormat.Jpeg);
}
doc.Dispose();
}
Spire.PDF 也支持将图片转回为 PDF,请参考:C# 图片转 PDF:将 JPG/PNG 转换为 PDF 文件
在使用 .NET 进行 PDF 转图片时可能会遇到一些常见问题,以下是相应的解决方案:
1. 大文件内存占用过高
2. 输出图像模糊或质量不佳
3. 文件路径相关问题
4. 加密 PDF 文件处理
doc.LoadFromFile("secured.pdf", "password");
5. 资源释放管理
遵循这些实践建议,能够有效提升转换效率并确保输出质量。
通过本指南的详细讲解,我们全面掌握了在 .NET 平台使用 Spire.PDF 库将 PDF 文档转换为 JPG 图像的方法。从基础的单个页面转换,到处理多页文档、调整图像分辨率与质量,再到将图像保存至内存流以及批量处理多个 PDF 文件,Spire.PDF 提供了一套灵活且功能强大的 API 来满足多样化的开发需求。
遵循文中的最佳实践与故障排查建议,如合理管理内存、处理加密文档以及确保资源正确释放,将帮助您构建出更加稳定、高效的 PDF 转图像功能。无论是集成到 Web 服务、桌面应用还是文档管理系统中,Spire.PDF for .NET 都是一个值得信赖的工具,能够帮助您优雅地解决 PDF 到 JPG 图像的转换需求。
是的。Spire.PDF 支持 PNG、BMP、SVG 等多种常见图像格式。
支持。但在加载文件时需要提供正确的密码才能进行转换。
完全可以。您可以将图像保存到内存流中,并通过 HTTP 响应直接返回给客户端。
支持。您可以加载 JPG、PNG 或 BMP 文件并将其插入到 PDF 页面中,实现图像到 PDF 的逆向转换。
如果您需要去除生成文档中的评估提示或解除功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
Spire.Office 10.9.0 现已发布。在这个版本中,Spire.Doc 提供了用于细粒度文档样式控制的核心接口;Spire.XLS 支持创建和修改公式;Spire.Presentation 修复了文档无法打开的问题;Spire.PDF 改进了 OFD 到 PDF 的转换;Spire.DocViewer 调整了与安全相关的依赖项;Spire.PDFViewer 添加了一个跨平台的 .NET 7.0 版本;Spire.Barcode 修复了字体应用问题。此外,本版本成功修复了许多已知问题。更多详细信息见下文。
该版本涵盖了最新版的 Spire.Doc、Spire.PDF、Spire.XLS、Spire.Presentation、Spire.Barcode、Spire.Email、Spire.DocViewer、Spire.PDFViewer、Spire.OfficeViewer 和 Spire.DataExport。
https://www.e-iceblue.cn/Downloads/Spire-Office-NET.html
新功能:
Document sDoc = new Document();
sDoc.LoadFromFile(inputFile);
ToPdfParameterList toPdfParameter = new ToPdfParameterList();
toPdfParameter.DigitalSignatureInfo = new PdfDigitalSignatureInfo(pfxInputFile, pfxPassword, "Test signing", "Spire Doc"); // 数字签名
toPdfParameter.DigitalSignatureInfo.HashAlgorithm = PdfDigitalSignatureHashAlgorithm.RipeMD160;
toPdfParameter.DigitalSignatureInfo.SignatureDate = nowDateTime;
toPdfParameter.DigitalSignatureInfo.TimestampConfiguration = new PdfDigitalSignatureTimestampConfiguration("https://freetsa.org/tsr", "bill", "Password"); // 时间戳
sDoc.SaveToFile(outputFile3, toPdfParameter);
int firstColumn = doc.Bookmarks["t_insert"].FirstColumn;
int lastColumn = doc.Bookmarks["t_insert"].LastColumn;
SearchOptions op = new SearchOptions();
op.IgnoreOfficeMath = false;
doc.Replace("ab","new", op);
Document doc = new Document("xx.docx");
ToPdfParameterList toPdf = new ToPdfParameterList(){ PageLayout = PdfPageLayout.TwoColumnLeft };
doc.SaveToFile("xx.pdf", toPdf);
IStyle style = document.Styles.FindByName("Normal");
if (style != null && style is ICharacterStyle)
{
ICharacterStyle cStyle = style as ICharacterStyle;
cStyle.CharacterFormat.FontName = "cambria";
cStyle.CharacterFormat.FontSize = 14;
cStyle.CharacterFormat.Bold = true;
cStyle.CharacterFormat.TextColor = Color.FromArgb(42, 123, 136);
}
string pStyleName = "testStyle";
Document document = new Document();
ParagraphStyle pStyle = (ParagraphStyle)document.Styles.Add(StyleType.ParagraphStyle, pStyleName);
pStyle.CharacterFormat.FontName = "Calibri";
pStyle.CharacterFormat.FontSize = 16;
pStyle.CharacterFormat.Bold = true;
pStyle.CharacterFormat.TextColor = Color.DarkRed;
Section section = document.AddSection();
Paragraph para = section.AddParagraph();
para.ApplyStyle(pStyle);
para.AppendText("Hello world!");
Style firstParaStyle = document.FirstSection.Body.FirstParagraph.Format.Style;
document.SaveToFile(outputDocxFile1, FileFormat.Docx);
document.Styles[pStyleName].RemoveSelf();
document.SaveToFile(outputDocxFile2, FileFormat.Docx);
Document doc = new Document();
Section section = doc.AddSection();
Table table = section.AddTable();
table.ResetCells(15, 4);
for (int i = 0; i < 15; i++)
{
TableRow row = table.Rows[i];
for (int j = 0; j < 4; j++)
{
TableCell cell = row.Cells[j];
cell.AddParagraph().AppendText(string.Format("{0} column.", (j % 2 == 0 ? "Even" : "Odd")));
cell.AddParagraph().AppendText(string.Format("Row banding {0}", (i % 3 == 0 ? "start" : "continuation")));
}
}
TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.TableStyle, "TestTableStyle1");
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.BorderType = BorderStyle.Double;
tableStyle.RowStripe = 3;
tableStyle.ConditionalStyles[TableConditionalStyleType.OddRowStripe].Shading.BackgroundPatternColor = Color.LightBlue;
tableStyle.ConditionalStyles[TableConditionalStyleType.EvenRowStripe].Shading.BackgroundPatternColor = Color.LightCyan;
tableStyle.ColumnStripe = 1;
tableStyle.ConditionalStyles[TableConditionalStyleType.EvenColumnStripe].Shading.BackgroundPatternColor = Color.LightPink;
table.ApplyStyle(tableStyle);
table.Format.StyleOptions = table.Format.StyleOptions | TableStyleOptions.ColumnStripe;
doc.SaveToFile(outputDocxFile1, FileFormat.Docx);
Document doc = new Document();
Section section = doc.AddSection();
TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.TableStyle, "TestTableStyle1");
tableStyle.HorizontalAlignment = RowAlignment.Center;
tableStyle.Borders.Color = Color.Blue;
tableStyle.Borders.BorderType = BorderStyle.Single;
Table table = section.AddTable();
table.ResetCells(1, 1);
table.Rows[0].Cells[0].AddParagraph().AppendText("Aligned to the center of the page");
table.PreferredWidth = PreferredWidth.FromPoints(300);
table.ApplyStyle(tableStyle);
section.AddParagraph().AppendText(" ");
tableStyle = (TableStyle)doc.Styles.Add(StyleType.TableStyle, "TestTableStyle2");
tableStyle.LeftIndent = 55;
tableStyle.Borders.Color = Color.Green;
tableStyle.Borders.BorderType = BorderStyle.Single;
table = section.AddTable();
table.ResetCells(1, 1);
table.Rows[0].Cells[0].AddParagraph().AppendText("Aligned according to left indent");
table.PreferredWidth = PreferredWidth.FromPoints(300);
table.Format.Style = tableStyle;
doc.SaveToFile(outputDocxFile1, FileFormat.Docx);
Document doc = new Document();
Section section = doc.AddSection();
Table table = section.AddTable();
table.ResetCells(15, 4);
for (int i = 0; i < 15; i++)
{
TableRow row = table.Rows[i];
for (int j = 0; j < 4; j++)
{
TableCell cell = row.Cells[j];
cell.AddParagraph().AppendText(string.Format("{0} column.", (j % 2 == 0 ? "Even" : "Odd")));
cell.AddParagraph().AppendText(string.Format("Row banding {0}", (i % 2 == 0 ? "Even" : "Odd")));
}
}
TableStyle tableStyle = doc.AddStyle(DefaultTableStyle.LightListAccent3);
table.ApplyStyle(tableStyle);
doc.SaveToFile(outputDocxFile1, FileFormat.Docx);
问题修复:
优化:
新功能:
Workbook workbook = new Workbook();
workbook.LoadFromFile("Equation_1.xlsx");
Worksheet sheet = workbook.Worksheets[0];
//添加公式
sheet.Equations.AddEquation(1, 1, 50, 50, "\frac{A}{B}");
// 获取该工作表中的第一个公式对象
IXlsEquation equation = sheet.Equations[0];
// 使用 LaTeX 语法更新该公式的文本内容
equation.UpdateByLatexText("\\text{tan}\\frac{\\alpha}{2}=\\frac{\\text{sin}\\alpha}{1+ \\text{cos}\\alpha}");
// 设置公式在工作表中的位置和大小
equation.Top = 19;
equation.Left = 72;
equation.Width = 100;
equation.Height = 100;
// 获取该工作表中的第二个公式对象
IXlsEquation equation1 = sheet.Equations[1];
// 获取该公式的子项集合
IEquationItemCollection equationItems = equation1.EquationItems;
// 获取第一个子项
IEquationItem item1 = equationItems[0];
item1.Text = "e-iceblue";
// 在公式末尾添加一个新的 LaTeX 公式
equationItems.AddByLatex("\\frac{n!}{r!(n-r)!} ");
// 在索引为 0 的位置插入一个 LaTeX 公式
equationItems.InsertByLatex(0, "\\Delta A B C");
workbook.SaveToFile("out.xlsx");
HTMLOptions.Default.IsSaveFreezedPanes = true; //true为保留冻结效果,false为不保留
sheet.Range["D7"].Formula = "=LAMBDA(val,max,IF(ISOMITTED(max),val,IF(AND(val>0,val<max),\"within range\",\"out of range\")))(A1,A2)";
sheet.Range["D5"].Formula = "=LAMBDA(a,b,IF(ISOMITTED(b),a*a,a*b))(A1,A2)";
问题修复:
新功能:
// true:逐份打印 ; 默认false:逐页打印
doc.PrintSettings.Collate = true;
问题修复:
问题修复:
调整:
修复:
调整:
新功能:
调整:
新功能: