【问题标题】:Itextsharp Pdf to Text extractionItextsharp Pdf 到文本提取
【发布时间】:2013-11-23 07:19:51
【问题描述】:

如果我保存上传的 pdf 文件,它会抛出格式损坏的 msg。问题是如果我删除 下面的代码 字符串 resumetext = ParsePdf(resumedoc.PostedFile.InputStream); pdf文件保存完好。我可以打开它。 如果我添加上面的代码 Pdf 文件被保存为损坏的格式。

我在这两种情况下都能完美阅读文本。请帮我解决问题。

 string ext = System.IO.Path.GetExtension(FileUp.PostedFile.FileName);
        if (ext == ".pdf")
        {
    //resumedoc is input type='file' 
            string resumetext = ParsePdf(resumedoc.PostedFile.InputStream); 
            string Filename = "dddd" + ext;
            string FilePath =  "E:\\temp\\" + Filename;
            FileUp.PostedFile.SaveAs(FilePath);//Problem arises only here
            Response.Write("Uploaded");

}

public string ParsePdf(Stream inFileName)
{
    StringBuilder text = new StringBuilder();
    PdfReader pdfReader = new PdfReader(inFileName);
    for (int page = 1; page <= pdfReader.NumberOfPages; page++)
    {
        try
        {
            ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
            //ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
            string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
            text.Append(System.Environment.NewLine);
            currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
            text.Append(currentText);
        }
        catch { }

    }
    return text.ToString();
}

【问题讨论】:

  • 哈比你第一次打电话FileUp.PostedFile.SaveAs(FilePath)然后才打电话string resumetext = ParsePdf(resumedoc.PostedFile.InputStream)
  • 与您的问题无关,但请参阅这篇文章,解释为什么您永远不应该使用 Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText))); stackoverflow.com/a/10191879/231316

标签: pdf itextsharp


【解决方案1】:

我的猜测是,通过读取流,您正在移动流的当前位置,这让 SaveAs() 感到害怕,它期望位置为零。解析后写前尝试:

FileUp.PostedFile.InputStream.Seek(0, SeekOrigin.Begin);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    相关资源
    最近更新 更多