Elaborate on the efficient and stable enterprise-level. NET Office component Spire (. NET Component introduction II),. netspire
In project development, especially in enterprise business systems, there are many operations on documents, sometimes the illusion is that "this system seems to be a specialized operation document". After all, many of the current offices mostly operate documents and other software on the PC end. In these huge and heavy businesses, the cost of simply relying on manpower to perform document operations is huge, for example, business requirements such as data statistics and data analysis. This requires us to minimize the workload of users during system development. For example, we can directly write data to documents and save the webpage information as PDF for further viewing. The purpose of software development is convenient for users, but this requirement may not be convenient for developers.
I have introduced DocX, an open-source and free component, which is mainly used for document operations. An NPOI component for Excel operations. Today, we will introduce a. NET Office Operation component Spire, an enterprise-level. NET Office Operation component, which is neither free nor open-source. Many people may not want to read it any more. Indeed, it is free to use the mainstream market in China after all, because many customers want to reduce costs, so they want to use free tools.
As a developer, I also have such a point of view. However, sometimes I think about which of the billing and free tools is good. In fact, this thinking seems meaningless at the end, because things are valuable, free of charge can reduce costs, and stable and secure support can be obtained for billing, each with its own advantages and characteristics. The generation of any software requires cost, because any software is developed by personnel and the corresponding cost needs to be paid. No money is collected here, and fees are charged elsewhere. No matter which one is charged or free, there is always nothing wrong with technology. We can also learn about it and make a technical reserve.
The component I want to introduce today has a paid part and a free part. However, this software is indeed quite powerful and easy to use, because of the charges, after all, we need to be human-oriented. Otherwise, people will pay for it. After all, there are few cheap and useful things. The usage of this component is very simple. The official website provides a relatively complete operation demo, so today's article is only an introduction.
Since there are many Spire components, Spire is used today. PDF. NET as an introduction, no customers will choose if they do not have to pay for it. If stable service support is required, the charged components can be considered, or they can meet local luxury customers, it can also be used in projects. After all, it is very convenient to use.
I. Spire. PDF for. NET Component Overview:
Spire. PDF for. NET is a professional PDF component used to create, compile, edit, process, and read PDF files in. NET applications without any external dependencies. With this. net pdf library, you can create PDF files from scratch or process existing PDF files completely through C #/VB. NET without installing Adobe Acrobat.
. Net pdf api supports many rich functions, such as security settings (including digital signatures), PDF text/attachment/image extraction, PDF merge/split, metadata update, segment, image/Image Rendering and insertion, table creation, processing, and data import.
In addition, Spire. PDF for. NET can be applied to use C #/VB. NET to easily convert text, images, and HTML to PDF with high quality.
The following is an official component analysis diagram:
Spire. PDF for. NET supports converting HTML, RTF, XPS, text and images into PDF documents with efficient performance. Developers can convert PDF files to Word, XPS, SVG, EMF, JPG, PNG, BMP, TIFF, and text formats. In addition, with Spire. Doc for. NET and Spire. XLS for. NET, developers can convert Word (Doc/Docx), Excel (Xls/Xlsx), and XML to PDF.
The functions of this component are still very powerful. Every developer knows that the product is not doing well and it is still difficult to get the customer's money. Let's take a look at the main functions of the component:
1. Text format, multi-language support, text alignment, etc.
2. Pen and paint brush draw shape elements, text, and images into PDF documents.
3. layers, transparent images, color spaces, and bar codes can be displayed as PDF documents.
4. PDF/A-1b and PDF/x1a: 2001 compliance, which can be applied to both standards.
5. Add scalar/vector images and masks and place them at the specified position.
6. Spire. PDF for. NET supports table and Table Styles.
7. Insert interactive elements, including comments, operations, JavaScript, attachments, bookmarks, and specific locations and appearances.
The above is a brief introduction to the background of the component, and the functions and usage of the component are briefly listed.
Ii. parsing related classes of Spire. PDF for. NET:
Here we will mainly introduce the Spire of Spire. in the PDF component section, this component has two free and paid versions. The free version does not charge much for its functions, but its stability and practicality are still high. Let's take a look at the main classes and methods of this component. Here we mainly introduce the operations of PDF. Let's take a look at the operation classes and methods of PDF.
Here we will look at the main classes of the following namespaces:
In the above method, only the PDF category is operated. Because there are many classes included, too much space will be introduced, and many methods are provided for PDF operations, therefore, the functions are rich and convenient to use.
1. Declare document class: declare PDF document:
(1) constructor of the document class:
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);
This class provides overloaded versions of 7 constructors, the corresponding parameter types will not be described in detail
(2) .PdfDocument.LoadFromHTML (): Load HTML page:
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 namespace: Html converter.
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 ();
The above is a review of the related classes and methods of PDF operation. Since this software is commercial software, only part of the externally disclosed code can be viewed, but the complexity of its internal implementation can be seen from the viewable code.
Three. Spire.PDF for .NET example:
Since this article mainly explains the conversion of HTML pages to PDF documents, we first provide a GET request for HTML pages and an operation method for obtaining page pictures. Then introduce the operation methods of creating PDF documents, converting Text to PDF, converting XPS to PDF, and converting Image to PDF.
1. Create an HTTP GET request to obtain web page information:
/// <summary>
/// Specify path to send GET request
/// </ 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. Get the URL of all pictures in HTML:
/// <summary>
/// Get the URL of all pictures in HTML.
/// </ summary>
/// <param name = "url"> HTML code </ param>
/// <returns> Image URL list </ returns>
public static string HtmlCodeRequest (string url)
{
if (string.IsNullOrEmpty (url))
{
throw new ArgumentNullException (url);
}
try
{
// Create a request
var httprequst = (HttpWebRequest) WebRequest.Create (url);
// Do not establish persistent links
httprequst.KeepAlive = true;
// Set the request method
httprequst.Method = "GET";
// Set header value
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;
// Allow 302
httprequst.AllowAutoRedirect = true;
ServicePointManager.DefaultConnectionLimit = 30;
// Get response
var webRes = (HttpWebResponse) httprequst.GetResponse ();
// Get the response text stream
string content;
using (var stream = webRes.GetResponseStream ())
{
using (var reader = new StreamReader (stream, Encoding.GetEncoding ("utf-8"))))
{
content = reader.ReadToEnd ();
}
}
// Cancel the request
httprequst.Abort ();
// Return data content
return content;
}
catch (Exception ex)
{
throw new Exception (ex.Message);
}
}
3. Create a PDF document:
PdfDocument doc = new PdfDocument ();
doc.LoadFromHTML (url, false, true, true);
doc.Close ();
The above does not assemble the operation into a method. Since the creation operation is relatively simple, it will not be described in detail. The url is the path address of the web page.
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 to 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. Convert XPS to 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. Convert Image to 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");
}
The above provides an HTTP request to the website, access to the website page information, and the use of Spire.PDF components to create PDF documents. If necessary, you can directly load the information obtained by the HTTP request into components such as Spire.PDF,
The component directly converts the web page information into a PDF file, so I won't go into more details here. Since the official provides a very complete demo and operation documentation, I won't introduce too much usage here.
4. Summary:
The above introduces a component that is not open source for a fee. There is no more in-depth introduction. Since the component is not open source, it cannot be decompiled. After all, there are copyright issues. If you need to use enterprise-level document operation components, and the company does not lack For money, you can use this component, the underlying method of the component is highly encapsulated, so when using it, developers need to consider how to use the component to complete the function.
Personally think that software charges should be the trend, after all, any software requires investment, whether it is labor costs, or capital and time costs. Although this article is an article that introduces technology, it also raises a question that all developers are thinking about. In the end of the project, do you need to use paid software? In fact, this depends on the use environment.