溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何理解.NETOffice組件Spire

發(fā)布時(shí)間:2021-09-16 11:50:17 來源:億速云 閱讀:126 作者:柒染 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)如何理解.NETOffice組件Spire,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

在項(xiàng)目開發(fā)中,尤其是企業(yè)的業(yè)務(wù)系統(tǒng)中,對文檔的操作是非常多的,有時(shí)幾乎給人一種錯(cuò)覺的是”這個(gè)系統(tǒng)似乎就是專門操作文檔的“。畢竟現(xiàn)在的很多辦公中大都是在PC端操作文檔等軟件,在這些龐大而繁重的業(yè)務(wù)中,單單依靠人力去做文檔的操作需要的代價(jià)是巨大的,比如數(shù)據(jù)統(tǒng)計(jì),數(shù)據(jù)分析等業(yè)務(wù)要求。這就需要我們在開發(fā)系統(tǒng)時(shí),應(yīng)該盡量減少使用者的一些工作量,例如將數(shù)據(jù)直接寫入文檔,獲取網(wǎng)頁信息后直接存為PDF保存,以便以后繼續(xù)查看。軟件開發(fā)的目地是對使用者便捷,但這一要求未必對開發(fā)者來說也是便捷的。

作為開發(fā)者,我也會有這樣的觀點(diǎn),不過有的時(shí)候也會思考收費(fèi)與免費(fèi)的工具到底哪一個(gè)好,其實(shí)這樣的思考到最后似乎是沒有意義的,因?yàn)槭挛锎嬖诩扔袃r(jià)值,免費(fèi)的可以減少成本,收費(fèi)的可以獲取穩(wěn)定而安全的支持,各有優(yōu)勢和特點(diǎn)。任何一個(gè)軟件的生成都是需要成本的,因?yàn)槿魏诬浖际侨藛T開發(fā)出來的,需要支付對應(yīng)的成本,此處不收錢,其他的地方也會收費(fèi)。無論收費(fèi)與免費(fèi)的哪一個(gè)好,技術(shù)總是沒有錯(cuò)的,收費(fèi)的東西,我們也可以了解,做一個(gè)技術(shù)儲備。

今天要介紹的一款組件有收費(fèi)的部分和免費(fèi)的部分,但是這款軟件的功能的確比較的強(qiáng)大,使用起來也比較簡單,因?yàn)橐召M(fèi)的東西,畢竟需要做到人性化,不然誰會出錢去買,畢竟便宜而好用的東西很少。此組件的使用方式很簡單,官方提供了比較完備的操作demo,所以今天的文章只做為一個(gè)引子。

由于Spire的組件較多,今天就用Spire.PDF for .NET做個(gè)引子,不一定收費(fèi)就沒有客戶會選擇,如果需要穩(wěn)定的服務(wù)支持,收費(fèi)的組件是可以考慮的,或者遇到土豪客戶,也可以在項(xiàng)目中使用一下,畢竟使用起來很便捷。

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

Spire.PDF for .NET是一個(gè)專業(yè)的PDF組件,用于在.NET應(yīng)用程序中創(chuàng)建,編寫,編輯,處理和閱讀PDF文件,而不需要任何外部依賴。 使用這個(gè).NET PDF庫,您可以實(shí)現(xiàn)豐富的功能從頭開始創(chuàng)建PDF文件或完全通過C#/ VB.NET處理現(xiàn)有的PDF文檔,而無需安裝Adobe Acrobat。

 .NET PDF API支持許多豐富的功能,例如安全設(shè)置(包括數(shù)字簽名),PDF文本/附件/圖像提取,PDF合并/拆分,元數(shù)據(jù)更新,段,圖像/圖像繪制和插入,表創(chuàng)建 以及處理和導(dǎo)入數(shù)據(jù)等。

此外,Spire.PDF for .NET可以應(yīng)用于使用C#/ VB.NET以高質(zhì)量輕松地將文本,圖像和HTML轉(zhuǎn)換為PDF。

以下是一個(gè)官方給出的組件解析圖:

如何理解.NETOffice組件Spire

Spire.PDF for .NET支持將HTML,RTF,XPS,文本和圖像轉(zhuǎn)換為具有高效性能的PDF文檔。 開發(fā)人員可以將PDF轉(zhuǎn)換為Word,XPS,SVG,EMF,JPG,PNG,BMP,TIFF,文本格式。 此外,隨著Spire.Doc for .NET和Spire.XLS for .NET,開發(fā)人員可以將Word(Doc / Docx),Excel(Xls / Xlsx)和XML轉(zhuǎn)換為PDF。

此組件的功能還是非常強(qiáng)大的,每個(gè)開發(fā)人員都知道,產(chǎn)品做得不好,想要客戶的錢還是很難的??匆幌陆M件的主要功能:

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

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

3.圖層,透明圖形,顏色空間和條形碼創(chuàng)建可以呈現(xiàn)為PDF文檔。

4.PDF / A-1b和PDF / x1a:2001合規(guī)性,可以應(yīng)用這兩種標(biāo)準(zhǔn)。

5.添加標(biāo)量/矢量圖像和掩碼,并將它們放在指定的位置。

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

