高效而穩定的企業級.NET Office 組件Spire(.NET組件介紹之二)

  在項目開發中,尤爲是企業的業務系統中,對文檔的操做是很是多的,有時幾乎給人一種錯覺的是」這個系統彷佛就是專門操做文檔的「。畢竟如今的不少辦公中大都是在PC端操做文檔等軟件,在這些龐大而繁重的業務中,單單依靠人力去作文檔的操做須要的代價是巨大的,好比數據統計,數據分析等業務要求。這就須要咱們在開發系統時,應該儘可能減小使用者的一些工做量,例如將數據直接寫入文檔,獲取網頁信息後直接存爲PDF保存,以便之後繼續查看。軟件開發的目地是對使用者便捷,但這一要求未必對開發者來講也是便捷的。javascript

    在前面介紹過一款開源免費的組件DocX,這個組件主要是對文檔進行操做。另外一種對Excel操做的組件NPOI組件。今天介紹一款.NET Office操做組件Spire,這是一個企業級的.NET Office操做組件,可是這是一款難免費也不開源的組件。可能不少人聽到這裏就不想再讀下去了,的確,在國內畢竟免費才能夠佔用主流市場,由於不少客戶但願減小成本,因此但願採用免費的工具。html

   做爲開發者,我也會有這樣的觀點,不過有的時候也會思考收費與免費的工具到底哪個好,其實這樣的思考到最後彷佛是沒有意義的,由於事物存在既有價值,免費的能夠減小成本,收費的能夠獲取穩定而安全的支持,各有優點和特色。任何一個軟件的生成都是須要成本的,由於任何軟件都是人員開發出來的,須要支付對應的成本,此處不收錢,其餘的地方也會收費。不管收費與免費的哪個好,技術老是沒有錯的,收費的東西,咱們也能夠了解,作一個技術儲備。java

    今天要介紹的一款組件有收費的部分和免費的部分,可是這款軟件的功能的確比較的強大,使用起來也比較簡單,由於要收費的東西,畢竟須要作到人性化,否則誰會出錢去買,畢竟便宜而好用的東西不多。此組件的使用方式很簡單,官方提供了比較完備的操做demo,因此今天的文章只作爲一個引子。web

    因爲Spire的組件較多,今天就用Spire.PDF for .NET作個引子,不必定收費就沒有客戶會選擇,若是須要穩定的服務支持,收費的組件是能夠考慮的,或者遇到土豪客戶,也能夠在項目中使用一下,畢竟使用起來很便捷。安全

一.Spire.PDF for .NET組件概述:

    Spire.PDF for .NET是一個專業的PDF組件,用於在.NET應用程序中建立,編寫,編輯,處理和閱讀PDF文件,而不須要任何外部依賴。 使用這個.NET PDF庫,您能夠實現豐富的功能從頭開始建立PDF文件或徹底經過C#/ VB.NET處理現有的PDF文檔,而無需安裝Adobe Acrobat。cookie

   .NET PDF API支持許多豐富的功能,例如安全設置(包括數字簽名),PDF文本/附件/圖像提取,PDF合併/拆分,元數據更新,段,圖像/圖像繪製和插入,表建立 以及處理和導入數據等。app

   此外,Spire.PDF for .NET能夠應用於使用C#/ VB.NET以高質量輕鬆地將文本,圖像和HTML轉換爲PDF。ide

   如下是一個官方給出的組件解析圖:函數

      Spire.PDF for .NET支持將HTML,RTF,XPS,文本和圖像轉換爲具備高效性能的PDF文檔。 開發人員能夠將PDF轉換爲Word,XPS,SVG,EMF,JPG,PNG,BMP,TIFF,文本格式。 此外,隨着Spire.Doc for .NET和Spire.XLS for .NET,開發人員能夠將Word(Doc / Docx),Excel(Xls / Xlsx)和XML轉換爲PDF。工具

     此組件的功能仍是很是強大的,每一個開發人員都知道,產品作得很差,想要客戶的錢仍是很難的。看一下組件的主要功能:

    1.文本格式,多語言支持,文本對齊等。

    2.筆和畫筆將形狀元素,文本,圖像繪製成PDF文檔。

    3.圖層,透明圖形,顏色空間和條形碼建立能夠呈現爲PDF文檔。

    4.PDF / A-1b和PDF / x1a:2001合規性,能夠應用這兩種標準。

    5.添加標量/矢量圖像和掩碼,並將它們放在指定的位置。

    6.Spire.PDF for .NET可支持表和表樣式

    7.插入交互式元素,包括註釋,操做,JavaScript,附件,書籤和指定地點和外觀。

   以上對組件的相關背景作了一個簡單的介紹,而且對組件的功能和使用情形作了簡單的羅列。

