C# PDF分析Helper主要设计类库

本文档介绍了一个C# PDF处理助手类库,用于从网络URL下载并保存PDF,提取PDF文本并保存为TXT,转换PDF为HTML,以及保存PDF中的图片。类库依赖于Spire.Pdf,提供了详细的代码示例。

条件:需要引用Spire.pdf 包。再使用以下类库进行具体操作。如果没有的表况下。可以到这里下载https://download.csdn.net/download/wulixing/11227168

也可以查询(征信PDF分析自动生成TXT并入Sqlserver库源码.rar) 这里是我写的一个案例。有相当不错的源码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Spire.Pdf;
using System.Threading;
using System.Drawing;
using System.Drawing.Imaging;
 
namespace PDFServer
{
    public class PDFHelper
    {

        /// <summary>
        /// 打開一個網絡地址,并且保存為一個PDF
        /// </summary>
        /// <param name="webUrl">網絡地址</param>
        ///  <param name="fileaddress">保存的物理地址</param>
        /// <param name="filename">保存的PDF名稱</param>
        /// <returns></returns>
        public string PdfReader(string webUrl,string fileaddress, string filename)
        {
            String pdoc = "";
            //create PdfDocument instance
            PdfDocument doc = new PdfDocument();
            //load html from URL

            var thread = new Thread(() =>
            {
                doc.LoadFromHTML(webUrl, false, true, true);

            });
            //set to single thread
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            //save to PDF document
            String s = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
            doc.SaveToFile(fileaddress + s + filename, FileFormat.PDF);//XXX.PDF\ HTML\ DOC\ XPS
            doc.Close();
            System.Diagnostics.Process.Start(fileaddress+s + filename);
            return pdoc;
        }

        /// <summary>
        /// 打開PDF文件
        /// </summary>
        /// <param name="filename">物理路徑 H:\pdfceshi\陈军清个人信用报告.pdf</param>
        /// <param name="txtpath">數據讀取后保存的txt文件 物理路徑 H:\pdfceshi\</param>
        ///  <param name="newfilename">新的文件名称</param>
        /// <returns></returns>
        public String OpenPDF(string filename,String txtpath,String newfilename)
        {
            String str = "";
            String str_error = "";
            int count =1;
         

            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(filename);

            //实例化一个StringBuilder 对象
            StringBuilder content = new StringBuilder();

            //遍历文档所有PDF页面,提取文本
            foreach (PdfPageBase page in doc.Pages)
            {
                try
                { 
                    String values = page.ExtractText();
                    if (!"".Equals(values))
                    {
                        content.Append(values);
                    }                   
                }
                catch (Exception ex)
                {

                    str_error += " 第[" + count + "] 次異常,內容{" + ex.ToString() + "}";
                }
                count++;
            }


            if (txtpath!="")
            { 
              
               File.WriteAllText(txtpath + newfilename, content.ToString());
               if (str_error!="")
               {
                   File.WriteAllText(txtpath +"_error_"+ newfilename, str_error);
               }
            }

            #region   将提取到的文本写为.txt格式并保存到本地路径
            //将提取到的文本写为.txt格式并保存到本地路径
            /**
               String s = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
               String fileName =  s + "_获取文本.doc";
               File.WriteAllText(fileName, content.ToString());
               System.Diagnostics.Process.Start(s + "_获取文本.doc");
               **/
            #endregion
           

            str = content.ToString();

           // doc.SaveToFile(txtpath + s+ ".txt", FileFormat.HTML);//XXX.PDF\ HTML\ DOC\ XPS
           // doc.Close();
            return str;
        }
        /// <summary>
        /// 打開PDF文件 轉成HTML
        /// </summary>
        /// <param name="filename">物理路徑 H:\pdfceshi\陈军清个人信用报告.pdf</param>
        /// <param name="txtpath">數據讀取后保存的txt文件 物理路徑 H:\pdfceshi\</param>
        /// <returns></returns>
        public String OpenPDFRealHTML(string filename, String txtpath)
        {
            String str = "";
            String str_error = "";
          

            String s = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(filename);
         

            if (txtpath != "")
            {
                try
                {
                    doc.SaveToFile(@"" + txtpath + s + ".doc", FileFormat.DOC);
                    doc.Close();
                    str = "OK";
                }
                catch (Exception EX)
                {

                    str_error = EX.ToString();
                }
              
                if (str_error != "")
                {
                    String fileName_error = s + "_获取PDF文本_error.txt";
                    File.WriteAllText(txtpath + fileName_error, str_error);
                }
            }
              
            return str;
        }

