【发布时间】:2014-07-12 07:35:30
【问题描述】:
我正在做一个项目,我需要从 pdf 文件中获取文本数据并将整个文本转储到数据库列中。在 iTextsharp 的帮助下,我得到了数据并将其引用为 String。
但现在我需要检查字符串是否超过 4MB 限制,如果超过则接受大小小于 4MB 的字符串数据。
这是我的代码:
internal string ReadPdfFiles()
{
// variable to store file path
string filePath = null;
// open dialog box to select file
OpenFileDialog file = new OpenFileDialog();
// dilog box title name
file.Title = "Select Pdf File";
//files to be accepted by the user.
file.Filter = "Pdf file (*.pdf)|*.pdf|All files (*.*)|*.*";
// set initial directory of computer system
file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// set restore directory
file.RestoreDirectory = true;
// execute if block when dialog result box click ok button
if (file.ShowDialog() == DialogResult.OK)
{
// store selected file path
filePath = file.FileName.ToString();
}
//file path
/// use a string array and pass all the pdf for searching
//String filePath = @"D:\Pranay\Documentation\Working on SSAS.pdf";
try
{
//creating an instance of PdfReader class
using (PdfReader reader = new PdfReader(filePath))
{
//creating an instance of StringBuilder class
StringBuilder text = new StringBuilder();
//use loop to specify how many pages to read.
//I started from 5th page as Piyush told
for (int i = 5; i <= reader.NumberOfPages; i++)
{
//Read the pdf
text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
}//end of for(i)
int k = 4096000;
//Test whether the string exceeds the 4MB
if (text.Length < k)
{
//return the string
text1 = text.ToString();
} //end of if
} //end of using
} //end try
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Please Do select a pdf file!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
} //end of catch
return text1;
} //end of ReadPdfFiles() method
帮帮我吧!
【问题讨论】:
-
您遇到了什么问题?您已经编写了检测字符串长度的代码,因此如果长度过大,您只需提供错误消息。或者您在将其存储在数据库中时遇到问题?您的数据库访问代码是什么样的?
-
你想在最大值时发生什么。长度达到?中止整个过程并显示错误消息?或者也许写出第一块然后继续?在这种情况下,请更改代码的结构以从循环中调用 write 方法,而不是返回它!
标签: c# string pdf itextsharp