二.Spire.PDF for .NET相關類的解析:

      在這裏主要介紹Spire的Spire.PDF組件部分,此組件有免費的和收費的兩個版本,免費的版本在功能沒有收費的多,可是穩定性和實用性仍是較高的。咱們具體看一下此組件的主要的類和方法,這裏是主要介紹PDF的操做,就先看一下有關PDF的操做類和方法。

     這裏看如下命名空間的主要類:

    

     以上的方法中只是操做PDF部分類,因爲包含的類較多,過大的介紹篇幅就顯得多餘,在對PDF的操做中提供了較多的方法,所以在功能上會較爲的豐富,使用起來也較爲的便捷。

  1.PdfDocument類:聲明PDF文檔:

     (1).PdfDocument類的構造函數:

    public PdfDocument();
    public PdfDocument(string filename);
    public PdfDocument(byte[] bytes);
    public PdfDocument(Stream stream);
    public PdfDocument(string filename, string password);
    public PdfDocument(byte[] bytes, string password);
    public PdfDocument(Stream stream, string password);

該類提供了7個構造函數的重載版本,對應的參數類型就不作詳細的介紹

   (2).PdfDocument.LoadFromHTML():加載HTML頁面:

public void LoadFromHTML(string Url, bool enableJavaScript, bool enableHyperlinks, bool autoDetectPageBreak)
{
    // This item is obfuscated and can not be translated.
    PdfHtmlLayoutFormat format;
    int num;
    goto Label_001E;
Label_008F:
    num = 0;
Label_0002:
    switch (num)
    {
        case 0:
            break;

        case 1:
            if (!autoDetectPageBreak)
            {
                format.Layout = PdfLayoutType.OnePage;
                format.FitToPage = Clip.Width;
                format.FitToHtml = Clip.Height;
                num = 2;
            }
            else
            {
                num = 3;
            }
            goto Label_0002;

        case 2:
            switch ((1 == 1))
            {
                case 2:
                    goto Label_008F;
            }
            if (0 != 0)
            {
            }
            break;

        case 3:
            format.Layout = PdfLayoutType.Paginate;
            format.FitToPage = Clip.Width;
            goto Label_008F;

        default:
            goto Label_001E;
            if (1 != 0)
            {
            }
            format = new PdfHtmlLayoutFormat();
            num = 1;
            goto Label_0002;
    }
    this.Sections.Add().LoadFromHTML(Url, enableJavaScript, enableHyperlinks, format);
}

   2.HtmlConverter名稱空間:Html轉換器。

namespace Spire.Pdf.HtmlConverter
{
    public enum AspectRatio

    public enum Clip

    [ToolboxItem(false)]
    public class HtmlConverter : UserControl, sprᰐ, sprᶪ, sprṳ, sprẝ, sprẏ

    public enum ImageType

