markdown 以其轻量级的语法提供了一种简化网页内容创建、协作和文档共享的方法,尤其在 git 或支持 markdown 的编辑器等工具流行的环境中。通过将 word 文档转换为 markdown 文件,用户可以提升生产效率,简化版本控制,并确保不同系统和平台之间的兼容性。本文将介绍如何使用 spire.doc for .net 通过 c# 代码将 word 文档转换为 markdown 文件。
安装 spire.doc for .net
首先,您需要将 spire.doc for.net 包含的 dll 文件作为引用添加到您的 .net 项目中。dll 文件可以从此链接下载,也可以通过 安装。
pm> install-package spire.doc
将 word 文档转换为 markdown 文件
使用 spire.doc for .net,我们可以通过加载文档使用 document.loadfromfile() 方法,然后使用 document.savetofile(filename: string, fileformat.markdown) 方法将其转换为 markdown 文件。具体步骤如下:
- 创建 document 类的实例。
- 使用 document.loadfromfile() 方法加载 word 文档。
- 使用 document.savetofile(filename: string, fileformat.markdown) 方法将文档转换为 markdown 文件。
- c#
using spire.doc;
namespace wordtomarkdown
{
class program
{
static void main(string[] args)
{
// 创建document类的实例
document doc = new document();
// 加载一个word文档
doc.loadfromfile("示例.docx");
// 将文档转换为markdown文件
doc.savetofile("output/word转markdown.md", fileformat.markdown);
doc.dispose();
}
}
}
删除 word 图片并转换为 markdown
当使用 spire.doc for .net 将 word 文档转换为 markdown 文件时,默认情况下图片会以 base64 编码存储,可能会使转换出的文件过大且影响兼容性。为了应对这一问题,我们可以在转换过程中移除图片,从而减小文件大小并提高兼容性。
以下步骤说明了如何移除 word 文档图片并将其转换为 markdown 文件:
- 创建 document 类的实例。
- 使用 document.loadfromfile() 方法加载 word 文档。
- 遍历文档中的各部分,再遍历段落。
- 遍历段落中的文档对象:
- 通过 paragraph.childobjects[] 属性获取文档对象。
- 检查其是否是 docpicture 类的实例。如果是,则使用 paragraph.childobjects.remove(documentobject) 方法将其从段落中移除。
- 使用 document.savetofile(filename: string, fileformat.markdown) 方法将文档转换为 markdown 文件。
- c#
using spire.doc;
using spire.doc.documents;
using spire.doc.fields;
namespace wordtomarkdownnoimage
{
class program
{
static void main(string[] args)
{
// 创建document类的实例
document doc = new document();
// 加载一个word文档
doc.loadfromfile("示例.docx");
// 遍历文档中的各个部分
foreach (section section in doc.sections)
{
// 遍历部分中的各个段落
foreach (paragraph paragraph in section.paragraphs)
{
// 遍历段落中的文档对象
for (int i = 0; i < paragraph.childobjects.count; i )
{
// 获取一个文档对象
documentobject docobj = paragraph.childobjects[i];
// 检查它是否是docpicture类的实例
if (docobj is docpicture)
{
// 移除docpicture实例
paragraph.childobjects.remove(docobj);
}
}
}
}
// 将文档转换为markdown文件
doc.savetofile("output/word转markdown移除图片.md", fileformat.markdown);
doc.dispose();
}
}
}
申请临时 license
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用javascript。获取有效期 30 天的临时许可证。