.net将Word,Pdf等文档文件中的文本提取出来代码分享

作者:小菜 更新时间:2025-03-16 点击数:
简介:经常有人问我怎么将类似word,pdf这样的文档转换为文本然后索引,.net 这方面的解决方案不是很多,为了方便大家,我花了一天时间自己做了一个。

Java 版本

【菜科解读】

经常有人问我怎么将类似word,pdf这样的文档转换为文本然后索引,.net 这方面的解决方案不是很多,为了方便大家,我花了一天时间自己做了一个。

Java 版本的 lucence 提供了一个 tika 的工具用于将 word, excel, pdf 等文档转换为文本,然后进行索引。

但这个工具没有 .net 版本,要在 .net 下用,需要用 IKVM.net,很麻烦。

而且这个工具实际上底层是调用 POI 和 PDFParse 来转换的。

从网上搜索到的信息看,POI 对 office 2007 以上版本的文档处理有问题,不知道最新版本是否解决了,我没有试过。

PDFParse 这个东西,我用过 .net 版本,对中文不支持,不知道 Java 版本是否支持。

其实 .net 下完全不需要用这些开源解决方案来解决,因为微软提供了一个官方的解决方案,这个解决方案叫 IFilter,这个过滤器是为 sql server 的全文索引设计的,但第三方软件可以调用API来完成文档的提取工作。

为了方便大家,我把 IFilter 转换的功能封装到了一个开源的组件中去,大家可以到下面地址去下载源码:HBTextParse.

调用很简单:

这个是提取文件中的文本到字符串的代码

if (openFileDialog.ShowDialog() == DialogResult.OK) //要转换的文件 textBoxFilePath.Text = openFileDialog.FileName; //实例化 TextParse ,传入要转换的文件路径 TextParse textParse = new TextParse(textBoxFilePath.Text); //提取文件中的文本,并输出 richTextBoxView.Text = textParse.ConvertToString();}这个是将文件转换为文本文件的代码:

if (saveFileDialog.ShowDialog() == DialogResult.OK) //实例化 TextParse,传入要转换的文件的路径 TextParse textParse = new TextParse(textBoxFilePath.Text); //将文件转换到 saveFileDialog.FileName 指定的文本文件中 textParse.ConvertToFile(saveFileDialog.FileName); catch (Exception ex) MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);}

要注意的问题是提取 Pdf 文档,如果机器是 64为操作系统,必须要安装Adobe PDF iFilter 9 for 64-bit platforms. 否则会报异常。

这个问题我搞了将近一天才搞定。

支持的文档类型:

目前这个组件可以支持所有 Microsoft office 提供的文档类型,包括 *.rtf, *.doc, *.docx, *.xls, *.xlsx, *.ppt, *.pptx 等等

除了微软Office的文档外,还可以转换

html 文档:可以把html文档中的文本提取出来(不包含标签)

Pdf 文档:我测试过,对中文支持没有问题

Txt 文档

这个代码的核心部分是一个叫 FilterCode 的类。

这个类是从http://ifilter.codeplex.com/这个地方下载的,我对这个类做了改进,加入了转换到文件的方法。

我把这个类的代码贴出来,如果对如何调用IFilter的windows API感兴趣,可以参考这段代码

IFilter 的相关API函数如下:通常这些API函数就可以通过IFilter接口提取文本。