    public class PdfHtmlLayoutFormat
}
private Metafile ᜍ();
    static HtmlConverter();
    public HtmlConverter();
    public int Authenticate(ref IntPtr phwnd, ref IntPtr pszUsername, ref IntPtr pszPassword);
    public HtmlToPdfResult Convert(string url, ImageType type, int width, int height, AspectRatio aspectRatio);
    public HtmlToPdfResult Convert(string html, string baseurl, ImageType type, int width, int height, AspectRatio aspectRatio);
    public HtmlToPdfResult Convert(string url, ImageType type, int width, int height, AspectRatio aspectRatio, string username, string password);
    public Image ConvertToImage(string url, ImageType type);
    public Image ConvertToImage(Stream stream, Encoding encoding, ImageType type);
    public Image ConvertToImage(string url, ImageType type, int width);
    public Image ConvertToImage(Stream stream, Encoding encoding, ImageType type, int width);
    public Image ConvertToImage(string url, ImageType type, int width, int height);
    public Image ConvertToImage(string url, ImageType type, string username, string password);
    public Image ConvertToImage(Stream stream, Encoding encoding, ImageType type, int width, int height);
    public Image ConvertToImage(string url, ImageType type, int width, int height, AspectRatio aspectRatio);
    public Image ConvertToImage(string url, ImageType type, int width, string username, string password);
    public Image ConvertToImage(Stream stream, Encoding encoding, ImageType type, int width, int height, AspectRatio aspectRatio);
    public Image ConvertToImage(string url, ImageType type, int width, int height, string username, string password);
    public Image ConvertToImage(string url, ImageType type, int width, int height, AspectRatio aspectRatio, string username, string password);
    [DispId(-5512)]
    public int CustomizeDownload();
    protected override void Dispose(bool disposing);
    public Image FromString(string html, ImageType type, int width);
    public Image FromString(string html, string baseUrl, ImageType type);
    public Image FromString(string html, ImageType type, int width, int height);
    public Image FromString(string html, string baseUrl, ImageType type, int width);
    public Image FromString(string html, ImageType type, int width, int height, AspectRatio aspectRatio);
    public Image FromString(string html, string baseUrl, ImageType type, int width, int height);
    public Image FromString(string html, string baseUrl, ImageType type, int width, int height, AspectRatio aspectRatio);
    public Image FromString(string html, string baseUrl, ImageType type, int width, int height, AspectRatio aspectRatio, string username, string password);
    public Image[] GetImagesFromString(string html, string baseUrl, ImageType type);
    public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject);int sprẏ.GetSecurityId(string pwszUrl, IntPtr pbSecurityId, ref uint pcbSecurityId, ref uint dwReserved);
    int sprẏ.GetSecuritySite(out IntPtr pSite);
    int sprẏ.GetZoneMappings(uint dwZone, out IEnumString ppenumString, uint dwFlags);
    int sprẏ.MapUrlToZone(string pwszUrl, out uint pdwZone, uint dwFlags);
    int sprẏ.ProcessUrlAction(string pwszUrl, uint dwAction, IntPtr pPolicy, uint cbPolicy, IntPtr pContext, uint cbContext, uint dwFlags, uint dwReserved);
    int sprẏ.QueryCustomPolicy(string pwszUrl, ref Guid guidKey, out IntPtr ppPolicy, out uint pcbPolicy, IntPtr pContext, uint cbContext, uint dwReserved);
    int sprẏ.SetSecuritySite(IntPtr pSite);
    int sprẏ.SetZoneMapping(uint dwZone, string lpszPattern, uint dwFlags);
    int sprᶪ.GetContainer(object ppContainer);
    int sprᶪ.GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk);
    int sprᶪ.OnShowWindow(bool fShow);
    int sprᶪ.RequestNewObjectLayout();
    int sprᶪ.SaveObject();
    int sprᶪ.ShowObject();
   

   以上是對PDF操做的相關類和方法的查看,因爲此軟件爲商業軟件,只能查看部分對外公開的代碼,可是從能夠查看到的代碼就能夠看出其內部實現的複雜度。若是須要詳細瞭解:http://www.e-iceblue.com/Introduce/free-pdf-component.html#.WEEFj_l962w。

三.Spire.PDF for .NET實例:

   因爲本文主要講解HTML頁面轉換爲PDF文檔,因此先提供一種GET請求HTML頁面,以及一種獲取頁面圖片的操做方法。接着介紹建立PDF文檔、Text轉化爲PDF, XPS轉換爲

PDF,Image轉換爲PDF等操做方法。 