        /// <summary>
        /// 將PDF內的圖片保存到本地
        /// </summary>
        /// <param name="pdfPath">PDF路徑 H:\pdfceshi\sss.pdf"</param>
        /// <param name="imgPath">保存圖片的路徑 H:\pdfceshi\ </param>
        /// <returns></returns>
        public String GetPDFImageList(String pdfPath,String imgPath)
        {
            String str = "";

            //Create a pdf document.
            PdfDocument doc = new PdfDocument();
            // Load the PDF Document
            doc.LoadFromFile(@""+pdfPath);
            // Image collection to hold
            IList<Image> images = new List<Image>();
            // Loop thru each pages
            foreach (PdfPageBase page in doc.Pages)
            {
                // Check that page contains any images
                if (page.ExtractImages() != null)
                {
                    foreach (Image image in page.ExtractImages())
                    {
                        images.Add(image);
                    }
                }
            }
            //close the document
            doc.Close();
            //save image
            int index = 0;
            foreach (Image image in images)
            {
                String imageFileName = String.Format("Image-{0}.png", index++);
                image.Save(imgPath+imageFileName, ImageFormat.Png);
            }

            return str;
        
        }

        /// <summary>
        /// 获得路径下所有的pdf文件名称,返回结果集
        /// </summary>
        /// <param name="filename">目录 H:\pdfceshi\01</param>
        /// <param name="txtpath"></param>
        /// <param name="newfilename">新的文件名</param>
        /// <returns></returns>
        public int[] Getpath(string filename, String txtpath, String newfilename)
        {
            int[] totalvalue = new int[6];
            var files = Directory.GetFiles(filename, "*.pdf");

            int total = 0;
            int save = 0;
            int repeat = 0;
            int error = 0;
            int other = 0;
            int error_other = 0;
            foreach (var file in files)
            {
                #region 数据处理

                try
                {
                    String tep_fileName = file;
                    String[] pathlist = tep_fileName.Split('\\');
                    String tep_newfilename = newfilename;
                    if (pathlist.Length > 0)
                    {
                        String tep_name = pathlist[pathlist.Length - 1].Replace(".pdf", "");
                        tep_newfilename = tep_name + tep_newfilename;
                    }
                    String spath = OpenPDF(tep_fileName, txtpath, tep_newfilename);

                    if (spath.Length > 4)
                    {
                        //进行批时入库
                        Form1 f = new Form1();
                        int isSave = f.Gettxtstr(txtpath + tep_newfilename);
                        if (isSave == 1)
                        {
                            save++;
                        }
                        else if (isSave == 2)
                        {
                            repeat++;
                        }
                        else if (isSave == -1)
                        {
                            error++;
                        }
                        else if (isSave == -2)
                        {
                            error_other++;
                        }
                        else if (isSave == 0)
                        {
                            other++;
                        }
                        System.Threading.Thread.Sleep(300);
                    }

                    total++;

                }
                catch (Exception)
                {

                    error++;
                }
                #endregion
            }

            totalvalue[0] = total;
            totalvalue[1] = save;
            totalvalue[2] = repeat;
            totalvalue[3] = error;
            totalvalue[4] = other;
            totalvalue[5] = error_other;
            return totalvalue;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值