[DllImport("query.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern int LoadIFilter(string pwcsPath, [MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, ref IFilter ppIUnk);

[ComImport, Guid("89BCB740-6119-101A-BCB7-00DD010655AF")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IFilter /// /// The IFilter::Init method initializes a filtering session. /// [PreserveSig] IFilterReturnCodes Init( //[in] Flag settings from the IFILTER_INIT enumeration for // controlling text standardization, property output, embedding // scope, and IFilter access patterns. IFILTER_INIT grfFlags, // [in] The size of the attributes array. When nonzero, cAttributes // takes // precedence over attributes specified in grfFlags. If no // attribute flags // are specified and cAttributes is zero, the default is given by // the // PSGUID_STORAGE storage property set, which contains the date and // time // of the last write to the file, size, and so on; and by the // PID_STG_CONTENTS // 'contents' property, which maps to the main contents of the // file. // For more information about properties and property sets, see // Property Sets. int cAttributes, //[in] Array of pointers to FULLPROPSPEC structures for the // requested properties. // When cAttributes is nonzero, only the properties in aAttributes // are returned. IntPtr aAttributes, // [out] Information about additional properties available to the // caller; from the IFILTER_FLAGS enumeration. out IFILTER_FLAGS pdwFlags); /// /// The IFilter::GetChunk method positions the filter at the beginning /// of the next chunk, /// or at the first chunk if this is the first call to the GetChunk /// method, and returns a description of the current chunk. /// [PreserveSig] IFilterReturnCodes GetChunk(out STAT_CHUNK pStat); /// /// The IFilter::GetText method retrieves text (text-type properties) /// from the current chunk, /// which must have a CHUNKSTATE enumeration value of CHUNK_TEXT. /// [PreserveSig] IFilterReturnCodes GetText( // [in/out] On entry, the size of awcBuffer array in wide/Unicode // characters. On exit, the number of Unicode characters written to // awcBuffer. // Note that this value is not the number of bytes in the buffer. ref int pcwcBuffer, // Text retrieved from the current chunk. Do not terminate the // buffer with a character. [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder awcBuffer); /// /// The IFilter::GetValue method retrieves a value (public /// value-type property) from a chunk, /// which must have a CHUNKSTATE enumeration value of CHUNK_VALUE. /// [PreserveSig] IFilterReturnCodes GetValue( // Allocate the PROPVARIANT structure with CoTaskMemAlloc. Some // PROPVARIANT // structures contain pointers, which can be freed by calling the // PropVariantClear function. // It is up to the caller of the GetValue method to call the // PropVariantClear method. // ref IntPtr ppPropValue // [MarshalAs(UnmanagedType.Struct)] ref IntPtr PropVal); /// /// The IFilter::BindRegion method retrieves an interface representing /// the specified portion of the object. /// Currently reserved for future use. /// [PreserveSig] IFilterReturnCodes BindRegion(ref FILTERREGION origPos, ref Guid riid, ref object ppunk); }

从文档中提取文本的代码如下:

/// /// Utilizes IFilter interface in Windows to parse the contents of files. /// ///

Path - Location of file to parse ///

Buffer - Return text artifacts /// Raw set of strings from the document in plain text format. public void GetTextFromDocument(string path, ref StringBuilder buffer) IFilter filter = null; int hresult; IFilterReturnCodes rtn; // Initialize the return buffer to 64K. buffer = new StringBuilder(64 * 1024); // Try to load the filter for the path given. hresult = LoadIFilter(path, new IntPtr(0), ref filter); if (hresult == 0) IFILTER_FLAGS uflags; // Init the filter provider. rtn = filter.Init( IFILTER_INIT.IFILTER_INIT_CANON_PARAGRAPHS | IFILTER_INIT.IFILTER_INIT_CANON_HYPHENS | IFILTER_INIT.IFILTER_INIT_CANON_SPACES | IFILTER_INIT.IFILTER_INIT_APPLY_INDEX_ATTRIBUTES | IFILTER_INIT.IFILTER_INIT_INDEXING_ONLY, 0, new IntPtr(0), out uflags); if (rtn == IFilterReturnCodes.S_OK) STAT_CHUNK statChunk; // Outer loop will read chunks from the document at a time. For those // chunks that have text, the contents will be pulled and put into the // return buffer. bool bMoreChunks = true; while (bMoreChunks) rtn = filter.GetChunk(out statChunk); if (rtn == IFilterReturnCodes.S_OK) // Ignore all non-text chunks. if (statChunk.flags != CHUNKSTATE.CHUNK_TEXT) continue; // Check for white space items and add the appropriate breaks. switch (statChunk.breakType) case CHUNK_BREAKTYPE.CHUNK_NO_BREAK: break; case CHUNK_BREAKTYPE.CHUNK_EOW: buffer.Append(' '); break; case CHUNK_BREAKTYPE.CHUNK_EOC: case CHUNK_BREAKTYPE.CHUNK_EOP: case CHUNK_BREAKTYPE.CHUNK_EOS: buffer.AppendLine(); break; // At this point we have a text chunk. The following code will pull out // all of it and add it to the buffer. bool bMoreText = true; while (bMoreText) // Create a temporary string buffer we can use for the parsing algorithm. int cBuffer = DefaultBufferSize; StringBuilder sbBuffer = new StringBuilder(DefaultBufferSize); // Read the next piece of data up to the size of our local buffer. rtn = filter.GetText(ref cBuffer, sbBuffer); if (rtn == IFilterReturnCodes.S_OK || rtn == IFilterReturnCodes.FILTER_S_LAST_TEXT) // If any data was returned, scrub it and then add it to the buffer. CleanUpCharacters(cBuffer, sbBuffer); buffer.Append(sbBuffer.ToString()); // If we got back some text but there is no more, terminate the loop. if (rtn == IFilterReturnCodes.FILTER_S_LAST_TEXT) bMoreText = false; break; // Once all data is exhausted, we are done so terminate. else if (rtn == IFilterReturnCodes.FILTER_E_NO_MORE_TEXT) bMoreText = false; break; // Check for any fatal errors. It is a bug if you land here. else if (rtn == IFilterReturnCodes.FILTER_E_NO_TEXT) System.Diagnostics.Debug.Assert(false, "Should not get here"); throw new InvalidOperationException(); // Once all chunks have been read, we are done with the file. else if (rtn == IFilterReturnCodes.FILTER_E_END_OF_CHUNKS) bMoreChunks = false; break; else if (rtn == IFilterReturnCodes.FILTER_E_EMBEDDING_UNAVAILABLE || rtn == IFilterReturnCodes.FILTER_E_LINK_UNAVAILABLE) continue; else throw new COMException("IFilter COM error: " + rtn.ToString()); else // If you get here there is no filter for the file type you asked for. Throw an // exception for the caller. throw new InvalidOperationException("Failed to find IFilter for file " + path); }

.net,将,Word,Pdf,等,文档,文件,中的,文本,

教你如何将win10手机投屏到电脑

我们都知道新出的win10系统有一个投屏的功能,它使我们的办公特别的便利,那么我们手机投屏到win10电脑怎么操作呢?下面小编就来把手机投屏到win10电脑的方法教给大家,一起学习下吧。

手机投屏到win10电脑怎么操作步骤如下: 1.首先我们打开win10的系统桌面,然后我们按下组合键“win+i 打开设置页面。

然后我们点击系统选项。

2.进入到页面后,我们在左侧找到”投影到此电脑“选项。

3.然后我们在右侧把第一个选项打开”所有位置都可用“。

4.接着我们将需要投屏的手机连接上跟电脑一样的wifi,然后我们打开手机设置,在手机设置界面找到”连接和共享“。

5.我们点击投屏选择需要连接的电脑。

6.选择电脑的型号,点击连接。

7.接着电脑提示是否允许连接,可以选择允许一次或者始终允许,点确定即可。

连接成功后手机屏幕图像就显示在电脑上了。

以上就是win10手机投屏到电脑的操作步骤内容,你学会了吗。

win10手机投屏到电脑,手机投屏到win10电脑怎么操作,手机投屏到win10电脑的方法

三国中被丑化的良将,70岁还在为国出征

末年乱局时代,也造就这个时代一些能臣良将,这期间人物犹如“走马灯”似的纷纷登上历史舞台。

有的人英明一世,名垂青史,有的人则一出场变消失。

还有的落下骂名。

最惨的莫过于那些生活在名将光环下,最后还落个丑化的名声。

时就这样一个将领,曾被丑化成“无能”将领,但他70多岁还上阵杀敌,是王朝无将,还是他要为留名而战? 这位将领就是三国时蜀汉将领廖化。

廖化在三国演义中一出场是一名盗贼身份出现的,他杀了杜远,然后把两位夫人放出。

其实,史料中的廖化却是沔南的豪门世族,最初任职是的主簿。

后来关羽兵败被东吴俘虏后,廖化投降了东吴。

史料记载,廖化因想念刘备,以诈死方式再次跑到蜀汉。

廖化西归蜀汉是不是是投降后良心发现呢? 不过廖化以单骑回到蜀汉,被后人认为他这一经历很传奇。

那么三国这位传奇式人物后来在蜀汉干得怎么样呢? 从廖化的职业看,他是主簿出身,这个职务是能写能画出谋略的职务,但从后期廖化的工作履历看,他却是蜀汉的一名将领,由此可以看出廖化是一个复合型人才,而且是一员能文能武的儒将。

但廖化在蜀汉时,却没放出多少光彩,因为那时的蜀汉名将云集,赵云、马超等老一辈将官太鑫,哪个都比廖化强。

但当这些老将退出后,我们从记载看,廖化依然活跃在蜀汉的军事舞台上。

但依然不是主帅,他又成为新生代将领手下将军,而且比王平、句扶的排名还靠下,只和张翼排在一起。

廖化七十多岁时,被刘禅派为先锋,继续领兵作战。

于是后人有了一句:“蜀中无大将,廖化作先锋”。

把廖化比作平庸将领,也笑话蜀汉已经没有人才了。

其实,从廖化一生看,虽然没有像关羽、、赵云等将领有过光彩夺目的战斗,但廖化终其一生为蜀汉兢兢业业,让他干啥他都去干,也取得了一些业绩。

公元238年9月,廖化率兵攻打魏国守善羌侯宕蕈驻守的营寨,雍州刺史郭淮派王赟、南安郡太守游奕率兵救援。

两军夹击廖化军队。

廖化抓住魏军分散弱点,击败游奕,王赟也在交战中箭身亡。

除了这场放彩战斗外,廖化其余战斗都是在主师的派遣下完成的例行性战斗。

但廖化也是一个有眼光的人,他曾劝姜维“用兵如果不收敛,必将自食恶果”,但姜维未听,最终败于邓艾。

廖化最后在姜维的指挥下兵败后,随姜维投降钟会。

但在去洛阳的路上病逝。

终其一生也没能真正成为一名主帅。

后人评价廖化,总把他作为一个平庸的将军。

但如果廖化是平庸之人,为何刘禅还一直用他?这说明廖化也有一定水平,并不是人们想象那样“囊”人。

只不过年轻时生活在名将如云光环之下,年老时新生代又比他厉害,他只能作为一位附属的将领存在。

后人认为廖化一生熬死很多人,虽有些调侃,但廖化七十多岁还能上战场,这说明此人老当益壮,为国效力之心未减。

所以评价廖化不应看他能多大能力,应该看其“忠”字,这一点很关键。

随机文章朝鲜三国时期简介明治维新与戊戌变法世界十大天坑望而生畏,燕子洞天坑深达426米(可跳伞)古埃及女木乃伊现精美文身,30处文身演绎别样魅力(地位尊贵)尼古拉特斯拉的惊世预言,精准预测第一次世界大战的开始结束时间

加入收藏
               

.net将Word,Pdf等文档文件中的文本提取出来代码分享

点击下载文档

格式为doc格式

  • 账号登录
社交账号登录