1.建立HTTP的GET請求,獲取網頁信息:

        /// <summary>
        /// 指定路徑發送GET請求
        /// </summary>
        /// <param name="getUrl"></param>
        /// <returns></returns>
        public static string HttpGet(string getUrl)
        {
            try
            {
                if (string.IsNullOrEmpty(getUrl))
                    throw new ArgumentNullException(getUrl);
                var request = WebRequest.Create(getUrl) as HttpWebRequest;
                if (request == null)
                    return null;
                var cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                var response = request.GetResponse() as HttpWebResponse;
                if (response != null)
                {
                    var instream = response.GetResponseStream();
                    if (instream == null)
                        throw new ArgumentNullException("getUrl");
                    string content;
                    using (var sr = new StreamReader(instream, Encoding.UTF8))
                    {
                        content = sr.ReadToEnd();
                    }
                    return content;
                }
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }
            return null;
        }

  2.取得HTML中全部圖片的 URL:

        /// <summary>   
        /// 取得HTML中全部圖片的 URL。   
        /// </summary>   
        /// <param name="url">HTML代碼</param>
        /// <returns>圖片的URL列表</returns> 
        public static string HtmlCodeRequest(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(url);
            }
            try
            {
                //建立一個請求
                var httprequst = (HttpWebRequest)WebRequest.Create(url);
                //不創建持久性連接
                httprequst.KeepAlive = true;
                //設置請求的方法
                httprequst.Method = "GET";
                //設置標頭值
                httprequst.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705";
                httprequst.Accept = "*/*";
                httprequst.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");
                httprequst.ServicePoint.Expect100Continue = false;
                httprequst.Timeout = 5000;
                //是否容許302
                httprequst.AllowAutoRedirect = true;
                ServicePointManager.DefaultConnectionLimit = 30;
                //獲取響應
                var webRes = (HttpWebResponse)httprequst.GetResponse();
                //獲取響應的文本流
                string content;
                using (var stream = webRes.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
                    {
                        content = reader.ReadToEnd();
                    }
                }
                //取消請求
                httprequst.Abort();
                //返回數據內容
                return content;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

   3.建立PDF文檔:

            PdfDocument doc = new PdfDocument();

            doc.LoadFromHTML(url, false, true, true);

            doc.Close();

以上沒有將操做組裝爲一個方法,因爲建立操做較爲簡單,因此不作詳細介紹,url爲網頁路徑地址。
HtmlConverter.Convert
("http://www.wikipedia.org/","HTMLtoPDF.pdf",
 //enable javascript 
 true,
 //load timeout
100 * 1000,
//page size
new SizeF(612, 792),
//page margins
new PdfMargins(0, 0));

   4.Text轉化爲PDF:

 public static void  TextLayout()
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            // Create one page
            PdfPageBase page = doc.Pages.Add();
            float pageWidth = page.Canvas.ClientSize.Width;
            float y = 0;

            //page header
            PdfPen pen1 = new PdfPen(Color.LightGray, 1f);
            PdfBrush brush1 = new PdfSolidBrush(Color.LightGray);
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 8f, FontStyle.Italic));
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Right);
            String text = "Demo of Spire.Pdf";
            page.Canvas.DrawString(text, font1, brush1, pageWidth, y, format1);
            SizeF size = font1.MeasureString(text, format1);
            y = y + size.Height + 1;
            page.Canvas.DrawLine(pen1, 0, y, pageWidth, y);

            //title
            y = y + 5;
            PdfBrush brush2 = new PdfSolidBrush(Color.Black);
            PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
            PdfStringFormat format2 = new PdfStringFormat(PdfTextAlignment.Center);
            format2.CharacterSpacing = 1f;
            text = "Summary of Science";
            page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2);
            size = font2.MeasureString(text, format2);
            y = y + size.Height + 6;

            //icon
            PdfImage image = PdfImage.FromFile(@"..\..\..\..\..\..\Data\Wikipedia_Science.png");
            page.Canvas.DrawImage(image, new PointF(pageWidth - image.PhysicalDimension.Width, y));
            float imageLeftSpace = pageWidth - image.PhysicalDimension.Width - 2;
            float imageBottom = image.PhysicalDimension.Height + y;

            //refenrence content
            PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font("Arial", 9f));
            PdfStringFormat format3 = new PdfStringFormat();
            format3.ParagraphIndent = font3.Size * 2;
            format3.MeasureTrailingSpaces = true;
            format3.LineSpacing = font3.Size * 1.5f;
            String text1 = "(All text and picture from ";
            String text2 = "Wikipedia";
            String text3 = ", the free encyclopedia)";
            page.Canvas.DrawString(text1, font3, brush2, 0, y, format3);

            size = font3.MeasureString(text1, format3);
            float x1 = size.Width;
            format3.ParagraphIndent = 0;
            PdfTrueTypeFont font4 = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Underline));
            PdfBrush brush3 = PdfBrushes.Blue;
            page.Canvas.DrawString(text2, font4, brush3, x1, y, format3);
            size = font4.MeasureString(text2, format3);
            x1 = x1 + size.Width;

            page.Canvas.DrawString(text3, font3, brush2, x1, y, format3);
            y = y + size.Height;

            //content
            PdfStringFormat format4 = new PdfStringFormat();
            text = System.IO.File.ReadAllText(@"..\..\..\..\..\..\Data\Summary_of_Science.txt");
            PdfTrueTypeFont font5 = new PdfTrueTypeFont(new Font("Arial", 10f));
            format4.LineSpacing = font5.Size * 1.5f;
            PdfStringLayouter textLayouter = new PdfStringLayouter();
            float imageLeftBlockHeight = imageBottom - y;
            PdfStringLayoutResult result
                = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight));
            if (result.ActualSize.Height < imageBottom - y)
            {
                imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight;
                result = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight));
            }
            foreach (LineInfo line in result.Lines)
            {
                page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4);
                y = y + result.LineHeight;
            }
            PdfTextWidget textWidget = new PdfTextWidget(result.Remainder, font5, brush2);
            PdfTextLayout textLayout = new PdfTextLayout();
            textLayout.Break = PdfLayoutBreakType.FitPage;
            textLayout.Layout = PdfLayoutType.Paginate;
            RectangleF bounds = new RectangleF(new PointF(0, y), page.Canvas.ClientSize);
            textWidget.StringFormat = format4;
            textWidget.Draw(page, bounds, textLayout);

            //Save pdf file.
            doc.SaveToFile("TextLayout.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("TextLayout.pdf");
        }

   5.XPS轉換爲PDF:

  public void XPStoPDF()
        {
            //xps file
            String file = @"..\..\..\..\..\..\Data\Sample4.xps";

            //open xps document
            PdfDocument doc = new PdfDocument();
            doc.LoadFromXPS(file);

            //convert to pdf file.
            doc.SaveToFile("Sample4.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("Sample4.pdf");
        }

   6.Image轉換爲PDF:

 public void ImageToPdf()
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            // Create one page
            PdfPageBase page = doc.Pages.Add();

            //Draw the text
            page.Canvas.DrawString("Hello, World!",
                                   new PdfFont(PdfFontFamily.Helvetica, 30f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);
            //Draw the image
            PdfImage image = PdfImage.FromFile(@"..\..\..\..\..\..\Data\SalesReportChart.png");
            float width = image.Width * 0.75f;
            float height = image.Height * 0.75f;
            float x = (page.Canvas.ClientSize.Width - width) / 2;

            page.Canvas.DrawImage(image, x, 60, width, height);

            //Save pdf file.
            doc.SaveToFile("Image.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("Image.pdf");
        }

   以上提供了對網站發起HTTP請求,獲取網站頁面信息,以及採用Spire.PDF組件建立PDF文檔。若是有須要能夠直接將HTTP請求獲取到的信息直接加載如Spire.PDF的組件中,

由組件直接將網頁信息轉化爲PDF文件,在這裏就再也不作更多的贅述,因爲官方提供了很完善的demo和操做文檔,在這裏就再也不過多的介紹使用方法。

四.總結:

    以上介紹了一款收費不開源的組件,沒有更多的深刻的去介紹,因爲組件不開源,沒法進行反編譯,畢竟存在版權問題,若是須要使用到企業級的文檔操做組件,而且公司不缺錢的話,可使用一下此組件,組件的底層方法封裝度較高,因此在使用的時候,開發者所須要考慮的是如何去使用組件完成功能。

   我的認爲軟件收費應該是趨勢,畢竟任何軟件都是須要投入,不管是人力成本,仍是資金和時間成本。本文雖然是一篇介紹技術的文章,可是也提出了一個全部開發者都在想的問題,在項目開發中到底需不須要使用收費的軟件,其實這個就是看使用環境。

 

 

.NET組件介紹系列:

    一款開源免費的.NET文檔操做組件DocX(.NET組件介紹之一)http://www.cnblogs.com/pengze0902/p/6122311.html

    高效而穩定的企業級.NET Office 組件Spire(.NET組件介紹之二)http://www.cnblogs.com/pengze0902/p/6125570.html

    最好的.NET開源免費ZIP庫DotNetZip(.NET組件介紹之三)http://www.cnblogs.com/pengze0902/p/6124659.html

    免費開源的DotNet二維碼操做組件ThoughtWorks.QRCode(.NET組件介紹之四)http://www.cnblogs.com/pengze0902/p/6134506.html

    免費開源的DotNet任務調度組件Quartz.NET(.NET組件介紹之五)http://www.cnblogs.com/pengze0902/p/6128558.html

    免費高效實用的Excel操做組件NPOI(.NET組件介紹之六)http://www.cnblogs.com/pengze0902/p/6150070.html

相關文章
相關標籤/搜索