文庫關鍵技術之PDF轉換為HTML

來源:互聯網
上載者:User

標籤:des   style   blog   color   使用   os   io   檔案   

Aspose.PDF的使用方法,官網上介紹的都有,但是都比較簡單,主要是起樣本作用。

結合自己實際工作,我對相關方法進行了整理,自認為比較關鍵的地方,會作簡要說明。

 

用來轉換成html之前,必須對filepath和folder進行定義,切記切記。

 

class PdfTools{    /// <summary>    /// 源檔案    /// </summary>    public string filepath { get; set; }    /// <summary>    ///     /// </summary>    private string filename {        get {            string _filename = Path.GetFileName(filepath);            _filename = _filename.Substring(0, _filename.IndexOf(‘.‘));            return _filename;        }    }    /// <summary>    /// 最終檔案目標夾    /// </summary>    public string folder { get; set; }    public PdfTools() { }    public PdfTools(string _filepath, string _folder)    {        filepath = _filepath;        folder = _folder;        folder = folder.Replace("/",@"\");        if (folder.EndsWith(@"\") == false)            folder = folder + @"\";    }    /// <summary>    /// 將PDF檔案轉換成一個完整的HTML    /// filepath為PDF源檔案,必須將檔案路徑填寫完整    /// folder為最終儲存目錄,組建檔案均在此目錄下    /// </summary>    /// <returns></returns>    public bool Pdf2Html_NoSplit()    {        //判斷PDF檔案是否存在        if (File.Exists(filepath) == false)            return false;        folder = folder.Replace("/", @"\");        if (folder.EndsWith(@"\") == false)            folder = folder + @"\";        if (Directory.Exists(folder) == true)            Directory.Delete(folder,true);        Directory.CreateDirectory(folder);        Document doc = new Document(filepath);        HtmlSaveOptions hso = new HtmlSaveOptions();        hso.SplitIntoPages = false;        hso.FixedLayout = true;        hso.CompressSvgGraphicsIfAny = true;

//我偏向於所有資源存放在一個檔案夾內,因此,需要重寫下面三個函數 hso.CustomResourceSavingStrategy
= new HtmlSaveOptions.ResourceSavingStrategy(ResourceStrategy); hso.CustomCssSavingStrategy = new HtmlSaveOptions.CssSavingStrategy(CssStrategy); hso.CustomStrategyOfCssUrlCreation = new HtmlSaveOptions.CssUrlMakingStrategy(CssUrlStrategy); hso.FontSavingMode = HtmlSaveOptions.FontSavingModes.AlwaysSaveAsTTF; string outpath = folder + filename + ".html"; try { doc.Save(outpath, hso); return true; } catch { Directory.Delete(folder,true); return false; } }/// <summary> /// 根據PDF檔案產生首頁縮圖 /// </summary> /// <param name="_input">PDF源檔案完整路徑</param> /// <param name="_output">圖片儲存路徑</param> public void CreateThumb(string _input,string _output) { if (File.Exists(_output) == true) File.Delete(_output); using (Document doc = new Document(_input)) using (FileStream imgstream = new FileStream(_output, FileMode.Create)) { //圖片顯示品質 Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(100); Aspose.Pdf.Devices.PngDevice device = new Aspose.Pdf.Devices.PngDevice(resolution); device.Process(doc.Pages[1], imgstream); imgstream.Close(); } } /// <summary> /// 從PDF檔案中提取本文 /// </summary> /// <param name="_input">PDF檔案目錄</param> /// <returns></returns> public string GetTxtFromPDF(string _input) { Document doc = new Document(_input); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= doc.Pages.Count; i++) { Aspose.Pdf.Text.TextAbsorber ab = new Aspose.Pdf.Text.TextAbsorber(); ab.TextSearchOptions.LimitToPageBounds = true; try { doc.Pages[i].Accept(ab); sb.Append(ab.Text); } catch { return null; } } sb = sb.Replace("\r\n", " ").Replace(" "," "); string output = sb.ToString(); while (output.IndexOf(" ") >= 0) output = output.Replace(" "," "); return output; }/// <summary> /// 對字型、圖片進行重新命名,如果不用該函數,頁面可能出現異常 /// </summary> /// <param name="resource"></param> /// <returns></returns> private string ResourceStrategy(SaveOptions.ResourceSavingInfo resource) { string resourcename = ""; if (resource.ResourceType == SaveOptions.NodeLevelResourceType.Image) resourcename = Guid.NewGuid().ToString() + Path.GetExtension(resource.SupposedFileName); else resourcename = resource.SupposedFileName; if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); string outfile = folder + resourcename; if (File.Exists(resourcename) == true) return resourcename; System.IO.BinaryReader reader = new BinaryReader(resource.ContentStream); System.IO.File.WriteAllBytes(outfile, reader.ReadBytes((int)resource.ContentStream.Length)); return resourcename; }/// <summary> /// 產生頁面引用的css檔案 /// </summary> /// <param name="resource"></param> private void CssStrategy(HtmlSaveOptions.CssSavingInfo resource) { string path = folder+ filename + @".css"; BinaryReader reader = new BinaryReader(resource.ContentStream); File.WriteAllBytes(path, reader.ReadBytes((int)resource.ContentStream.Length)); } /// <summary> /// 對頁面引用的css地址進行重寫 /// </summary> /// <param name="resource"></param> /// <returns></returns> private string CssUrlStrategy(HtmlSaveOptions.CssUrlRequestInfo resource) { return filename + ".css"; }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.