7.插入交互式元素,包括注釋,操作,JavaScript,附件,書簽和指定地點(diǎn)和外觀。

以上對組件的相關(guān)背景做了一個(gè)簡單的介紹,并且對組件的功能和使用情形做了簡單的羅列。

二.Spire.PDF for .NET相關(guān)類的解析:

在這里主要介紹Spire的Spire.PDF組件部分,此組件有免費(fèi)的和收費(fèi)的兩個(gè)版本,免費(fèi)的版本在功能沒有收費(fèi)的多,但是穩(wěn)定性和實(shí)用性還是較高的。我們具體看一下此組件的主要的類和方法,這里是主要介紹PDF的操作,就先看一下有關(guān)PDF的操作類和方法。

這里看以下命名空間的主要類:

如何理解.NETOffice組件Spire

如何理解.NETOffice組件Spire

如何理解.NETOffice組件Spire

如何理解.NETOffice組件Spire

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

  1.PdfDocument類:聲明PDF文檔:

(1).PdfDocument類的構(gòu)造函數(shù):

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個(gè)構(gòu)造函數(shù)的重載版本,對應(yīng)的參數(shù)類型就不做詳細(xì)的介紹

(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轉(zhuǎn)換器。

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操作的相關(guān)類和方法的查看,由于此軟件為商業(yè)軟件,只能查看部分對外公開的代碼,但是從可以查看到的代碼就可以看出其內(nèi)部實(shí)現(xiàn)的復(fù)雜度。

三.Spire.PDF for .NET實(shí)例:

   由于本文主要講解HTML頁面轉(zhuǎn)換為PDF文檔,所以先提供一種GET請求HTML頁面,以及一種獲取頁面圖片的操作方法。接著介紹創(chuàng)建PDF文檔、Text轉(zhuǎn)化為PDF, XPS轉(zhuǎn)換為PDF,Image轉(zhuǎn)換為PDF等操作方法。

1.創(chuàng)建HTTP的GET請求,獲取網(wǎng)頁信息:

/// <summary>
    /// 指定路徑發(fā)送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
      {
        //創(chuàng)建一個(gè)請求
        var httprequst = (HttpWebRequest)WebRequest.Create(url);
        //不建立持久性鏈接
        httprequst.KeepAlive = true;
        //設(shè)置請求的方法
        httprequst.Method = "GET";
        //設(shè)置標(biāo)頭值
        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;
        //獲取響應(yīng)
        var webRes = (HttpWebResponse)httprequst.GetResponse();
        //獲取響應(yīng)的文本流
        string content;
        using (var stream = webRes.GetResponseStream())
        {
          using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
          {
            content = reader.ReadToEnd();
          }
        }
        //取消請求
        httprequst.Abort();
        //返回?cái)?shù)據(jù)內(nèi)容
        return content;
      }
      catch (Exception ex)
      {
        throw new Exception(ex.Message);
      }
    }

3.創(chuàng)建PDF文檔:

PdfDocument doc = new PdfDocument();

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

      doc.Close();

以上沒有將操作組裝為一個(gè)方法,由于創(chuàng)建操作較為簡單,所以不做詳細(xì)介紹,url為網(wǎng)頁路徑地址。

HtmlConverter.Convert
("http://www.wikipedia.org/","HTMLtoPDF.pdf",
 //enable javascript 
 true,
 //load timeout
* 1000,
//page size
new SizeF(612, 792),
//page margins
new PdfMargins(0, 0));

4.Text轉(zhuǎn)化為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 brush2 = 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, brush2, 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 brush3 = 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, brush3, 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, brush3, 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 brush4 = PdfBrushes.Blue;
      page.Canvas.DrawString(text2, font4, brush4, x1, y, format3);
      size = font4.MeasureString(text2, format3);
      x1 = x1 + size.Width;

      page.Canvas.DrawString(text3, font3, brush3, 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, brush3, 0, y, format4);
        y = y + result.LineHeight;
      }
      PdfTextWidget textWidget = new PdfTextWidget(result.Remainder, font5, brush3);
      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轉(zhuǎn)換為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轉(zhuǎn)換為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");
    }

以上提供了對網(wǎng)站發(fā)起HTTP請求,獲取網(wǎng)站頁面信息,以及采用Spire.PDF組件創(chuàng)建PDF文檔。如果有需要可以直接將HTTP請求獲取到的信息直接加載如Spire.PDF的組件中,

由組件直接將網(wǎng)頁信息轉(zhuǎn)化為PDF文件,在這里就不再做更多的贅述,由于官方提供了很完善的demo和操作文檔,在這里就不再過多的介紹使用方法。

 以上介紹了一款收費(fèi)不開源的組件,沒有更多的深入的去介紹,由于組件不開源,無法進(jìn)行反編譯,畢竟存在版權(quán)問題,如果需要使用到企業(yè)級的文檔操作組件,并且公司不缺錢的話,可以使用一下此組件,組件的底層方法封裝度較高,所以在使用的時(shí)候,開發(fā)者所需要考慮的是如何去使用組件完成功能。

  

看完上述內(nèi)容,你們對如何理解.NETOffice組件Spire有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI