Quantcast
Channel: ByteScout
Viewing all 325 articles
Browse latest View live

Updated Software: ByteScout Barcode Generator SDK 4.41.0.867, Barcode Reader SDK 8.50.0.1548, Spreadsheet SDK 2.60.1545, Barcode Reader Freeware 8.50.0.1548, Barcode Generator freeware 4.41.0.867

$
0
0
spreadsheetsdk_screenshot

ByteScout Spreadsheet SDK screenshot

ByteScout updated

  1. ByteScout Barcode Generator SDK 4.41.0.867
  2. ByteScout Barcode Generator freeware 4.41.0.867
  3. ByteScout Barcode Reader SDK 8.50.0.1548
  4. ByteScout Barcode Reader Freeware 8.50.0.1548
  5. ByteScout Spreadsheet SDK 2.60.1545

on June 16, 2016.

Whats’s new:

Barcode Generator SDK 4.41.867

  • minor improvements and bug fixes

Barcode Generator freeware 4.41.867

  • minor improvements and bug fixes

Barcode Reader SDK 8.50.0.1548

  • improved Code 39 edge tracking
  • improved decoding of distorted Code 39 and Code 128 barcodes
  • improved handling of PDF files
  • demo application UI improvements
  • added override for Reader.ReadFrom() method allowing to specify the page rangle
  • fixed page range bug in Reader.ReadFromPdfFilePage() method
  • other minor improvements and bug fixes

Barcode Reader Freeware 8.50.0.1548

  • improved Code 39 edge tracking
  • improved decoding of distorted Code 39 and Code 128 barcodes
  • improved handling of PDF files
  • UI improvements
  • other minor improvements and bug fixes

Spreadsheet SDK 2.60.1545

  • fixed custom date format processing
  • fixed calculation of ROW and COLUMN functions
  • other minor improvements and bug fixes

The post Updated Software: ByteScout Barcode Generator SDK 4.41.0.867, Barcode Reader SDK 8.50.0.1548, Spreadsheet SDK 2.60.1545, Barcode Reader Freeware 8.50.0.1548, Barcode Generator freeware 4.41.0.867 appeared first on ByteScout.


Updated Software: ByteScout PDF SDK 1.3.0.120

$
0
0

ByteScout updated PDF SDK 1.3.0.120 software on July 7, 2016.

Whats’s new:ByteScout PDF SDK screenshot

  • implemented signing with digital signature
  • added “Bytescout.PDF.Converters” add-on (requires .NET 4.5 or later); implementing DOCX to HTML, HTML to PDF and DOCX to PDF conversion
  • made assembly CLS compliant
  • fixed Page.Watermarks collection visibility in ActiveX/COM.

The post Updated Software: ByteScout PDF SDK 1.3.0.120 appeared first on ByteScout.

JavaScript vs CoffeeScript vs TypeScript

$
0
0

JavaScript

 JavaScript is  a dynamic, advanced level interpreted programming language. It is one of the three core technologies of World Wide Web alongside HTML and CSS. The majority of websites employ it and it is supported by all modern Web browsers. JavaScript is prototype-based with first-class functions, making it a multi-purpose tool, supporting functional and object-oriented programming styles. It includes an API for working with arrays, expressions and texts, but does not have any I/O support, like storage, media, networking and graphics facilities. For these it has to rely on the host environment but there are frameworks like Node.js to leverage all advantage of javascript.

JavaScript is also used in applications that are not entirely web-based, like desktop widgets, website-specific browsers and PDF documents. It also plays an important part in game development, desktop/mobile applications, and server-side network programming.

JavaScript development has got even better with the advent of various new frameworks. For server-side web development one can use a multitude of languages and frameworks, but for client-side programming JavaScript is the sole option as it is supported by all browsers. To overcome this problem, newer languages were developed that can compile down to JavaScript. These new languages offer new concepts and improved syntax while hiding the complex bits of the JavaScript. They can offer good ways to write and manage large code, while automatically generating more ‘correct’ JavaScript as an alternative.

Why Javascript is so popular on server-side too? Because, thanks to Google, it can be run by ultra fast ES6 compiler that provides high speed comparing to other interpreted languages like Ruby, Python.

Coffeescript 

Coffescript is one of these languages, and a popular one. Its syntax is kind of similar to JavaScript, but has a lot of changes for the sake of cleaner, more concise code. It’s comparatively easy to read, and becomes more easy to learn after some good effort.

Coffeescript is a clean little language type that nicely compiles into the JavaScript. Underneath those lame complex ‘braces and semicolons’ composed structure, JavaScript has always had a classic object model at its heart. Coffeescript is an attempt to expose the good and bad parts of the JavaScript in a simple easier way.

The classic rule of Coffeescript is: ‘It’s just a plain JavaScript’. The Coffeescript code compiles one by one into the equivalent JavaScript, and there is no interpretation at the runtime. The final compiled output is readable and nicely printed, passes through JavaScript without warnings, will work in every other JavaScript application or usage, and aims to run as fast or much faster than the plain equivalent handwritten JavaScript.

Aside from syntax, there are also some other features and improvisations in the Coffeescript. Like variable scoping is improved, there’s no need to actually declare variables, just use desired variables and they are declared for you in the output. 

Typescript

Typescript is a newer contender, developed by Microsoft and made to have first class citizen support in Visual Studio including Intelligence and on-the-fly compiler errors. TypeScript differs from Coffeescript in a way that it’s just a complete superset of JavaScript. All JavaScript code is totally valid TypeScript code.

TypeScript provides lot of help for generating better JavaScript, such as a natural syntax for defining classes. TypeScript has one major benefit which is the optional support for static type checking, which makes it a lot easier to interface with the external JavaScript libraries either without type checking or with a typed interface definition that you create.

TypeScript integrates well with all the existing JavaScript code and it’s easy to understand even if u know a little bit of JavaScript and C. Another point why to choose TypeScript is that someday today’s TypeScript will be standard JavaScript and therefore run in the browser.

TypeScript allows you to create today’s web applications with language features of tomorrow. TypeScript is the only one that is a very strict superset of JavaScript.  This means that any type of valid JavaScript code is also good for TypeScript, and surely compatible with existing libraries without any problem.

This nice compatibility, however, has some issues as well.  As a superset, TypeScript cannot make up for any of the JavaScript’s ugly complex sides.  So, all the pitfalls of the JavaScript are there lurking, waiting for you to make a mistake. In the TypeScript the static typing and Visual Studio plugins do a lot to alleviate these problems, though.

TypeScript usually supports all the definition files that contain method information of existing JavaScript libraries, much like C/C++ header files that explain the structures of previous object files. This enables other programs to use all the values defined in the files as if they were TypeScript entities which are statically typed.

TypeScript is obviously a forward step at what JavaScript may be in a few years’ time.  The addition of, classes, modules, a type system and an IDE that takes full use of these features makes it a very tempting choice over plain JavaScript.

Overall, TypeScript is relatively much closer to JavaScript than Coffeescript, making it easier to learn as well as the generated output is closer to the input in its case.

Coffeescript or Typescript?

There’s a good case for both of them, and if someone didn’t mind the odd maintenance and mental torture, he could actually use both of them on the same project. Since both compile to JavaScript, one can easily use any code written in the other language.

Following are some recommendations:

  1. For static type checking and a good tool chain support on Visual Studio, TypeScript is the option.
  2. For a quick and short learning curve from JavaScript or a need to add legacy code (which isn’t common since it can easily be used as old JavaScript without modification), choose TypeScript.
  3. If someone wants more concise, cleaner code and lots of syntactic sugar, choose Coffeescript.
  4. If coming from Ruby or Python, Coffeescript is likely to be a good option, as it’s a closer mental match.

Summary

Coffeescript:

  • Small, clear language with lots of code examples.
  • Effective after learning the basics.
  • Good working tools provided.

TypeScript:

  • Developed by Microsoft (yes, some of developers may consider this as disadvantage)
  • Each part of JavaScript code is valid TypeScript and therefore it integrates much better than the other languages.
  • Compatible with next-gen JavaScript standards.
  • Compiled JavaScript runs on server (node.js).
  • Similar syntax as in C/C++.

The post JavaScript vs CoffeeScript vs TypeScript appeared first on ByteScout.

Javascript tutorial: How to add a button that shows Modal window message using JQuery and Bootsrap

$
0
0

Introduction

Modal windows in Bootstrap are nothing but simple dialogue boxes that are used for displaying important information to the visitors. Modal windows typically contain special offers, login box, session timeout warnings etc. Modal windows are also used to get input from the user. For instance, modal windows can contain sign up forms, purchase order or feedback forms for customers.

Before, bootstrap based Modals were developed by conjunction of complex HTML and Javascript/JQuery code. However, with Bootstrap framework, the process of creating modal window has become extremely seamless and straight forward. Though, in the backend, Bootstrap uses JQuery for displaying modal windows but the complexities of the code are hidden from the developer.

Sample Modal Dialog

Let’s take our first Example of developing a Modal using Bootstrap. Let’s look at the index.html page which contains a button. When the button is clicked, a modal window is populated containing a header, some messages and footer. The code of the index.html page is as follows:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->

<title>Bootsrap Modal Window</title>

<!-- Bootstrap core CSS -->

<link href="css/bootstrap.min.css" rel="stylesheet">

<!-- Custom styles for this template -->

<link href="css/style.css" rel="stylesheet">

</head>

<body>


<div class= "text-center">

<!—HTML Button -->

<a href="#BootstrapModal" role="button" class="btn btn-large btn-primary" data-toggle="modal">Open Bootsrap Modal</a>

</div>




<!-- Modal HTML -->


<div id="BootstrapModal" class="modal fade">


<div class="modal-dialog">


<div class="modal-content">


<div class="modal-header">

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>


<h4 class="modal-title">This is a sample Modal</h4>


</div>



<div class="modal-body">



Do you understand how this Modal works? If not see, the code.




<small>Keep practicing, you will learn how to create this</small>


</div>



<div class="modal-footer">

<button type="button" class="btn btn-success" data-dismiss="modal">Okay, I Understand</button>

<button type="button" class="btn btn-warning">Take me to code</button>

</div>


</div>


</div>


</div>




<!-- Bootstrap core JavaScript ================================================== -->

<!-- Placed at the end of the document so the pages load faster -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>

<script src="js/bootstrap.min.js"></script>

<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->

<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>

</body>

</html>

You can see in the above code that we are referring to Bootsrap CSS in the header section. Also at the end of the Body section we are referring to JQuery and JavaScript libraries as well. However, our main focus is on the HTML Button and Modal HTML section as mentioned in the comments.

The HTML button that is actually a link but using Bootsrap classes we have made it look like a button of large size and its outlook will be similar to a primary button of dark blue color. It can be seen that the HTML link contains two attributes i.e data-toggle with value “modal” and href attribute with value “#BootstrapModal”. The former attributes states that this link is used to open a modal window while the later attribute specified that the id of the modal which will be open when the link is clicked should be “BootstrapModal”. In case of button the data-target attribute refers to the id of the modal to be opened.

Now if you look at the code of the Modal, you should see that it has a unique id of “BootstrapModal”. This is necessary since the controller which is a link in this case targets this id. The modal-dialog class is used to set the width and height of the modal window while modal-content class sets the styles associated with the modal. The output of the aforementioned code will be a button centered at the top of the page and when this button is clicked a modal window shall appear as shown in the following figure.

 

Sample modal dialog window displayed with two buttons

Sample modal dialog window displayed with two buttons

You can see a cross button at the top right corner of the modal. If you remove the following line from your modal code, this cross shall disappear.

</pre>
<pre><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button></pre>
<pre>

Furthermore, you can see classes like modal-header, modal-body, and modal-footer which are used for creating header, body and footer sections of the modal window.

Changing Size of the Modal

The size of the modal can be changed by using modal-lg and modal-sm classes in conjunction with the modal-dialog class. The following line of code shall decrease the size of the modal.

</pre>
<pre><div class="modal-dialog modal-sm"></pre>
<pre>

The corresponding modal will look like the one shown below:

pic2

 

Similarly, if the following line is added in the code:

</pre>
<pre><div class="modal-dialog modal-lg"></pre>
<pre>

it will result in large modal box as shown in the following figure:

Modal window dialog with changed size

Modal window dialog with changed size

Outro

Bootstrap is a powerful library for front end software development. This article bears witness to the amazing power of bootstrap. We saw how simple it is to create a complex modal window via bootstrap. For more interesting articles, keep visiting our blog.

The post Javascript tutorial: How to add a button that shows Modal window message using JQuery and Bootsrap appeared first on ByteScout.

Updated Software: ByteScout Barcode Generator SDK 4.50.0.875, Barcode Reader SDK 8.60.0.1561, Barcode Reader Freeware 8.60.0.1561, Barcode Generator freeware 4.50.0.875

$
0
0

 

Barcodereader_SDK_Screenshot

Bytescout Barcodereader SDK Screenshot

ByteScout updated

  1. ByteScout Barcode Generator SDK 4.50.0.875
  2. ByteScout Barcode Generator freeware 4.50.0.875
  3. ByteScout Barcode Reader SDK 8.60.0.1561
  4. ByteScout Barcode Reader Freeware 8.60.0.1561

on August 15, 2016.

Whats’s new:

Barcode Generator SDK 4.50.0.875

  • fixed ProduceMonochromeImages property. It now affects all barcode generation routines and creates real
  • monochrome images compatible with professional color separation software
  • improved PDF files handling
  • minor improvements and bug fixes.

Barcode Generator freeware 4.50.0.875

  • minor improvements and bug fixes

Barcode Reader SDK 8.60.0.1561

  • demo Application: Added page navigation controls for multi-page TIFF files
  • improved PDF417 decoding
  • improved PDF documents rendering
  • other minor improvements and bug fixes

Barcode Reader Freeware 8.60.0.1561

  • added page navigation controls for multi-page TIFF files
  • improved PDF417 decoding
  • improved PDF documents rendering
  • other minor improvements and bug fixes

The post Updated Software: ByteScout Barcode Generator SDK 4.50.0.875, Barcode Reader SDK 8.60.0.1561, Barcode Reader Freeware 8.60.0.1561, Barcode Generator freeware 4.50.0.875 appeared first on ByteScout.

Updated software: ByteScout Spreadsheet SDK 2.70.1553

Updated software: PDF To HTML SDK 8.0.0.2523, PDF Multitool 8.0.0.2523, PDF Viewer SDK 8.0.0.2523, PDF SDK 1.3.5.126, PDF Renderer SDK 8.0.0.2523, PDF Extractor SDK 8.0.0.2523

$
0
0

pdf_to_html_sdk-screenshotByteScout updated software on August 19, 2016:

  1. ByteScout PDF To HTML SDK 8.0.0.2523
  2. ByteScout PDF Multitool 8.0.0.2523
  3. ByteScout PDF Viewer SDK 8.0.0.2523
  4. ByteScout PDF SDK 1.3.5.126
  5. ByteScout PDF Renderer SDK 8.0.0.2523
  6. ByteScout PDF Extractor SDK 8.0.0.2523

What’s new:

ByteScout PDF To HTML SDK 8.0.0.2523

  • improved text extraction
  • improved performance
  • fixed PDF parsing issues
  • fixed JBIG images decoding
  • other minor improvements and bug fixes

ByteScout PDF Multitool 8.0.0.2523

  • updated OCR engine to the latest version
  • fixed PDF parsing issues
  • fixed fonts rendering issues
  • fixed JBIG images decoding
  • other minor improvements and bug fixes

ByteScout PDF Viewer SDK 8.0.0.2523

  • minor performance improvements
  • fixed PDF parsing issues
  • fixed fonts rendering issues
  • fixed JBIG images decoding
  • other minor improvements and bug fixes

ByteScout PDF SDK 1.3.5.126

  • added Canvas.MeasureString() method allowing to measure dimensions of a text string
  • table class: Added padding to cells to butify PDF tables
  • other minor bug fixes and improvements

ByteScout PDF Renderer SDK 8.0.0.2523

  • changed API of RasterRenderer and VectorRenderer classes
  • minor performance improvements
  • fixed PDF parsing issues
  • fixed fonts rendering issues
  • fixed JBIG images decoding
  • fixed arithmetic overflow on image transformations
  • other minor improvements and bug fixes

ByteScout PDF Extractor SDK 8.0.0.2523

  • added filtering of extracted content by font name, font size and color
  • updated OCR engine to the latest version. Update language files from “tessdata” folder
  • improved text extraction
  • improved lines grouping in tabular data
  • improved performance
  • improved XFA forms extraction
  • improved TableDetector
  • fixed PDF parsing issues
  • fixed JBIG images decoding
  • imageExtractor: fixed per-page image extraction
  • multimediaExtractor: fixed extraction on embedded MPEG audio
  • TextExtractor: fixed non-working RemoveHyphenation property
  • other minor improvements and bug fixes.

The post Updated software: PDF To HTML SDK 8.0.0.2523, PDF Multitool 8.0.0.2523, PDF Viewer SDK 8.0.0.2523, PDF SDK 1.3.5.126, PDF Renderer SDK 8.0.0.2523, PDF Extractor SDK 8.0.0.2523 appeared first on ByteScout.

Updated software: ByteScout Bitmap Visualizer 1.0.4.105


Bytescout released new versions of major products

$
0
0

Bytescout PDF Extractor SDK 8.1.0.2600

  • New OCR processing filters were added in order to make the recognition quality better, especially on bad-quality scanned documents.
  • DocumentOptimizer class was added, it is able to recompress all images in the documents with JPEG or CCITT compression.
  • New filters to remove were added.
  • Any kind of extraction class (TextExtractor, XMLExtractor, etc.) is now capable to load image files and also extract some text with OCR help.
  • A demo app for PDF Multitool can now load images and extract the text with OCR.
  • Extraction of Korean charset is not fixed (KSCms-UHC-H / Code Page 949).
  • Extraction from a specific rectangular area is now fixed.
  • Invisible text extraction is fixed.
  • Representation of transparent color in XML extraction is fixed.
  • Other improvements and bugs are fixed.

ByteScout PDF Renderer SDK 8.1.0.2600

  • PDF parsing issues are now fixed.
  • Support of colorspaces and soft masks.
  • More bugs and improvements are now fixed.

ByteScout PDF SDK 1.3.6.149

  • Canvas.DrawString() bug eating spaces are improved.
  • URL input parameter is now supported by HtmlToPdfConverter.
  • Minor issues are fixed.

ByteScout PDF To HTML SDK 8.1.0.2600

  • Korean charset (KSCms-UHC-H / Code Page 949) extraction is fixed.
  • Invisible text extraction is improved.
  • Colorspaces support and soft masks are now fixed.
  • Other minor improvements and bug fixes.

ByteScout PDF Viewer SDK 8.1.0.2600

  • Color spaces and soft masks support are improved.
  • Image files display control is now fixed.
  • Extraction of text and search in Korean charset (KSCms-UHC-H / Code Page 949) are fixed.
  • Minor fixes and bugs improvements.

Barcode Reader SDK 8.70.0.1587

  • 144×144 DataMatrix barcodes alternative error correction mode is now added.
  • Malformed code 128 barcodes decoding is now improved.
  • Merged QR Codes support is added.
  • Check boxes recognition is fixed.
  • Minor issues improved and bug fixed.

Barcode Generator SDK 4.55.0.903

  • Added alternative error correction mode for 144×144 DataMatrix barcodes for compatibility with some readers.
  • DrawImagesToPDF() methods were overwriting user provided images. Fixed now.
  • Minor improvements and bug fixes.

ByteScout PDF Multitool 8.1.0.2600

  • Added OCR preprocessing filters to improve the recognition quality on low-quality scanned documents.
  • Now the app is able to load image files and extract text from them using OCR.
  • Fixed extraction of text in Korean charset (KSCms-UHC-H / Code Page 949).
  • Improved support of colorspaces and soft masks.
  • Improved text extraction from specified rectangular area.
  • Fixed transparent color representation in XML extraction.
  • Other minor improvements and bug fixes.

Spreadsheet SDK 2.75.1568

  • Malformed XLS files is improved.
  • ODS files loading bugs are now fixed.
  • Other minor improvements and bug fixes.

Barcode Generator freeware 4.55.0.903

  • Alternative error correction mode for 144×144 DataMatrix barcodes is now added, valid for compatibility with some readers.
  • Minor improvements and bug fixes.

Barcode Reader Freeware 8.70.0.1587

  • Error correction mode is added for 144×144 DataMatrix barcodes.
  • Merged QR Codes are improved.
  • Improved check boxes recognition.
  • Other minor improvements and bug fixes.

Bytescout Screen Capturing SDK 2.53.1038

  • Runtime WEBM codecs files for C++ are added.
  • Detection of desktop dimensions during the full-screen capturing mode is improved.
  • Web camera overlay handling is improved that helps to avoid black recording.
  • Other fixes and improvements.

ByteScout SWF To Video SDK 2.13.1038

  • WEBM codecs C++ runtime files are added.
  • The background image is now stretched by default.
  • Minor bug-fixes and improvements.

ByteScout Image To Video SDK 2.12.1038

  • KeepAspectRatio property does not influence the background image.
  • Added C++ runtime files necessary for WEBM codecs.
  • Other improvements and bug fixes.

The post Bytescout released new versions of major products appeared first on ByteScout.

WHY QR CODE IS THE GREAT CHOICE FOR YOUR DOCUMENTS?

$
0
0

Barcodes have become very common in today’s world. You see a barcode on almost everything you come across nowadays. You see them on consumable goods, gift cards, labels and everywhere in supermarkets. There is no denying of the fact that traditional pricing system has effectively given way to the barcodes.

Almost all types of businesses across the globe are making most of the barcode technology. For example, it is used to identify employees in a warehouse, keep track of company’s vehicles and their drivers or to track assets such as tables, desks, computers, air conditioners or telephones in any building. Barcodes are very easy to use as well. In fact, every sane individual can gather information from a barcode if he knows how to use a scanning device.

QR Codes for Documents Sharing:

QR codes are one of the many types of barcodes. There are many benefits of using QR codes for your business. However, very few people are aware of the fact that QR codes are extremely useful when it comes to sharing your documents. Be it is your office documents, medical records, business inventory record, invoices or freight records, QR codes can make them more secure and safe.

QR codes are not only super accurate but cost and time effective as well. There are many ways you can use QR codes for data capture in documents.

  • Bookmarking/Splitting:

Many barcode scanners can search for QR codes in data. As soon as they find a common or new barcode, they create a new document for that barcode. As a result, you can virtually scan thousands of documents containing things like invoice numbers, repair orders, patient records or any kind of classifications in one go.

You can also use barcodes information to insert PDF bookmarks. It is pertinent to note that the process will not divide your file as it will remain as 1 file. On the other hand, the output PDF file will have different bookmarks to make navigation easier for you.

  • Classifying:

You can also identify the type of document being processed using QR codes. Similarly, you can use them to appropriate process depending upon the type of the document. Some advanced systems will choose the subsequent procedures after scanning contents of the QR codes.

  • Routing:

QR codes can also help users determine the route or path of the scanned documents in their files system. The system reads the barcode content of the scanned document sets and automatically creates folders and subfolders.

  • Indexing:

QR codes are also commonly used for indexing information or storing metadata. You can extract the barcode data and send it along the associated scanned image to a document management system. The typical example is the medical records where this data exists in the forms of patient name or patient id etc.

  • Naming:

You can also take help of QR codes in combination with other document variables to name different output files you have created for scanned documents.

Why QR Code is better than Code 39?

QR code belongs to the latest 2 Dimensional (2D) series of barcodes. They use two-dimensional shapes and figures to store information. QR codes are much better than other types of barcodes such as Code 39 and Code 128. Following are some main differences between QR Codes and traditional barcodes.

  • Capacity and Type of Data:

Almost all the scanning devices and software support QR codes. They cover a wide range of things and can be quite useful for you. They can handle a tremendous amount of information which traditional barcodes such as Code 128 or Code 39 simply cannot. They are high capacity barcodes and you can insert a wide variety of data into them. They can hold up to several dozen letters and numbers. On the other hand, traditional codes can hold up to just 20 letters and numbers.

  • QR Codes are Compact:

It is pertinent to note that Code 128 or 39 require a lot of space to store a small amount of data. On the hand, QR codes consume very small space to store huge amount of data. QR codes are compact and very easier to scan.

  • Language Capability:

Unlike traditional codes, QR barcodes can read data in many different languages. The data needs not to be only English numbers or letters. Even if the data is in a different language, QR codes work smoothly and don’t create problems for the users.

  • Error Correction:

Obviously, error correction capabilities are limited in Code 128, Code 39 and other traditional barcodes. As a matter of fact, Code 39 does not have any error checking and correction ability at all. Therefore, the code becomes unusable once it has been damaged due to any reason. On the contrary, QR codes can restore almost all data if they are damaged. The scanner can still read the data even if the code is damaged. 

  • Reading Direction:

You can scan QR codes in any direction you want as compared to traditional barcodes which can be read only in one direction. You don’t need to align both code and scanner vertically to scan the code as in the case of Code 128 or Code 39. This feature actually makes QR codes super useful for all types of businesses, products, and documents.

  • Information Classification:

QR codes can further classify information contained in them in specific areas within the code. This makes it easier for the user to only read the required information. He can either read the information on one side or information stored on the other side. Traditional barcodes simply lack this excellent feature.

  • Software Support:

QR codes belong to the latest 2D technology of barcodes. Therefore, almost all of the scanning software and devices support them. You can scale them easily using any software or device available to you. On the other hand, Code 128 and Code 39 are slowly becoming obsolete. This simply means that modern software and devices will not scan them, making them virtually useless.

The advent of QR codes is just one example of how rapidly the technology is advancing. QR codes have totally revolutionized the business world. They provide a safer, advanced, reliable and quick option to store your important data and protect it from miscreants.

The post WHY QR CODE IS THE GREAT CHOICE FOR YOUR DOCUMENTS? appeared first on ByteScout.

How The Resolution (DPI, Dots Per Inch) Affects Images And Video

$
0
0

The use of some terms in digital imaging has become a matter of great confusion for many people. It is really a cumbersome task for a layman to differentiate between Dots per Inch (DPI) and Pixels per Image (PPI). Well, both DPI and PPI are the measure of resolution for both onscreen and print images. It is pertinent to note that DPI is relatively an old term. People have been using this very term to relate everything about the digital images and their size and resolution before the appearance of PPI in recent years. Currently, PPI is most commonly used to manage resolution and size of digital images yet DPI is still used for some software and documents.

The following lines explain what Dots per Inch (DPI) means and how it affects the resolution of your image.

Dots per Inch (DPI) Image Resolution:

The DPI specifically refers to the printers. In some words, it is only used in printers nowadays. Everyone should be aware that all the printers consist of different colored inks which combine to create every single pixel output. There are usually 4-6 differently colored inks in a printer. The printer works on the principle of mixing all these colors to create an image.

The printer has to mix the inks because of a small number of colors available to it. It has to create an image using only these 4-6 colors. Actually, a series of tiny dots create each pixel of an image. You can consider these tiny dots as sub pixels. It is important to note that the tonality of the printer will be higher if there are more dots per inch in an image. That is higher the DPI, better will be the quality of the image.

Colors in the image will also look better if the DPI is higher. Most importantly, the colors will blend with each other naturally and smoothly. There is also a reverse side of using high DPI. That is the printing job will be slower and the printer will use more ink. In order to overcome this problem, you must try to lower the DPI setting without distorting the image. The lowest DPI setting which does not reduce the image quality is the one you should be using.

Dots per Image (DPI) and the Video Quality:

Against common perception, DPI has nothing to do with the video quality. Almost all the modern video formats, as well as rasterized images, store their data solely as pixels. The do not depend upon DPI or real world measurements such as inches for their quality. On the other hand, monitors also display video only in units of pixels. If you are displaying a video or rasterized image, the monitor maps them pixels by pixels instead of dots per inch.

You may have to use DPI in videos and rasterized images when you want to map real pixels into real word measurements. For example, 20 points are roughly 0.28 inches. Therefore, a 20 point Font will use dots per image settings to determine how many pixels it should use.

Why 400 DPI Screen is Better than 120 DPI Screen?

You might be surprised to learn that most pros recommend using 300-400 DPI resolution for digital images. This raises a very important question. Why not use higher 1000 or 2000 DPI for an image or for that matter, lower 120 DPI? Is there a threshold for lower and higher image resolution beyond which you should not venture.

It is also pertinent to note that an image with 72 DPI might look amazing on your computer screen. However, you may be shocked to test the image on your 720 HDTV. Although, 400 DPI is always better than 120 DPI, the actual image resolution you want to use depends upon the type of image and your requirements.

For instance, most old photo labs would develop your photos using only 300 DPI physically. As a matter of fact, 300-400 DPI is still good enough for most of the photos. For example, if you scan an old photo at 300 DPI, you are very likely to get an exact copy of your photo. On the contrary, if you scan it using 600, 900 or higher DPI, it will distort your photo instead to provide you with more details. 300 DPI is the limit for such photos and you should not go higher or lower.

Again, the quality of the image depends upon the device on which you are viewing your image. You might totally distort your image if you want to get the bigger print of your 300 DPI photo. This is where you must scan your image at higher DPI. It will help you retain the image quality without stretching the image.

DPI and the Physical Size of the Image:

The DPI can also have an effect on the physical size of the image. You might have to increase or decrease the DPI in order to set the image to the default size of the printer you are using to print the image. For example, the DPI of the photo should be 400 if the default print dimension is 5 inch and you want to set the image width to 2000 pixels. The formula is simply. You will divide 2000 with 5 to get 400 DPI.

You should try not to resample or resize your image while changing its DPI. It is advisable to retain the original pixel dimensions while changing your DPI. These pixels normally determine the real digital resolution of an image. This way, you will be able to retain the size and resolution of the original image without distorting its quality. The only thing you will be changing is its inner dots per inch (DPI) dimensions.

There are many programs such as Photoshop and Illustrator which help you change the DPI without disturbing the physical size of the image. The only thing you need to keep in mind is that you should never resample or resize your image while changing the DPI. Your new photo will be the carbon copy of the original as long as its pixels remain unchanged.

 

The post How The Resolution (DPI, Dots Per Inch) Affects Images And Video appeared first on ByteScout.

Introduction to Bootstrap

$
0
0

This step by step tutorial shows how to learn bootstrap quickly and how to integrate the Bootstrap framework into an existing website. We’ll start with one of the default website templates in visual studio community 2015. We’ll then integrate some Bootstrap layout examples into it. At the end of this tutorial, the reader will know the Bootstrap’s fundamentals and should be able to use it in his work.

The tutorial will be divided into 7 sections:

Section 1. Why should we choose Bootstrap

Choosing a framework is often crucial for the developer. “Why do I will choose this one instead of that another one, both of them seems to do the same thing”. You’re totally right and here are some keys that you should know about Bootstrap.

  • Bootstrap is the most popular framework for building modern responsive app (mobile included).

  • There is a large support over the Bootstrap’s web community, the official website (http://getbootstrap.com/) offers a lot of information on the framework and it is a well documented project.

  • Bootstrap is an extensible framework, it comes with two parts: the css and the javascript parts. The css part can be customized to suit our needs or just kept as is. Since Bootstrap uses the well known Jquery core framework, the javascript part allows the developer to use javascript. Similarly to Jquery UI’s plugins, a lot of Bootstrap’s components (official or third party) are available for free and are most often ready to use.

  • Bootstrap is also built over Html5 and Css3. It is compatible with almost browsers in the market including mobile devices and tablets.

Section 2. Initializing the solution

For the sake and simplicity, we will start with the default website generated by visual studio Community 2015.

From Menu File > New > Web Site

In the left pane, select Installed > Templates > Visual C#

In the middle pane, select .NET Framework 4.5 and the choose “Asp.NET Web Site (Razor v3)”, give a name to the new website and finally click “Ok” to create it.

The website solution looks like

introbootstrap_scr_1

The most relevant components in this tutorial are:

– the Content folder is all about css files

– the Scripts folder contains all javascript files

_SiteLayout.cshtml file is the common layout (the master page) of all web pages.

The website contains three main pages: Default.cshtml, Contact.cshtml, About.cshtml and each of them are referenced in the website menu.

introbootstrap_scr_2

Section 3: How to add Bootstrap to a website

The minimal requirement to use bootstrap on our site is to add the bootstrap stylesheet and javascript to our solution. At the time of writing, the stable version is v3.3.7 and it can be downloaded at https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css

Tips: Instead of downloading the full file, some developers prefer to make a direct link to Bootstrap CDN server. Both two methods are working, just consider the case the internet connection falls down and external references can’t be reached. In this tutorial we will use the minified version.

Let’s now examine the actual main layout file _SiteLayout.cshtml

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>@Page.Title – My ASP.NET Web Page</title>
<link href=”~/Content/themes/base/jquery.ui.all.css” rel=”stylesheet” type=”text/css” />
<link href=”~/Content/Site.css” rel=”stylesheet” type=”text/css” />
<link href=”~/favicon.ico” rel=”shortcut icon” type=”image/x-icon” />

<script src=”~/Scripts/jquery-1.10.2.min.js”></script>
<script src=”~/Scripts/jquery-ui-1.10.3.js”></script>
<script src=”~/Scripts/modernizr-2.6.2.js”></script>
<meta name=”viewport” content=”width=device-width” />
</head>

Since we want Bootstrap to manage styles and also need to ensure the responsiveness of our website, we remove the jquery.ui.all.css definitely.

The file Site.css contains customized style. At this stage, we also remove it to let Bootstrap the only style manager.

After adding the Bootstrap components, the updated part looks like

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<title>@Page.Title – My ASP.NET Web Page</title>
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css” />
<link href=”~/favicon.ico” rel=”shortcut icon” type=”image/x-icon” />
<script src=”~/Scripts/jquery-1.10.2.min.js”></script>
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js”></script>
<script src=”~/Scripts/modernizr-2.6.2.js”></script>
<meta name=”viewport” content=”width=device-width” />
</head>

introbootstrap_scr_3

The content is now in disorder, this is normal because we hadn’t configure anything yet. We will apply Bootstrap’s layout as we go along this tutorial.

Note: the second meta element (<meta http-equiv="X-UA-Compatible" content="IE=edge">) ensures the compatibility with IE Edge browser.

Before continuing, let’s talk about some fundamental keys on Bootstrap.

Section 4: Bootstrap fundamental

Key 0: Bootstrap container

A container is like a “big box” inside which we put multiple “small boxes”. In Bootstrap language, container is just all div having the css class “container”. There’s actually two type of css container class: “container” and “container-fluid”

The only difference is that the second takes all of the viewport’s width. Viewport is the all surface where an html page is displayed.

Tips: To make your work easy, it is strongly recommended to avoid nested container.

Key 1: The Boostrap grid system

Bootstrap classifies devices into 4 groups according to their width.

– Extra small devices (< 768px)

– Small devices tablets (>=768px)

– Medium devices (>=992px)

– Large devices (>=1200px)

The display may vary depending on the device width and Bootstrap will automatically adapt the website layout following that parameter. This is what we called responsiveness.

Key 2: Bootstrap row css class

An element (generally a div) having the special “row” css class will take 100% of its container’s width. Think the container as an html table, a row always takes 100% of the table’s width.

Key 3: Bootstrap column css class

Column is a subdivision of a row and it’s content (any html element) always stands inside a row. In Bootstrap, a row can be splited up to 12 columns. This is well explained by the figure below (from the official bootstrap page).

introbootstrap_scr_4

Css columns have the following naming rules: col-DEVICE_PREFIXNUMBER

where

– DEVICE_PREFIX is the type of the targeted device:

Device type

DEVICE_PREFIX value

Extra small devices

xs

Small devices tablets

sm

Medium devices

md

Large devices

lg

– NUMBER indicates how many column unit the element will take horizontally. This is relative to it’s container. As we’ve said so far, there is 12 possible subdivisions of a row so the number is in the range from 1 to 12.

We can assign multiple columns CSS class to an element provided that all device’s prefix differ from each other. That allows us to give multiple behavior for the same element based on the device type. This is how Bootstrap manages the responsiveness of our website.

To illustrate this point let’s have a look at this code:

<div class=”row” style=”background-color:lightpink;”>

<span id=”span1″ class=”col-xs-10 col-md-8 col-lg-6″ style=”background-color:blue;”>Span 1</span>

<span id=”span2″ class=”col-xs-2 col-md-4 col-lg-6″ style=”background-color:yellow;”>Span 2 2</span>

</div>

On extra small devices, span1 will take 10 columns units ( col-xs-12) and only 2 columns units for span2 ( col-xs-2)

When displaying in a medium device, span1 will stretch to 8 columns units ( col-md-8) against 4 columns units for span2 ( col-md-4)

Span1 and span2 have the same width on a large device since they both are col-lg-6

The illustration below shows the real rendering of the above code on an extra small device

introbootstrap_scr_5

Tips: Note that when the content doesn’t fit over the horizontal space, the container expands his height while remaining inside it’s row container and without overlapping the next container.

With those previous pieces in hands, we’ll build the menu bar of our website.

Section 5: Building the website menu

We will change the old menu to the most famous Bootstrap menu: a fixed navigation bar containing all menus to each respective pages. On a desktop device we want the menu to be fixed at the top of the viewport and showing all available links. On a mobile device, the menu only contains the name of the website at its left side and all the menu items are expanding when tapping the button at the right side.

Actual menu:

introbootstrap_scr_6

Expected result on a desktop:

introbootstrap_scr_7

Expected result  on a mobile device:

introbootstrap_scr_8 introbootstrap_scr_9

Code:

To achieve that goal, we need to copy the following code and insert it just after the body element of the page _SiteLayout.cshtml

<nav class=”navbar navbar-inverse navbar-fixed-top” >

<div class=”container”>

<div class=”navbar-header”>

<a class=”navbar-brand” href=”#”>Your logo here</a>

<button type=”button” class=”navbar-toggle collapsed” data-toggle=”collapse” data-target=”#navbar”>

<span class=”icon-bar”></span>

<span class=”icon-bar”></span>

<span class=”icon-bar”></span>

</button>

</div>

<div class=”collapse navbar-collapse” id=”navbar”>

<ul class=”nav navbar-nav navbar-right”>

<li><a href=”~/”>Home</a></li>

<li><a href=”~/About”>About</a></li>

<li><a href=”~/Contact”>Contact</a></li>

<li><a href=”~/Account/Register”>Register</a></li>

<li><a href=”~/Account/Login”>Log in</a></li>

</ul>

</div>

</div>

</nav>

Comments:

The HTML5 nav element is used as the global container for the navigation bar. It has the following Bootstrap css classes:

navbar: manages the general behavior of the nav component

navbar-inverse: apply a dark background, we can also use navbar-default to have a white background

navbar-fixed-top: the nav element will always stay at the top of the viewport even vertical scrolling happens. An alternative is to use navbar-static-top for a non fixed navbar. Instead of the -top suffix, we can use -bottom, the navbar will be displayed at the bottom of the viewport.

We then declare a div “container” to contain all the navigation bar elements.

The navbar-header ensures that this part of the navigation bar is always visible whatever the device type is.

navbar-brand: the website brand stands inside this css class. It just manages the positioning of the brand as show in the definition below:

.navbar-brand {

float: left;

height: 50px;

padding: 15px 15px;

font-size: 18px;

line-height: 20px;

}

The button element is only visible for extra small and small devices. The navbar-toggle class gives it the float right property, the collapse class tells that the content is hidden by default (always for small device type). The data-target attribute is pointing to the Id of the content that is display when tapping on the button (prefixed with # sign). The button element also contains three spans, it only displays three icon bars inside it.

The main container of the menu elements is the div having id=”navbar”. It is collapsed by default (class collapse) and the navbar-collapse class is mandatory for responsive capabilities (actually this class uses css media queries to display/hide the content depending on the viewport device). We choose an ul element to contain our menu list. The navbar-nav class displays the menu items horizontally and the navbar-right forces them to display on the right ( only visible on the medium and extra large device, if navbar-left is used, they display on the left just after the brand).

We have seen how to implement a typical Bootstrap navigation bar. It only involves few modifications on the main layout page. Before continuing into the next section, copy and past the final code below into the file _SiteLayout.cshtml

*Notice that we’ve included a footer as the same way we did for the top navigation bar.

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”utf-8″ />

<title>New @Page.Title – My ASP.NET Web Page</title>

<link href=”~/favicon.ico” rel=”shortcut icon” type=”image/x-icon” />

<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css” />

<script src=”~/Scripts/jquery-1.10.2.min.js”></script>

<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js”></script>

<script src=”~/Scripts/modernizr-2.6.2.js”></script>

<meta name=”viewport” content=”width=device-width” />

</head>

<body>

<nav class=”navbar navbar-inverse navbar-fixed-top”>

<div class=”container”>

<div class=”navbar-header”>

<a class=”navbar-brand” href=”#”>Your logo here</a>

<button type=”button” class=”navbar-toggle collapsed” data-toggle=”collapse” data-target=”#navbar”>

<span class=”icon-bar”></span>

<span class=”icon-bar”></span>

<span class=”icon-bar”></span>

</button>

</div>

<div class=”collapse navbar-collapse” id=”navbar”>

<ul class=”nav navbar-nav navbar-right”>

<li><a href=”~/”>Home</a></li>

<li><a href=”~/About”>About</a></li>

<li><a href=”~/Contact”>Contact</a></li>

<li><a href=”~/Account/Register”>Register</a></li>

<li><a href=”~/Account/Login”>Log in</a></li>

</ul>

</div>

</div>

</nav>

<div id=”body”>

@RenderSection(“featured”, required: false)

@RenderBody()

</div>

<nav class=”navbar navbar-inverse navbar-fixed-bottom”>

<div class=”container”>

<div class=”navbar-header”>

<p>&copy; @DateTime.Now.Year – My ASP.NET Web Page</p>

</div>

</div>

</nav>

@RenderSection(“Scripts”, required: false)

</body>

</html>

Section 6: Applying Bootstrap layout to the web page body

The actual home page looks like the figure below (after the previous section)

introbootstrap_scr_10

In this step, we will apply some basic layout to the webp age body. As we’ve seen so far, it is always a good practice to use a container for each major part of the website. We will do so by adding the “container” class to the body element (_SiteLayout.cshtml).

<div id=”body” class=”container”>

@RenderSection(“featured”, required: false)

@RenderBody()

</div>

The result is:

introbootstrap_scr_11

The container class adds a padding left and right to the container block, the padding value depends on the viewport width. It also apply a margin property to the block. Bootstrap actually uses css media queries to determine the suitable display for the current device.

Section 7: Applying the Bootstrap grid system

We have talk about the Bootstrap grid system at the section 1. In this section, we’re going to arrange each page content to follow a predefined grid rule. Since we’re expecting a responsive website, we always need to consider how should the content be displayed across devices.

The Default.cshtml file is updated as follow  (modifications are highlighted to simplify reading) 

@{

Layout = “~/_SiteLayout.cshtml”;

Page.Title = “Home Page”;

}

@section featured {

<section class=”featured row“>

<div class=”col-xs-12 col-md-12 col-ld-12“>

<hgroup class=”title”>

<h1>@Page.Title.</h1>

<h2>Modify this template to jump-start your ASP.NET Web Pages application.</h2>

</hgroup>

<p>

To learn more about ASP.NET Web Pages, visit

<a href=”http://asp.net/webpages” title=”ASP.NET Web Pages Website”>http://asp.net/webpages</a>.

The page features <mark>videos, tutorials, and samples</mark> to help you get the most from ASP.NET Web Pages.

If you have any questions about ASP.NET Web Pages, visit

<a href=”http://forums.iis.net/1166.aspx” title=”ASP.NET Web Pages Forum”>our forums</a>.

</p>

</div>

</section>

}

<div class=”row”>

<h3>We suggest the following:</h3>

<ol class=”round”>

<li class=”one col-ld-4 col-md-12 col-xs-12” >

<h5>Getting Started</h5>

ASP.NET Web Pages and the new Razor syntax provide a fast, approachable, and lightweight way to combine server code with HTML

to create dynamic web content. Connect to databases, add video, link to social networking sites, and include many more features

that let you create beautiful sites using the latest web standards.

<a href=”http://go.microsoft.com/fwlink/?LinkId=245139″>Learn more…</a>

</li>

<li class=”two col-ld-4 col-md-6 col-xs-12“>

<h5>Add NuGet packages and jump start your coding</h5>

NuGet makes it easy to install and update free libraries and tools.

<a href=”http://go.microsoft.com/fwlink/?LinkId=245140″>Learn more…</a>

</li>

<li class=”three col-ld-4 col-md-6 col-xs-12“>

<h5>Find Web Hosting</h5>

You can easily find a web hosting company that offers the right mix of features and price for your applications.

<a href=”http://go.microsoft.com/fwlink/?LinkId=245143″>Learn more…</a>

</li>

</ol>

</div>

By adding the “row” class to the section element and creating a new div (also has a row class too) below it, we want those two blocks to be independent each from other. Each part will take the full width of the current viewport and will be displayed vertically in the same order as they are declared inside the DOM tree.

We then control how each part should render on the viewport by using col-xs- (for extra small device – smartphones included), col-md- (medium device – probably any normal desktop screen) and col-ld- ( for very large screen resolution)

As example, we affect the col-md-12 and col-xs-12 class to the first li. It means that when displaying on a medium screen or on a smartphone that li takes 100% of the available width but reduced at only 25% of the total width on an extra large device ( col-ld-4). The second and third li have both a col-md-6 class, each of them will take 50% of their container (remember 12 is 100% width), they will then showed side by side.

Result :

On a medium device, LI region are surrounded by orange rectangle.

introbootstrap_scr_12

On a small device

introbootstrap_scr_13

Tips: For a better user experience, it is advised to always use col-xs-12 for small devices especially when the block content is quite large.

Since the website is responsive, there’s no need to refresh the web page to apply the correct display. When the device’s screen threshold is reached, Bootstrap automatically rearranges the view to satisfy the new design.

The Contact page Contacts.cshtml

The new content is now, changes are highlighted.

@{

Layout = “~/_SiteLayout.cshtml”;

Page.Title = “Contact”;

}

<hgroup class=”title”>

<h1>&nbsp;</h1>

</hgroup>

<hr />

<div class=”row”>

<section class=”contact col-xs-12“>

<header>

<h3>Phone:</h3>

</header>

<p>

<span class=”glyphicon glyphicon-phone-alt” aria-hidden=”true”></span>

<span>425.555.0100</span>

</p>

<p>

<span class=”glyphicon glyphicon glyphicon-phone” aria-hidden=”true”></span>

<span>425.555.0199</span>

</p>

</section>

</div>

<div class=”row”>

<section class=”contact col-xs-12“>

<header>

<h3>Email:</h3>

</header>

<p>

<span >Support:</span>

<span><a href=”mailto:Support@example.com”>Support@example.com</a></span>

</p>

<p>

<span >Marketing:</span>

<span><a href=”mailto:Marketing@example.com”>Marketing@example.com</a></span>

</p>

<p>

<span >General:</span>

<span><a href=”mailto:General@example.com”>General@example.com</a></span>

</p>

</section>

</div>

<div class=”row”>

<section class=”contact col-xs-12“>

<header>

<h3>Address:</h3>

</header>

<p>

One Microsoft Way<br />

Redmond, WA 98052-6399

</p>

</section>

</div>

Result:

On medium and large devices

introbootstrap_scr_14

On mobile device

introbootstrap_scr_15

The modification is quite simple, we just put each section inside a new div container (div having the row class). Each section is configured for extra small devices only(col-xs-12 had been used). In Bootstrap we can target specific devices and totally ignore the rest, the default behavior remains for other devices. Finally we’ve added some Bootstrap icons. As we can see Boostrap is not only limited to the grid system, it can manage all pieces of your website including layout, templates , forms, banner, images, icons, label, animations etc. There’s also a lot of plugins that you can download and use into your website. This is exactly what we well see in the next part of the tutorial.

Section 8. Building forms

With Bootstrap building responsive and pretty web forms was never so easy. Bootstrap comes with a lot of ready-to-use css classes that can be customized at our convenience.
We’ll work on the register page to illustrate the general concept.

Actual Register page ( ~/Account/Register.cshtml)

introbootstrap_scr_16

The most common way to place a pair of label and control components inside a form is shown as following:

<form>
<div class=”form-group“>
<label for=”email”>Email address</label>
<input type=”email” class=”form-control” id=”email” placeholder=”email”>
</div>….

Comments:
form-group: is used by Bootstrap to optimize spacing by adding a margin space around the element. It actually adds a bottom margin of 15px between the current container and it’s next sibling.
form-control: when a control takes the form-control class, its width will be 100% of its container.
Result:

On a medium device:

introbootstrap_scr_17

On a mobile screen:

introbootstrap_scr_18

Tips: The Html5 placeholder attribute shows the default text when the control is empty. In our case, the input displays “email” as content. The actual value of the input is still empty, the placeholder is only for a visual information. 

The best way to ensure that a page displays correctly on a specific device is to open it directly from the device’s web browser. This is not always the case due to the number of available devices and brands in the market. Web developers commonly use the browser debugger to emulate hardware devices (iphone, ipad, google nexus ,…) and all major web browsers have all this option. All mobile screenshots in this tutorial are done in this way.

Practice: Remove the form-control class and see the new behavior on desktop and mobile screen

We can also place the controls horizontally by adding the class form-inline to the form. Controls are then placed side by side till their total width doesn’t exceed the viewport width. If so Bootstrap automatically places them on a new line. According to Bootstrap official documentation, the form-inline class only applies on container being at least 768px wide.

Tips: all classes suffixed with *-inline (form-inline, checkbox-inline, radio-inline,…) always appends its elements side by side.

Code :
<div class=”form-group” class=”form-inline”>
<label for=”email”>Email address</label>
<input type=”email” id=”email” placeholder=”email”>
</div>
<div class=”form-group”>
<label for=”password”>Password</label>
<input type=”password” id=”password” placeholder=”password”>
</div>

Result on desktop screen

introbootstrap_scr_19

Result on a mobile screen: since the screen’s width is lower than 768px, the form-inline effect can’t be seen on this kind of display

introbootstrap_scr_20

Section 9. Using Bootstrap grid system to align form’s elements

Tips: Remember that the Bootstrap grid layout, rows and columns systems are still applicable to input, label, checkbox… actually on any html element)

In this section, we will see how to properly align the form’s controls by using the Bootstrap grid layout. Two steps are involved to make it working:
– First apply the class form-horizontal to the form element.
– Any form’s child elements having the form-group class will then act as a grid manager
– Each element inside each form-group class can finally define how many columns units will be used

Example
<form method=”post” class=”form-horizontal“>
<div class=”form-group“>
<label for=”email” class=”col-xs-4 col-md-4“>Email address</label>
<input type=”email” class=”col-xs-8 col-md-8” id=”email” placeholder=”email”>
</div>
<div class=”form-group“>
<label for=”password” class=”col-xs-4 col-md-4“>Password</label>
<input type=”password” class=”col-xs-8 col-md-8” id=”password” placeholder=”password” >
</div>

The figure below shows the form on a mobile device.

introbootstrap_scr_21

Comments:
On an extra small device, each label will use 4 columns units against 8 columns units for the input type.

The Register.cshtml final code is updated as below:

<form method=”post” class=”form-horizontal“>

<div class=”form-group“>

<label for=”email” class=”col-xs-4 col-md-4 “>Email address</label>

<div class=”col-xs-8 col-md-8″>

<input type=”email” class=”form-control” id=”email” placeholder=”email”>

</div>

</div>

<div class=”form-group“>

<label for=”password” class=”col-xs-4 col-md-4 “>Password</label>

<div class=”col-xs-8 col-md-8″>

<input type=”password” class=”form-control” id=”password” placeholder=”password”>

</div>

</div>

<div class=”form-group“>

<label for=”confirmPassword” class=”col-xs-4 col-md-4 “>Confirm password</label>

<div class=”col-xs-8 col-md-8″>

<input type=”password” class=”form-control” id=”confirmPassword” placeholder=”retype password”>

</div>

</div>

<div class=”form-group“>

<label for=”confirmPassword” class=”col-xs-4 col-md-4 “>Gender</label>

<div class=”col-xs-8″>

<div class=”radio-inline col-xs-4″>

<input type=”radio” name=”gender” id=”radio1″ value=”M”> Male

</div>

<div class=”radio-inline col-xs-4″>

<input type=”radio” name=”gender” id=”radio2″ value=”F”> Female

</div>

</div>

</div>

<div class=”form-group“>

<label for=”alert” class=”col-xs-4 col-md-4 “>Alert by</label>

<div class=”col-xs-8″>

<div>

<input type=”checkbox” name=”alert” id=”chk1″ value=”E”> Email

</div>

<div>

<input type=”checkbox” name=”alert” id=”chk2″ value=”S”> SMS

</div>

<div>

<input type=”checkbox” name=”alert” id=”chk3″ value=”C”> Call

</div>

</div>

</div>

<div class=”form-group“>

<label for=”alert” class=”col-xs-4 col-md-4 “>Payment</label>

<div class=”col-xs-8 col-md-8″>

<select class=”form-control“>

<option></option>

<option>Paypal</option>

<option>Visa</option>

</select>

</div>

</div>

<div class=”form-group“>

<p class=”sr-only“>This part is not visible</p>

<button type=”button” class=”col-xs-offset-2 col-md-offset-2 col-xs-8 col-md-8 btn btn-success“>Submit</button>

</div>

</form>

Result on mobile device :

introbootstrap_scr_22

Result on desktop version

introbootstrap_scr_23

 

The form contains now almost usual form controls (input text, input password, input checkbox, input radio, select and button). New introduced features have been highlighted.
radio-inline: place the radio buttons side by side
sr-only: this class hides its content on any devices. Actually it doesn’t totally hide its content as the property “display:none” does, it just sets a small width and height (~ 1px each).
col-xs-offset-2: the offset keyword marks a “left to right jump” of 2 columns units on extra small device. The component will be then displayed after the second column unit, the first two columns units display empty block.
btn: is special class for button elements. We will have a closer look at the buttons in the next section.

Bootstrap also offers height sizing by using the “input-DEVICE_TYPE” css classes where DEVICE_TYPE is one the keywords lg, sm, xs, md as usual.

The figure below shows the effect of input-lg on the email input

<input type=”email” class=”form-control input-lg ” id=”email” placeholder=”email”>

introbootstrap_scr_24

In the same way, we can enlarge the form-group class element by adding form-group-lg or form-group-sm to decrease the global height.

Practice: Add a textarea control to the register form in the same way as we did for an input type=text control. You can also disable the email address by using the html attribute “disabled”

Summary:
This section is very important for all the newbies on Bootstrap. Placing elements inside the page may be sometimes a nightmare. Remember that since you’re going to use Bootstrap on your project, you should take care of the display essentially on mobile devices. Any complicated forms may deteriorate the user experience so just keep your form as simple as possible.

Section 10. Button elements

Bootstrap has a large support for buttons that cannot be all seen in this introduction tutorial. We’ll only focus on major properties.

We call buttons any elements having the css class btn. They may be an <input type=”button” />, <input type=”submit” /> or just a simple <a> link. The btn class actually transforms them by modifying their borders to be a button-like object.

In the previous section we’ve introduced the button component with following code

<button type=”button” class=”col-xs-offset-2 col-md-offset-2 col-xs-8 col-md-8 btn btn-success”>Submit</button>

Available colors:
The btn-success class displays a green button. Others alternatives are:
. btn-default : bordered white
. btn-primary : blue
. btn-info : light blue
. btn-warning: orange
. btn-danger : red
. btn-link (as opposite to btn, the btn-link class removes all borders to display a link-like style): no background color applied, only the text is visible.

Tips: It is a very common use to reflect the button’s color to it’s real sense. Any delete buttons are better to be marked as btn-danger (strong red) to point out the irreversible operations.

Button sizing:
The button size can be modified with the following classes:
– btn-lg
– btn-sm
– btn-xs

Tips: You should always remember that Bootstrap operates on the css layer. Any attached javascript events will always still work after adding Bootstrap classes to the element.
Practice: We’ve rework the page Login.cshtml to have the following look on mobile device

introbootstrap_scr_25

Code:
<hgroup class=”title”>
<h1>@Page.Title.</h1>
</hgroup>
<form class=”form-horizontal”>
<div class=”form-group “>
<label for=”email” class=”col-xs-4 col-md-4 “>Login</label>
<div class=”col-xs-8 col-md-8″>
<input type=”email” class=”form-control” id=”email” placeholder=”your email address”>
</div>
</div>
<div class=”form-group”>
<label for=”password” class=”col-xs-4 col-md-4 “>Password</label>
<div class=”col-xs-8 col-md-8″>
<input type=”password” class=”form-control” id=”password” placeholder=”password”>
</div>
</div>
<div class=”form-group”>
<button type=”button” class=”col-xs-12 btn btn-info “>Log in</button>
</div>
<div class=”form-group”>
<p class=”pull-right“>
<a class=”btn-sm” href=”~/Account/Register”>Don’t have a Account?</a>
</p>
<p class=”pull-right“>
<a class=”btn-sm” href=”~/Account/ForgotPassword”>Did you forget your password?</a>
</p>
<p class=”pull-right hidden-xs“>
<a class=”btn-sm” href=”#”>Link to mobile version</a>
</p>
</div>
</form>

You may have noticed that we’ve used the pull-right css class. In Bootstrap when you want to apply a float right positioning, you will use the class pull-right (pull-left to place it on the left). We also reduce the font size of the last two links by using the btn-sm class. This example shows that you can independently use the btn-sm css class without the btn class and reciprocally.

An interesting feature of Bootstrap is it’s responsive utility classes. The class hidden-xs is one of them. It tells the browser to hide the content for the targeted device – all extra-small devices in our case. You can read more about all available responsive utilities at the Bootstrap main page.

Summary:
You’ve got a very important hands on experiments on Bootstrap in this section. You have learnt how Bootstrap manages your form’s buttons and how to resize them. We’ve also introduced the responsive utility classes which is a very helpful tools to do a selective display across client’s devices.

Section 11. Managing tables and images with Bootstra

In this section, we’ll see how to add Bootstrap table classes to your existing table to give them a modern look while staying responsive. This can be done easily with the minimum of effort.
Tables
We’ll use the page About.cshtml. The content has been updated as below

<hgroup class=”title”>
<h2>Company history</h2>
</hgroup>
<table>
<thead>
<tr>
<th>Subsidiary</th>
<th>Creation date</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bristol</td>
<td>1970-01-15</td>
</tr>
<tr>
<td>Norwitch</td>
<td>1972-05-06</td>
</tr>
<tr>
<td>Chicago</td>
<td>1980-10-10</td>
</tr>
<tr>
<td>New York</td>
<td>1990-12-11</td>
</tr>
<tr>
<td>London</td>
<td>1999-05-06</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>

 

introbootstrap_scr_26

We apply first the class “table” to the table: <table class=”table”>
We can add the table-responsive class to ensure the responsiveness of our table (effects are only visible on devices having width < 768px otherwise table is already responsive).

introbootstrap_scr_27

 

introbootstrap_scr_28

We can add the table-hover class to make an hover effect

We can also set a predefined status color on each row. There’s six predefined status background colors: active, success, info, danger, warning.

<hgroup class=”title”>

<h2 class=”text-primary bg-info“>Company history</h2>
</hgroup>

<table class=”table table-hover “>
<thead>
<tr>
<th>Subsidiary</th>
<th>Creation date</th>
</tr>
</thead>
<tbody>
<tr class=”success“>
<td>Bristol</td>
<td>1970-01-15</td>
</tr>
<tr class=”danger“>
<td>Norwitch</td>
<td>1972-05-06</td>
</tr>
<tr class=”info“>
<td>Chicago</td>
<td>1980-10-10</td>
</tr>
<tr class=”active“>
<td>New York</td>
<td>1990-12-11</td>
</tr>
<tr class=”warning“>
<td>London</td>
<td>1999-05-06</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>

introbootstrap_scr_29

 

We’ve also add two new classes (text-primary and bg-info), they aim to respectively manage the font and the background color.

Note: Sorting and filtering rows or columns are beyond of the scope of the Bootstrap native implementation. They require additional plugins.

For more advanced features on table, the Bootstrap’s official page is available at http://getbootstrap.com/css/#tables
Images
Boostrap can automatically scale an image to its container by adding the class img-responsive. It also ensures the responsiveness of the image. To center the image element inside it’s container we have to use the “center-block” class. There’s nothing more to say about images. However the future Bootstrap 4 will bring new features to do more with images.

Section 12: Bootstrap and javascrip

At the beginning of this tutorial, we’ve included the Bootstrap javascript file named “bootstrap.min.js”.
This file actually contains all natives Bootstrap’s plugins, they are transition.js, modal.js, dropdown.js, scrollspy.js, tab.js, tooltip.js, popover.js, alert.js , collaps.js, carousel.js ,affix.js. These plugins expose APIs which can be used to interact with them programatically with javascript language. All of them are based on jquery objects (remember that Bootstrap itself needs the jquery core to work). Apart from the official plugins, there’s also third-party plugins made by the community, some of them are hosted at github. Just note that Bootstrap doesn’t give any supports on them.
Tips: Before choosing a third-party library, you need to ensure that it is
– well documented
– well supported

Section 13: Customization

After you become more familiar with Bootstrap, it’s time for customization. This is the last part of the tutorial. In most of the cases, each company has it’s proper graphical charter. So there’s a little chance that you keep the default Bootstrap design layout and use your own instead. Bootstrap is fortunately very flexible and allows you to override existing classes.

As illustration, we’ve put a reference link to the css Site.css in the _SiteLayout.cshtml

<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css” />
<link rel=”stylesheet” href=”~/Content/Site.css” />

Tips: You should never modify the original Bootstrap files. You also need to place your css files after the Bootstrap link otherwise your modification may not carried out properly.

For the sake of simplicity, the Site.css contains the code below:

body {
font-family:’Segoe UI’, Tahoma, Geneva, Verdana, sans-serif;
}
.form-group {
margin-right: -30px!important;
margin-left: -30px!important;
padding-left:30px;
padding-right:30px;
}

We’ve redefined the global font family in the page. We’ve also modified some existing properties on the Bootstrap “form-group” css class and have added two new properties padding-left and padding-right.
We’ve used the css keyword !important to force the use of those properties if they’ve already been defined somewhere else before.

The new register page is shown below. Our new style is now applied to the page.

introbootstrap_scr_30

Note: After you’ve redefined any Bootstrap css styles, you should always check that your website remains responsive. One common mistake is to set a high pixel value width on a div and scroll bars begins to appear on the screen.
What’s next
You’ve seen along this tutorial how to transform quickly your old website into a modern and responsive one by using Bootstrap. It is a very flexible framework. If you want to get full details about Bootstrap, the official Bootstrap website is definitely the way you have to go (http://getbootstrap.com/).
You can also have a look at some existing themes (http://themes.getbootstrap.com/collections/all) to be better inspired.
Bootstrap 4 is now under alpha version (https://v4-alpha.getbootstrap.com/) and looks very promising in terms of new features.

The post Introduction to Bootstrap appeared first on ByteScout.

How to Generate Invoices with PDF SDK

$
0
0

The PDF format is one of the most commonly used format in the enterprise documents exchanges. Each company has its software for invoices, may be from a specific vendor or developed by its own development team. Many dedicated frameworks exist in the market to manipulate PDF files, they all aims to make developer’s work easy.

In this tutorial, we will show how to create your printable invoices with PDF SDK. The Bytescout’s PDF SDK contains many features to deal with pdf documents. You can create pdf files from scratch, on the fly or modify existing one, even exporting them to another file format like Microsoft Office word document without any format and data loss. You can find more details about that on the main website of Bytescout at https://bytescout.com

The rest of this tutorial is focusing on invoices PDF SDK. We’ll see three ways to generate an invoice:

  • Section 1 – build entirely all the invoices parts with the PDF SDK object
  • Section 2 – build an HTML template first, then map the model to the template and finally use the PDF SDK to generate the final invoice
  • Section 3 – use a .DOCX template to generate the invoice with PDF SDK.

.

All of the three methods are done on the server side so they can be plugged to an automated invoicing software for a future use. Each method is independent of the others and you can choose the most suitable one.

We will use the .NET framework 4.5, thus we have to use the net4.5 version of Bytescout.PDF.dll

It is located at C:\Program Files\Bytescout PDF SDK\net4.5\ folder

invoice_src0

Section 1: Building an invoice using the Bytescout’s pdf sdk framework

We will build the whole invoice by a fully use of Bytescout’s pdf sdk. The framework contains a lot of features that can be used to write and format texts, draw lines, arcs, tables, images, canvas and many others. Those objects are then positioned in the page by using the (left,top) system coordinates where (0,0) is at the top left corner of the page.

We start with the default Visual studio C# console application, name the project InvoiceSample01, add reference to Bytescout.PDF.dll and System.Drawing.dll

invoice_src1

In the file Program.cs we add the code below

Program.cs

using Bytescout.PDF;

namespace InvoiceSample01
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create the pdf document
            var invoicePdfDocument = new Document();

            //Define the type of Page format
            var invoicePage = new Page(PaperFormat.A4);

            //Add page to the pdf document
            invoicePdfDocument.Pages.Add(invoicePage);

            //Define two types of font

            //Simple Arial font, size of ten em
            var font = new Font("Arial", 10);
            //Arial font of 12 em and bold
            var fontBold = new Font("Arial", 12, true, false, false, false);

            //Define a brush
            var brush = new SolidBrush();

            /*
             Build each part (text, vertical/horizontal lines...) and place them in the page 
             using their coordinates (left,top)
             */

          
                        
            invoicePage.Canvas.DrawString("Computer accessories Ltd", fontBold, brush, 20, 20);
            invoicePage.Canvas.DrawString("INVOICE", fontBold, brush, 500, 20);

            //Seller address
            invoicePage.Canvas.DrawString("27 Street WorldLand", font, brush, 20, 40);
            invoicePage.Canvas.DrawString("City Lake", font, brush, 20, 60);
            invoicePage.Canvas.DrawString("+00.00.00.00.54", font, brush, 20, 80);
            invoicePage.Canvas.DrawString("+00.00.00.00.55", font, brush, 20, 100);

            //Invoice header labels
            invoicePage.Canvas.DrawString("Date", font, brush, 400, 40);
            invoicePage.Canvas.DrawString("Invoice #", font, brush, 400, 60);
            invoicePage.Canvas.DrawString("Customer #", font, brush, 400, 80);

            //Invoice header values
            invoicePage.Canvas.DrawString("2016-30-11", font, brush, 500, 40);
            invoicePage.Canvas.DrawString("1234567", font, brush, 500, 60);
            invoicePage.Canvas.DrawString("CT-111-52", font, brush, 500, 80);

            //Buyer information

            invoicePage.Canvas.DrawString("Bill To", fontBold, new SolidBrush(new ColorRGB(0, 0, 255)), 20, 120);
            invoicePage.Canvas.DrawString("Ship Sea Land", font, brush, 20, 140);
            invoicePage.Canvas.DrawString("Albert Best Buyer", font, brush, 20, 160);
            invoicePage.Canvas.DrawString("42 Dolphin Blv", font, brush, 20, 180);
            invoicePage.Canvas.DrawString("River City", font, brush, 20, 200);
            invoicePage.Canvas.DrawString("+44.00.00.12.55", font, brush, 20, 220);

            //Add a grey background color in the grid header                        
            SolidBrush brushBackground = new SolidBrush(new ColorRGB(192, 192, 192));
            invoicePage.Canvas.DrawRectangle(brushBackground, 20, 250, 560, 20);

            //Draw the grid lines

	     //The type of pen 
            SolidPen pen = new SolidPen();
            
            //Horizontal lines
            invoicePage.Canvas.DrawLine(pen, 20, 250, 580, 250);

            invoicePage.Canvas.DrawLine(pen, 20, 270, 580, 270);

            invoicePage.Canvas.DrawLine(pen, 20, 370, 580, 370);

            //Vertical lines
            invoicePage.Canvas.DrawLine(pen, 20, 250, 20, 370);

            invoicePage.Canvas.DrawLine(pen, 370, 250, 370, 370);

            invoicePage.Canvas.DrawLine(pen, 440, 250, 440, 370);

            invoicePage.Canvas.DrawLine(pen, 510, 250, 510, 370);

            invoicePage.Canvas.DrawLine(pen, 580, 250, 580, 370);
            

            //Labels
            invoicePage.Canvas.DrawString("Description", fontBold, brush, 160, 255);
            {
                //Items under Description
                invoicePage.Canvas.DrawString("RAM SDRAM PC 1333 Mhz", font, brush, 25, 275);
                invoicePage.Canvas.DrawString("RJ45 LAN connector", font, brush, 25, 295);
                invoicePage.Canvas.DrawString("C19 power supply cable 16A ", font, brush, 25, 315);
                invoicePage.Canvas.DrawString("Headphones CZBluetooth 4", font, brush, 25, 335);
            }
            invoicePage.Canvas.DrawString("Unit price", fontBold, brush, 380, 255);
            {
                //Items under Unit price
                invoicePage.Canvas.DrawString("20,45", font, brush, 390, 275);
                invoicePage.Canvas.DrawString("2,50", font, brush, 390, 295);
                invoicePage.Canvas.DrawString("10,70", font, brush, 390, 315);
                invoicePage.Canvas.DrawString("30,50", font, brush, 390, 335);
            }
            invoicePage.Canvas.DrawString("Quantity", fontBold, brush, 450, 255);
            {
                //Items under Quantity
                invoicePage.Canvas.DrawString("3", font, brush, 470, 275);
                invoicePage.Canvas.DrawString("4", font, brush, 470, 295);
                invoicePage.Canvas.DrawString("5", font, brush, 470, 315);
                invoicePage.Canvas.DrawString("1", font, brush, 470, 335);
            }
            invoicePage.Canvas.DrawString("Amount", fontBold, brush, 520, 255);
            {
                //Items under Amount
                invoicePage.Canvas.DrawString("61,35", font, brush, 540, 275);
                invoicePage.Canvas.DrawString("10,00", font, brush, 540, 295);
                invoicePage.Canvas.DrawString("53,50", font, brush, 540, 315);
                invoicePage.Canvas.DrawString("30,50", font, brush, 540, 335);
            }

            invoicePage.Canvas.DrawString("Sub Total", font, brush, 450, 380);
            invoicePage.Canvas.DrawString("Taxable", font, brush, 450, 400);
            invoicePage.Canvas.DrawString("Tax Rate", font, brush, 450, 420);
            invoicePage.Canvas.DrawString("Tax Due", font, brush, 450, 440);
            invoicePage.Canvas.DrawString("Total", fontBold, brush, 450, 460);

            {
                //amount value
                invoicePage.Canvas.DrawString("0,001", font, brush, 540, 380);
                invoicePage.Canvas.DrawString("0,002", font, brush, 540, 400);
                invoicePage.Canvas.DrawString("0,003", font, brush, 540, 420);
                invoicePage.Canvas.DrawString("0,004", font, brush, 540, 440);
                invoicePage.Canvas.DrawString("0,005", font, brush, 540, 460);
            }

            //Save the pdf as invoice01.pdf
            invoicePdfDocument.Save("invoice01.pdf");

            invoicePdfDocument.Dispose();
        }

    }
}

After running the program, the invoice01.pdf is created in the bin/Debug/ folder and looks like the figure below

invoice_src2

As we’ve seen along the Program.cs code, each piece of the final invoice has been inserted into the pdf document’s page object. The major part of the task is about positioning the elements at their right place in the page. We’ve used the Canvas property of the pdf document object to draw texts and graphics. You can picture a Canvas as a container where you can draw something. Although this method is very powerful – remember you have the full control of each element on the page, building the pdf file in this way may become tedious at the earlier stage of the development since you’ll playing with a lot of coordinates. The logic and the presentation layer are also in the same place so it may be hard to develop and to maintain.

The next two sections will show you how to use a template file to separate the invoice design and the invoice data. We’ll use an HTML and a Microsoft office document (.docx) template files.

Tips: When two elements have the same coordinate into the same page, the last added one is placed on the top of the other. In the above method, the Document.Save(string fileName) method writes the pdf file into the file system.

Section 2: Generate the invoice form an HTML template

We start with the default C# console application in visual studio 2015 Community. We choose the framework 4.5 and name the solution “InvoiceSample02”. We also add references to Bytescout.PDF.dll and Bytescout.PDF.Converters.dll. Those files can be found in the folder C:\Program Files\Bytescout PDK SDK\net4.5\

The figure below shows the snapshot of the solution at this stage

invoice_src3

We’ve added the InvoiceTemplates folder where we’ll put the invoice template. The Model folder contains the definition of classes used to map with the template.

You can picture a template file as a generic file that is used as a base layout to generate different invoices. All generated invoices differs only by specific fields like the customer name, the invoice details, the total amounts etc. The layout doesn’t change and remains the same in terms of design.

After creating the file template000.html in the InvoiceTemplates folder, copy and paste the following code into it.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cstyle%3E%0A%20%20%20%20%20%20%20%20body%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20font-family%3A%20Arial%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20font-size%3A%200.8em%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20width%3A%20800px%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoicePageContainer%20%7B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoiceHeader%2C%20%23invoiceDetail%2C%20%23invoiceFooter%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20display%3A%20block%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoiceHeader%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20min-height%3A%20100px%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23buyerInfoContainer%2C%20%23invoiceReferenceContainer%2C%20%23sellerInfoContainer%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20display%3A%20block%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23buyerInfoContainer%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20min-height%3A%20100px%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20top%3A%20100px%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23sellerInfoContainer%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20position%3A%20absolute%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20min-height%3A%20100px%3B%0A%0A%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoiceDetail%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20position%3A%20absolute%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20top%3A%20200px%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoiceTable%20%7B%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20border-left%3A%201px%20solid%20black%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20border-right%3A%201px%20solid%20black%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20border-top%3A%201px%20solid%20black%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20border-bottom%3A%201px%20solid%20black%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20border-spacing%3A%200%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20width%3A%20950px%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoiceTableDetail%20tr%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20border-bottom%3A%20none%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoiceTableSubTotal%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20border-top%3A%201px%20solid%20black%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%0A%20%20%20%20%20%20%20%20%23buyerInfoContainer%2C%20%23sellerInfoContainer%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20position%3A%20absolute%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20left%3A%2010px%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoiceReferenceContainer%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20position%3A%20absolute%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20left%3A%20700px%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoiceReferenceContainer_Labels%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20position%3A%20absolute%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20display%3A%20inline%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20min-width%3A%20200px%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoiceReferenceContainer_Entry%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20position%3A%20absolute%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20display%3A%20inline%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20width%3A%2064px%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20left%3A%20100px%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoice%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20font-size%3A%201.5em%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20font-weight%3A%20bold%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20display%3A%20block%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20text-align%3A%20right%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20.amount%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20text-align%3A%20right%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20.unitprice%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20text-align%3A%20center%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20border-left%3A%201px%20solid%20black%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20.quantity%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20text-align%3A%20center%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20border-left%3A%201px%20solid%20black%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20border-right%3A%201px%20solid%20black%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20.total%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20font-weight%3A%20bold%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23Tr2%20td%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20height%3A%20300px%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20vertical-align%3A%20text-top%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20border-bottom%3A%201px%20solid%20black%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23invoiceTableTotal%20.amount%2C%20%23invoiceTable%20thead%2C%20%23invoiceBillTo%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20background-color%3A%20%23032b64%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20color%3A%20white%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%23companyName%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20font-weight%3A%20bolder%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20font-size%3A%201.2em%3B%0A%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20.padding-10%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20padding%3A%2010px%2010px%200px%200px%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%3C%2Fstyle%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;style&gt;" title="&lt;style&gt;" />

</head>
<body>


<div id="invoicePageContainer">

<div id="invoiceHeader">


<div id="sellerInfoContainer">

<div id="companyName">Computer accessories Ltd</div>


<div id="companyAddress">27 Street WorldLand </div>


<div id="companyCity">City Lake </div>


<div id="companyPhone">+00.00.00.00.54</div>


<div id="companyFax">+00.00.00.00.55</div>

            </div>



<div id="invoiceReferenceContainer">

<div id="invoice">INVOICE</div>


<div id="invoiceReferenceContainer_Labels">

<div id="">Date</div>


<div id="Div1">Invoice #</div>


<div id="Div2">Customer #</div>

                </div>


<div id="invoiceReferenceContainer_Entry">

<div id="invoiceDate">{{INVOICE_DATE}}</div>


<div id="invoiceId">{{INVOICE_ID}}</div>


<div id="invoiceCustomerId">{{INVOICE_CUSTOMERID}}</div>

                </div>

            </div>


<div id="buyerInfoContainer">

<div id="invoiceBillTo">Bill To :</div>


<div id="invoiceHeader_billTo">{{INVOICE_CUSTOMER_TO}}</div>


<div id="customerName">{{INVOICE_CUSTOMER_NAME}}</div>


<div id="customerStreetAddress">{{INVOICE_CUSTOMER_STREET_ADDRESS}}</div>


<div id="customerCity">{{INVOICE_CUSTOMER_CITY}}</div>


<div id="customerPhone">{{INVOICE_CUSTOMER_PHONE_NUMBER}}</div>

            </div>

        </div>


<div id="invoiceDetail">

<table id="invoiceTable">

<thead>

<tr>

<th style="width:700px">Description</th>


<th style="width:100px">Unit price</th>


<th style="width:50px;">Quantity</th>


<th style="width:50px;">Amount</th>

                    </tr>

                </thead>


<tbody>
                    {{INVOCE_DETAILS}}
                                      

<tr id="invoiceTableSubTotal">

<td></td>


<td></td>


<td class="padding-10">SubTotal</td>


<td class="amount padding-10">{{INVOICE_SUBTOTAL}}</td>

                    </tr>


<tr id="invoiceTableTaxable">

<td></td>


<td></td>


<td class="padding-10">Taxable</td>


<td class="amount padding-10">{{INVOICE_TAXABLE}}</td>

                    </tr>


<tr id="invoiceTableTaxRate">

<td></td>


<td></td>


<td class="padding-10">Tax rate</td>


<td class="amount padding-10">{{INVOICE_TAXRATE}}</td>

                    </tr>


<tr id="invoiceTableTaxDue">

<td></td>


<td></td>


<td class="padding-10">Tax due</td>


<td class="amount padding-10">{{INVOICE_TAXDUE}}</td>

                    </tr>


<tr id="invoiceTableTotal">

<td></td>


<td></td>


<td class="total padding-10">Total</td>


<td class="amount padding-10">{{INVOICE_TOTAL}}</td>

                    </tr>

                </tbody>


<tfoot>
                </tfoot>

            </table>

        </div>


<div id="invoiceFooter">
        </div>

    </div>


</body>
</html>

The figure below shows the HTML template file opened in the browser.

invoice_src4

Static parts have been surrounded in blue. This is the case of the seller information which never changes across multiple invoices. We’ve used the double curly brackets to identity all dynamic fields. As you have noticed, those fields will be replaced by the real values during the mapping phase.

Tips: We’ve used the double curly brackets because Visual Studio highlights them in the editor.

invoice_src5

The next major step is to create our model class. A model class is just an object where each property is associated to one field in the template model.

The figure below shows our five models.

invoice_src6

We split the whole invoice model into five distinct parts. Each part corresponds to an independent set of data like the Buyer information, the item detail section and so on.

Template000_Buyer.cs

using System.Text;
namespace InvoiceSample02.Model
{
    public class Template000_Buyer
    {
        // Map to {{INVOICE_CUSTOMER_TO}}
        public string InvoiceCustomerTo { get; set; }

        // Map to {{INVOICE_CUSTOMER_NAME}}
        public string InvoiceCustomerName { get; set; }
        
        // Map to {{INVOICE_CUSTOMER_STREET_ADDRESS}}
        public string InvoiceCustomerStreetAddress { get; set; }
        
        // Map to {{INVOICE_CUSTOMER_CITY}}
        public string InvoiceCustomerCity { get; set; }
        
        // Map to {{INVOICE_CUSTOMER_PHONE_NUMBER}}
        public string InvoiceCustomerPhoneNumber { get; set; }

        //This method takes a stringbuilder input then looks and replaces a specific pattern
        //by the final value
        public void MapAndGenerate(StringBuilder input)
        {
            input = input.Replace("{{INVOICE_CUSTOMER_TO}}", InvoiceCustomerTo);
            input = input.Replace("{{INVOICE_CUSTOMER_NAME}}", InvoiceCustomerName);
            input = input.Replace("{{INVOICE_CUSTOMER_STREET_ADDRESS}}", InvoiceCustomerStreetAddress);
            input = input.Replace("{{INVOICE_CUSTOMER_CITY}}", InvoiceCustomerCity);
            input = input.Replace("{{INVOICE_CUSTOMER_PHONE_NUMBER}}", InvoiceCustomerPhoneNumber);           
        }
    }
}

Template000_Header.cs

using System.Text;

namespace InvoiceSample02.Model
{    
    public class Template000_Header
    {
        // Map to {{INVOICE_DATE}}
        public string InvoiceDate { get; set; }

        // Map to {{INVOICE_ID}}
        public string InvoiceId { get; set; }

        // Map to {{INVOICE_CUSTOMERID}}
        public string InvoiceCustomerId { get; set; }

        //This method takes a stringbuilder input then looks and replaces a specific pattern
        //by the final value
        public void MapAndGenerate(StringBuilder input)
        {
            input = input.Replace("{{INVOICE_DATE}}", InvoiceDate);
            input = input.Replace("{{INVOICE_ID}}", InvoiceId);
            input = input.Replace("{{INVOICE_CUSTOMERID}}", InvoiceCustomerId);          
        }
    }
}

Template000_Total.cs

using System.Text;
namespace InvoiceSample02.Model
{
    public class Template000_Total 
    {
        // Map to {{INVOICE_SUBTOTAL}}
        public string InvoiceSubTotal { get; set; }

        // Map to {{INVOICE_TAXABLE}}
        public string InvoiceTaxable { get; set; }

        // Map to {{INVOICE_TAXRATE}}
        public string InvoiceTaxRate { get; set; }

        // Map to {{INVOICE_TAXDUE}} 
        public string InvoiceTaxDue { get; set; }

        // Map to {{INVOICE_TOTAL}}
        public string InvoiceTotal { get; set; }

        //This method takes a stringbuilder input then looks and replaces a specific pattern
        //by the final value
        public void MapAndGenerate(StringBuilder input)
        {
            input = input.Replace("{{INVOICE_SUBTOTAL}}", InvoiceSubTotal);
            input = input.Replace("{{INVOICE_TAXABLE}}", InvoiceTaxable);
            input = input.Replace("{{INVOICE_TAXRATE}}", InvoiceTaxRate);
            input = input.Replace("{{INVOICE_TAXDUE}}", InvoiceTaxDue);
            input = input.Replace("{{INVOICE_TOTAL}}", InvoiceTotal);           
        }
    }
}

Template000_ItemDetail.cs

namespace InvoiceSample02.Model
{
    public class Template000_ItemDetail
    {
        //The template of an item in the invoice detail section.
        public const string ItemHtml = @"
<tr class='padding-10'>

<td>{{INVOICEDETAILITEM_LIB}}</td>


<td class='unitprice'>{{INVOICEDETAILITEM_UNITPRICE}}</td>


<td class='quantity'>{{INVOICEDETAILITEM_QUANTITY}}</td>


<td class='amount'>{{INVOICEDETAILITEM_AMOUNT}}</td>

                        </tr>

";

        // Map to {{INVOICEDETAILITEM_LIB}}
        public string InvoiceDetailItemLib { get; set; }

        // Map to {{INVOICEDETAILITEM_UNITPRICE}}
        public string InvoiceDetailItemUnitPrice { get; set; }

        // Map to {{INVOICEDETAILITEM_QUANTITY}}
        public string InvoiceDetailItemQuantity { get; set; }

        // Map to {{INVOICEDETAILITEM_AMOUNT}}
        public string InvoiceDetailItemAmount { get; set; }

        //ToString function is now returning the item detail in html format
        public override string ToString()
        {
            string html = ItemHtml.Replace("{{INVOICEDETAILITEM_LIB}}", InvoiceDetailItemLib);
            html = html.Replace("{{INVOICEDETAILITEM_UNITPRICE}}", InvoiceDetailItemUnitPrice);
            html = html.Replace("{{INVOICEDETAILITEM_QUANTITY}}", InvoiceDetailItemQuantity);
            html = html.Replace("{{INVOICEDETAILITEM_AMOUNT}}", InvoiceDetailItemAmount);
            return html;
        }
    }

}

Template000_Model.cs

using System.Collections.Generic;
using System.IO;
using System.Text;
namespace InvoiceSample02.Model
{
    // Template000_Model is the whole invoice, it contains the header information, the buyer and total and
    // also a list of items
    public class Template000_Model
    {
        //Reads and sets the template file
        private StringBuilder template000Html = new StringBuilder().Append( File.ReadAllText("../../InvoiceTemplates/template000.html"));

        public Template000_Model()
        {
            //Initialize all properties
            Header = new Template000_Header();
            Buyer = new Template000_Buyer();
            Details = new List&amp;amp;amp;lt;Template000_ItemDetail&amp;amp;amp;gt;();
            Total = new Template000_Total();
        }


        public Template000_Header Header { get; set; }
        public Template000_Buyer Buyer { get; set; }
        public List&amp;amp;amp;lt;Template000_ItemDetail&amp;amp;amp;gt; Details { get; set; }
        public Template000_Total Total { get; set; }

        
        //This method adds an item to the invoice model        
        public void AddItem(Template000_ItemDetail item)
        {
            Details.Add(item);
        }
        //Genarete the invoice detail section
        private void GenerateDetailsHtml()
        {
            StringBuilder detailHtml = new StringBuilder();
            foreach (var item in Details)
            {
                detailHtml.Append(item.ToString());
            }
            template000Html = template000Html.Replace("{{INVOCE_DETAILS}}", detailHtml.ToString());
        }
        //Process all mapping tasks and generate the final content in html string
        public StringBuilder MapAndGenerateHtml()
        {
            Header.MapAndGenerate(template000Html);
            Buyer.MapAndGenerate(template000Html);
            Total.MapAndGenerate(template000Html);
            GenerateDetailsHtml();
            return template000Html;
        }
    }
}

The Template000_Model class is where we reassemble all parts into one model. It contains the reference to the template file in the template000Html variable.

The main program below is divided into two parts, the first one is where we create the invoice object and the second is where we call the pdf sdk to generate the invoice pdf file. The final document is actually generated in memory by calling the method HtmlToPdfConverter.ConvertHtmlToPdf of Bytescout.PDF.Converters namespace and created in the file system by the MemoryStream.WriteTo method.

Main Program.cs

using Bytescout.PDF.Converters;
using InvoiceSample02.Model;
using System.IO;
using System.Text;

namespace InvoiceSample02
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declare the invoice object
            Template000_Model model = new Template000_Model();

            //Set value of each field in the invoice's header section
            model.Header.InvoiceDate = "2016-30-11";
            model.Header.InvoiceId = "1234567";
            model.Header.InvoiceCustomerId = "CT-111-52";

            //Fill invoice's buyer section
            model.Buyer.InvoiceCustomerTo = "Ship Sea Land";
            model.Buyer.InvoiceCustomerName = "Albert Best Buyer";
            model.Buyer.InvoiceCustomerStreetAddress = "42 Dolphin Blv";
            model.Buyer.InvoiceCustomerCity = "River City";
            model.Buyer.InvoiceCustomerPhoneNumber = "+44.00.00.12.55";

            //Add items to invoice
            model.AddItem(new Template000_ItemDetail() { InvoiceDetailItemLib = "RAM SDRAM PC 1333 Mhz", InvoiceDetailItemUnitPrice = "20,45", InvoiceDetailItemQuantity = "3", InvoiceDetailItemAmount = "61,35" });
            model.AddItem(new Template000_ItemDetail() { InvoiceDetailItemLib = "RJ45 LAN connector", InvoiceDetailItemUnitPrice = "2,50", InvoiceDetailItemQuantity = "4", InvoiceDetailItemAmount = "10,00" });
            model.AddItem(new Template000_ItemDetail() { InvoiceDetailItemLib = "C19 power supply cable 16A", InvoiceDetailItemUnitPrice = "10,70", InvoiceDetailItemQuantity = "5", InvoiceDetailItemAmount = "53,50" });
            model.AddItem(new Template000_ItemDetail() { InvoiceDetailItemLib = "Headphones CZ Bluetooth 4", InvoiceDetailItemUnitPrice = "30,50", InvoiceDetailItemQuantity = "1", InvoiceDetailItemAmount = "30,50" });
            model.AddItem(new Template000_ItemDetail() { InvoiceDetailItemLib = "Optical Mouse black edition", InvoiceDetailItemUnitPrice = "19,99", InvoiceDetailItemQuantity = "1", InvoiceDetailItemAmount = "19,99" });


            //Fill the Total section
            model.Total.InvoiceSubTotal = "45,05";
            model.Total.InvoiceTaxable = "45,05";
            model.Total.InvoiceTaxRate = "20%";
            model.Total.InvoiceTaxDue = "10,05";
            model.Total.InvoiceTotal = "55,10";

            //Generate the final string            
            StringBuilder invoiceHtml = model.MapAndGenerateHtml();

            // Generate the pdf with Bytescout's PDF SDK helper
            using (HtmlToPdfConverter converter = new HtmlToPdfConverter())
            {                
                // Create an in memory stream from the initial string
                var htmlSourceStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(invoiceHtml.ToString()));

                // Create an in memory stream to hold the generated pdf file 
                var destinationStream = new MemoryStream();

                // Generates the pdf in memory
                converter.ConvertHtmlToPdf(htmlSourceStream, destinationStream);

                // And writes it to disk
                FileStream file = new FileStream("invoice.pdf", FileMode.Create, FileAccess.Write);
                destinationStream.WriteTo(file);

                // Finaly close of opened resources
                file.Close();
                htmlSourceStream.Close();
                destinationStream.Close();
            }
        }
    }
}

 

After running the program, the invoice.pdf file is created at the same folder as the executable file, in the bin/Debug/ directory in the actual case.

invoice_src7

Section summary:

In this section we’ve seen how to generate the invoice pdf file form the html template. The invoice layout was entirely made with HTML and CSS, independently of the invoice model object and separated to the pdf process rendering. HTML and CSS are very popular and commonly used today so this method may be the most suitable one if you’re using them in your work.

Section 3: Generate an invoice file form a DOCX template file

Microsoft Office Word documents are largely used in the business for years. Primary versions had the extension .doc and the latest formats are in the .docx extension.They are based on the OpenXML standard. The template file will have the extension .docx thus we will use the Microsoft’s OpenXML SDK to process it. To make the printable invoices PDF SDK tools will be added to our solution.

We start with a basic C# console program named “InvoiceSample03”.

Then we add the Open XML SDK.

Right click the References items > Manage NuGet Packages …

invoice_src8

In the browse field, enter OpenXML SDK and choose the Microsoft’s OpenXML SDK 2.5 in the search result then click the Install button

invoice_src9

Add the reference to the Bytescout.PDF.Converters.dll (located under the folder C:\Program Files\Bytescout PDF SDK\net4.5\)

Add a reference to the assembly WindowsBase

We also create the Templates folder and copy the provided “InvoiceTemplate-000.docx” file inside it.

The solution should be similar to the figure below:

invoice_src10

The invoicetemplate-000 is a normal word document apart from template fields which are identified by double curly brackets.

invoice_src11

Copy the following content to the main Program.cs

Program.cs


using Bytescout.PDF.Converters;
using DocumentFormat.OpenXml.Packaging;
using System;
using System.IO;
namespace InvoiceSample03
{
    class Program
    {
        static void Main(string[] args)
        {
            //Path to the original template file
            string invoiceTemplate = "../../Templates/InvoiceTemplate-000.docx";

            //The name of the template working copy file
            string invoicePrint = "Invoice001.docx";

            //Create the working invoice from the template, overwrites if exist
            File.Copy(invoiceTemplate, invoicePrint,true);

            //Process the work document
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(invoicePrint, true))
            {    
                //this variable will contains the original content of the template file
                string docText = null;
                //Get the original stream from the orignal content
                using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }

                docText = docText.Replace("{{DATE}}","");
                docText = docText.Replace("{{INVOICE}}","");
                docText = docText.Replace("{{CUSTOMER}}", "");
                
                docText = docText.Replace("{{SELLERNAME}}","");
                docText = docText.Replace("{{SELLERADDRESS}}", "");
                docText = docText.Replace("{{SELLERSTREET}}", "");
                docText = docText.Replace("{{SELLERCITY}}", "");
                docText = docText.Replace("{{SELLERLINE}}", "");

                { //Description column
                    var descriptionColumnStr = String.Empty;
                    descriptionColumnStr = "RAM SDRAM PC 1333 Mhz " + Environment.NewLine;
                    descriptionColumnStr += "RJ45 LAN connector" + Environment.NewLine;
                    descriptionColumnStr += "C19 power supply cable 16A" + Environment.NewLine;
                    descriptionColumnStr += "Headphones CZBluetooth 4" + Environment.NewLine;
                    descriptionColumnStr += "Optical Mouse black edition" + Environment.NewLine;
                    docText = docText.Replace("{{ITEM_DESCRIPTION}}", descriptionColumnStr);
                }

                { //Unit price column
                    var unitPriceColumnStr = String.Empty;
                    unitPriceColumnStr = "20,45" + Environment.NewLine;
                    unitPriceColumnStr += "2,50" + Environment.NewLine;
                    unitPriceColumnStr += "10,70" + Environment.NewLine;
                    unitPriceColumnStr += "30,50" + Environment.NewLine;
                    unitPriceColumnStr += "19,99" + Environment.NewLine;
                    docText = docText.Replace("{{UP}}", unitPriceColumnStr);
                }

                { //Quantity column
                    var quantityColumnStr = String.Empty;
                    quantityColumnStr = "3" + Environment.NewLine;
                    quantityColumnStr += "4" + Environment.NewLine;
                    quantityColumnStr += "5" + Environment.NewLine;
                    quantityColumnStr += "1" + Environment.NewLine;
                    quantityColumnStr += "1" + Environment.NewLine;
                    docText = docText.Replace("{{QTY}}", quantityColumnStr);
                }

                { //Amount column
                    var amountColumnStr = String.Empty;
                    amountColumnStr = "61,35" + Environment.NewLine;
                    amountColumnStr += "10,00" + Environment.NewLine;
                    amountColumnStr += "53,50" + Environment.NewLine;
                    amountColumnStr += "30,50" + Environment.NewLine;
                    amountColumnStr += "19,99" + Environment.NewLine;
                    docText = docText.Replace("{{PRICE}}", amountColumnStr);
                }

                {//Sub total part
                    docText = docText.Replace("{{ST}}", "45,05");
                    docText = docText.Replace("{{TX}}", "45,05");
                    docText = docText.Replace("{{TR}}", "20%");
                    docText = docText.Replace("{{TD}}", "10,05");
                    docText = docText.Replace("{{TOTAL}}", "55,10");
                }         

                //Write to new content to the template file working copy 
                using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))                
                {
                    sw.Write(docText);
                }              
            }

            // Create the object to do the DOCX to PDF file
            using (DocxToPdfConverter converter = new DocxToPdfConverter())
            {
                // Perform conversion and save the pdf in the file "Invoice001.pdf"
                converter.ConvertDocxToPdf(invoicePrint, "Invoice001.pdf");
            }
            
            Console.ReadLine();
        }
    }
}

 

You can run the program to the generated pdf file below.

invoice_src12

The program can be divided into three major parts:

1 – Create a working copy of the invoice template .docx file and read it’s content.

2- Replace all template’s field identifiers to their actual values.

3- Call the PDF SDK helpers to generate the pdf version.

Step 1 is done by using the OpenXml SDK. You can use this library for almost all your OpenXML developments. It includes Microsoft Office Word, Excel, PowerPoint and other applications using the Microsoft OpenXml standard format. We only use the WordprocessingDocument object to read the template file’s content.

The step 2 is where we’ve replaced the patterns to values and created the final .docx file.

The step 3 is where we call the PDF SDK DocxToPdfConverter utility to generate the invoice pdf from the .docx file created in step 2.

In term of software design and architecture, your solution should keep the minimum of dependencies between layers. We advise you to always use the template file when it is possible. It avoids hard-coding and is very flexible since the template file is not embedded into any assembly. You can even place them in a shared folder in the network and update them in the fly without recompiling your program or restarting your application pool.

Performance indicators are also part of the game. We will do some metrics to show you how bad or well each method performs :

Average processing time / PDF SDK method (in ms) – base on the same pdf content.

*Workstation with 2 x Intel Xeon e5620 – 8Cores/16 Threads – 2.4Ghz, 24GB Memory

Hard-coding – section 1

Method: Document.Save

15

Exporting HTML to PDF – Section 2

Method: HtmlToPdfConverter.ConvertHtmlToPdf

369

Exporting DOCX to PDF – Section 3

Method: DocxToPdfConverter.ConvertDocxToPdf

4550

As shown in the above table, the method shown in the first section performs very fast with only an average of 15ms to generate an invoice file while the processing time increases by 24 times for creating the invoice from an HTML template. The .docx template is 296 times slower than the method 1.

Those metrics can guide you in the way you’ll use in your invoice processing. If your business requires a very fast processing, you may choose the method shown in section 1 (actually there’s a linear evolution between the number of generated invoices and the processing time). The hard-coding way can generate 1000 invoices in 16 seconds, 2000 invoices in 32 seconds and so on

If time factor is not critical, the second method is a good alternative for an average processing time of ~370ms. This scenario offers a good mix between performance and maintenance.

The third case is very useful if your business requires a DOCX template, however, the latency time makes it very partial for synchronous processing.

Conclusion

We’ve seen along this tutorial three ways to make printable invoices with PDF SDK. You can use the one which suits well your skills or the business requirements. The PDF SDK can be plugged into your actual invoice processing software. This can be done with only a couple of line codes and independently of any existing business logic rules, thus minimizing the risk of unexpected bugs. It can be also called from your invoice automation software as batch programs.

The post How to Generate Invoices with PDF SDK appeared first on ByteScout.

Advanced Action Formulas and Functions: Reading and Writing Excel Files

$
0
0

Excel files or more commonly known as spreadsheets are used to store, manipulate, analyze and retrieve statistical data. Spreadsheets work as a down-featured version of database management systems. Common uses of spreadsheets include daily price charts and sales data, student result calculation, employee salary management and similar systems. In short, almost all the statistical data can be stored, manipulated and presented in the form of graphs, charts, and tables via spreadsheets.

The best thing about spreadsheets is that they come with built-in mathematical formulas to perform common calculations such as finding an average of all the values in the column, calculating factorial of values in a particular row or column and finding percentages etc. Apart from built-in functions, excel spreadsheets also allow users to define custom formulas. For instance, you can take a square of each term in the column, subtract the original term from the squared value and then add them via some custom formula. The possibilities are virtually limitless.

Though excel can be used as a standalone application, sometimes we need to work with excel documents via application code. Simple tasks include read from excel file, write in excel file and so on and so forth. In this article, we are going to explain how we can read Microsoft excel spreadsheet file and how to write data in excel file.

We shall explain how to interact with excel spreadsheets via Microsoft.NET programs. For this tutorial, we shall use Bytescout spreadsheet SDK. This standard development kit comes with built-in functions that can be used to read and write data from excel files. To download, Bytescout SDK, go to this link and download the SDK. If you are using Windows computer, your downloaded SDK should be located in C:\Program Files\Bytescout Spreadsheet SDK. From there you can select the .NET version of your choice for the DLL and import in the .NET program.

Creating an Excel Spreadsheet via Bytescout SDK.

Creating an Excel spreadsheet via Bytescout SDK is pretty simple. In the following code snippet, we shall create a C# console application in visual studio. Once the project is created, right-click the name of the project and click add reference. Here you should choose the dynamic link library named Bytescout.Spreadsheet.dll. The following console application is created with .NET Framework version 4.0, therefore the Bytescout library, added in this case, will be that in the 4.0 folder. Now, to create a spreadsheet, take a look at the following code. The explanation for the code is given after that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bytescout.Spreadsheet;
using System.IO;
using System.Diagnostics;

namespace ByteScoutApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Spreadsheet exceldoc = new Spreadsheet();
            Worksheet excelSheet = exceldoc.Workbook.Worksheets.Add("ExcelSampleSheet");

            excelSheet.Cell("A1").Value = "Formula in Textual Form";

            excelSheet.Columns[0].Width = 200;

            excelSheet.Cell("B1").Value = "Formula1 (calculated Value)";

            excelSheet.Columns[1].Width = 200;

            excelSheet.Cell("C1").Value = "Formula2 (calculated Value)";

            excelSheet.Columns[2].Width = 200;

            excelSheet.Cell("A2").Value = "50-2-10";

            excelSheet.Cell("B2").Value = "=50*2+10";

            excelSheet.Cell("C2").Value = "=50/2-10";

            if (File.Exists("Demo.xls"))
            {
                File.Delete("Demo.xls");
            }

            exceldoc.SaveAs("Demo.xls");


            exceldoc.Close();

            Process.Start("Demo.xls");
        }
    }
}

Let’s explain the above code line by line.

The Spreadsheet class is used to create  a Spreadsheet object which is basically the parent class for all the sheets in the excel documents. Here the reference to Spreadsheet object is stored in “exceldoc” variable. Next, we use “exceldoc.Workbook.Worksheets.Add(“ExcelSampleSheet”); method to create a worksheet inside the exceldoc. The above function returns a handler for the newly created sheet. The handler name in our case is “excelSheet”.

Now to access cell within an excel sheet, we simply call “Cell” function on the excelSheet variable and pass it the name of the cell. For instance, we use excelSheet.Cell(“A1”). value in order to set the value of the column. In similar ways, we set values for the B1 and C1 columns. Similarly, we set the width of any column inside the spreadsheet via “excelSheet.Columns[1].Width” property. In the above code, we set the width of A, B and C columns to 200.

Now again we access the A2 cell and add some text to it. In the B2 and C2 cells, we specify that this should be the result of 50*2+10 and 50/2-10. Finally, we check if “demo.xls” exists, if it does exist we delete the previous file and save our new file with the name “demo.xls”. In the end, we open the newly created file. So if you did everything correctly and you run the above code, an excel file shall be opened with a sheet named “ExcelSampleSheet”. It will have three columns and two rows filled. And you shall see the result of 50*2+10 and 50/2-10 in the second and third columns of the second row respectively. This is how you basically create an excel file and add some values to it using Bytescout SDK.

Reading an Excel Sheet Via Bytescout SDK

The process of reading an excel sheet via Bytescout SDK is simple. You first have to import the corresponding Bytescout.Spreadsheet.dll into your program. The following explains how to read each value in the demo.xls that we created in last code sample.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;	
using Bytescout.Spreadsheet;
using System.IO;
using System.Diagnostics;

namespace ByteScoutApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            Spreadsheet excelDoc = new Spreadsheet();
            excelDoc.LoadFromFile("demo.xls");

            Worksheet excelSheet = excelDoc.Workbook.Worksheets.ByName("ExcelSampleSheet");

 
            for (int i = 0; i < 2; i++)
            {
                

                for (int j=0; j<3;j++)
                {
                    Cell currentCell = excelSheet.Cell(i, j);
                 
                        Console.WriteLine( currentCell.Value);
                    
                }
            }
            excelDoc.Close();

            Console.ReadKey();

        }
    }
}

The above code is very straight forward, here we simply use the loadFromFile function of the Spreadsheet object to load “demo.xls” file into excelDoc object. Next, we obtained the handler for the spreadsheet whose cell we want to access which is “ExcelSampleSheet” in our case. Finally, we use two for loops to loop over each and every cell in the spreadsheet. The outer loop iterates over each row while inner loop iterates over each column, we use Cell function of the spreadsheet to access each cell. It takes two parameters the row and column. In the console output, we displayed the value for each cell in the demo.xls file.

From the above two examples, it is clear that Bytescout spreadsheet SDK is extremely handy when it comes to reading and writing excel files. Apart from Spreadsheet SDK, Bytescout provides a variety of developer tools that are used to perform different functionalities. A list of such tools is available at the following link .

The post Advanced Action Formulas and Functions: Reading and Writing Excel Files appeared first on ByteScout.

FFMPEG Command Lines To Convert Various Video Formats Between Each Other

$
0
0

Fast Forward MPEG (FFmpeg) is one of the most popular and the best multimedia networks in the world. It offers plenty of tools for you to play the video, convert the formats, stream live broadcast and even analysis the multimedia stream. These are the tools which actually make FFmpeg is a great framework to work with. They provide you with best technical solutions, also offering a myriad of extremely useful yet free software to the users.

FFmpeg can perform many functions when it comes to digitally playing or recording your videos and audios. For instance, you can easily convert the video from one format to another. Following is a very simple example of a command line which converts MP4 file into AVI file.

  # ffmpeg –i  Shawshank_Redemption.mp4  Shawshank_Redemption.avi

 This is the simplest example of any command line you will come across in the FFmpeg. This command will make ffmpeg video converter to convert MP4 file into an file. It is as simple as that. However, it is also recommended to declare other specification such as bitrate and codex as well.

Various Command Lines to Convert Video Formats.

In the context of above discussion, following are some ffmpeg examples of the commands you can use to convert video formats.

.AVI VIDEO TO .MPG:

.avi and .mpg are two of the most popular video formats. Following commands help you convert .avi video to .mpg.

  # ffmpeg –i original_video.mpg final_vidoe.avi

 

Conversely, following command will convert an .avi video into an .mpg video.

  # ffmpeg –i – Shawshank_Redemption.avi  Shawshank_Redemption.mpg

 

.MP4 to .WMV:

The following commands convert .mp4 and .wmv formats between each other.

    # ffmpeg –i  – video_name.mp4  final_video_name.wmv

 

Now, simply reverse the code to make ffmpeg convert video to mp4. It can’t be simpler than that.

    # ffmpeg –i  – video_name.wmv final_video_name.mp4

 

.AVI to Uncompressed Animated Gifs:

Sometimes, you also want to convert your videos to animated gifs, especially if you run a blog or online video channel. Following is the Ffmpeg command for converting an .avi video to an uncompressed gif.

    # ffmpeg –i  – original_video.avi gif_uncompressed.gif

 

.AVI to .FLV:

.flv is another very popular video format. The command line used for converting .avi video format to .flv is slightly different from rest of the commands. Take a look at the following example.

    # ffmpeg –i  – original_video.avi –f flv final_video.flv

 

.AVI to DV:

DV is a new video format which is quickly garnering popularity among users. Following is a command line you can use to convert .AVI file to a DV file.  

    # ffmpeg –i  – origine.avi -s pal -r pal -aspect 4:3 -ar 48000 -ac 2 video_finale.dv

 

Converting formats for DVD players:

When it comes to converting videos for DVD players, you need a different line of code. Take a look at the following example.

    # ffmpeg –i  –original_video.avi –target pal-dvd –ps 1000000000 –aspect 16:9 final_video.mpeg

 

Following is a brief explanation of the above command line.

  • Aspect ratio is 16:9 which is perfect for widescreens.
  • ps 1000000000 is the size of the output file in bites. It is the maximum size for the output video in this particular case.
  • target pal-dvd determines the output format of the video.

In addition to converting video formats between each other, Ffmpeg can also help users to compress different formats between each other. Following is an example of a command line which compresses .AVI to DIVX.

    # ffmpeg –i  –original_video.avi –s 320×240 –vcodec msmpeg4v2 video_output.avi

 

Similarly you can use following commands to COMPRESS .AVI TO SVCD MPEG2.

PAL format

    # ffmpeg –i  –original_video.avi –target pal-svcd final_video.mpg

 

NTSC format:

    # ffmpeg –i  –original_video.avi –target ntsc-svcd final_video.mpg

 

FFmpeg Copy Video Command Line:

Sometimes, it is not a good idea to recode your video. All you need to do is to copy the contents especially when you are editing the video and cutting some of its parts. Following is the command you should use when you want to copy the video instead of recoding it.

    # ffmpeg –i  –origine.mp4 –c:v copy –c:a copy –final.mkv

 

You can use the same command to copy the video in any format.

Command Line Examples h264:

Ffmpeg also comes with latest x264 encoder which allows you to create high quality H.264 videos quite easily. There are actually two ways you can use x264 encoder to create videos. First of all you need to choose a CRF value and a preset. Subsequently, apply your chosen values in the coder to get the video. This will also help you maintain the quality of all of the future vides you want to encode as well. Take a look at these ffmpeg command line examples h264.

Ffmpeg CRF Example:

    # ffmpeg –i  –input –c:v libx264 –preset fast –crf 22 –c:a copy output.mkv

 FFmpeg Transcode Example:

If you are looking for a more flexible way to use FFmpeg for encoding videos, you must consider using the transcoding feature. You can convert any video and audio format into your specified video codecs and audio output. Following is an example of FFmpeg transcoding.

ffmpeg –i  {filepath/inputfile}.{inputwrapper} –vcodec {desired video codec} –acodec {desired audio codec} {outputfile}.{output wrapper}

 

The transcode code can look like this in real life.

    # ffmpeg –i  origine.avi –vcodec prores –acodec pcm_s16Ie file.

 

What this command line is doing that it is converting a standard .avi file to a Quick Time Apple Prores.

FFmpeg Command Line Generators:

You can use many generators or editors to generate command lines for FFmpeg. For instance, FFmpeg Little Helper is a very popular ffmpeg command line generator. Similarly, you can also use Command Line Encoder if you are using windows 10. This particular encoder makes it really simple to generate FFmpeg command lines for windows. There are in fact innumerable command line generates you can use. Just do a little search on Internet and you will get plenty of options to choose from.

Finally, it is also important for you to check the official documentation of FFmpeg if you are new to this multimedia framework. This will help you learn more about FFmpeg and all the amazing things you can do using this extremely popular video converting framework.

The post FFMPEG Command Lines To Convert Various Video Formats Between Each Other appeared first on ByteScout.


.NET versions: review .net version (Mono, Core, etc) and what are the key differences

$
0
0

Microsoft introduced the .NET Framework at the beginning of the 2000’s. It was considered to be the successor of Windows COM programming and came with:
– several programming languages where C#.net and VB.NET are the two most used
– a web framework is known as ASP.NET in the alternative to the classical ASP
– a compiler and a new runtime environment named CLR

The .NET framework became popular towards companies around the world and a large community of developers quickly arose around it.
The framework has been improved over the time. New features had been introduced, the .NET Framework has even been completely reworked at a certain stage in order to improve the framework performances and the developer experiences. We can list the introduction of the WPF for modern desktop applications, WCF for service oriented applications, WWF for business workflows or the Entity Framework product introduced a new way for consuming data.
The .NET Framework has been designed to run on computers with a Microsoft Windows based operating system. It is a non-free product with a closed source code. In June 2004, Mono, an open source project, has been initially released by an independent developer community in order to give an alternative to building and running .NET programs into other operating systems like Linux. The project was supported first by Novell and finally by Microsoft a few years later. However, Mono didn’t place itself as a direct competitor of the .NET Framework. It was considered by many developers to not be a real “serious” choice for their solutions. In the latest few years, technologies evolve very quickly. Due to the increasing number of platforms, engineer’s vision are converging towards cross-platform products. Since the .NET Framework has a big lack of interoperability on non-Windows platforms, Microsoft then introduced the .NET Core which aims to give a cross-platform framework for developers. This is the fundamental idea behind the new .NET Core: being compatible with all devices running different operation systems. The .NET Core is considered by many as the new .NET Framework, this is not actually very fair because the .NET Core is not going to replace the .NET Framework – at least for the moment.

At the time of writing, latest .NET framework version is 4.6.2, 4.6.2 for Mono too, and the .NET Core is at 1.1. Since things are growing and quickly change, some points that you’re going to read in this tutorial may become obsolete in the future.
In the rest of this tutorial, we will talk about classical .NET framework, the .NET Core and the Mono project. We essentially focus on the .NET Core, how to work with .NET Core since it is the most promising at the moment.

.NET Framework quick review
We’re not going to do a full detailed list of all .NET Framework features, a lot of words had been said about it. We just only give important keys of the framework.

The .NET Framework is often provided with Microsoft Windows. You can always download a specific version of .NET Framework from Microsoft website. Almost the time, the executable has the name dotNetFx[Version] where [version] is the version number of the current download. Prior any installation, it’s better a good practice to check the compatibility of your OS and the .NET Framework you’re going to install.

How to determine what .NET Framework version is installed on your system
You can find .NET framework installed at a specific location folder
C:\Windows\Microsoft.NET\Framework (for 32 bits) or C:\Windows\Microsoft.NET\Framework64 (for 64bits).
The figure below shows the major version on our system.

For 32bits folder

_net_src1

For 64 bits folder

_net_src2

The 32 bits folder contains .NET version from 1.0 to 4.0. It means that the 32 bits versions of the .NET Framework from 1.0 to 4.0 are installed on our computer. Our system only contains the 64 bits version of .NET Framework from 2.0 to 4.0.

Our system has also .NET Framework 4.6.1 which is not displayed in a separate folder. This is true in the sense that versions after 4.0 had been built over the top of 4.0 itself. To check if the framework 4.6.1 is installed, we have to go to the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full in the regedit tree

_net_src3

Tips: In the above figure, the NDP subkey lists all installed versions.

You then need to compare the value of the DWORD release key with the following table

Release DWORD

version

378389 .NET Framework 4.5

378675

.NET Framework 4.5.1 installed with Windows 8.1 or Windows Server 2012 R2

378758

.NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2

379893

.NET Framework 4.5.2

393295

.NET Framework 4.6 installed with Windows 10

393297

.NET Framework 4.6 installed on all other Windows OS versions

394254

.NET Framework 4.6.1 installed on Windows 10

394271

.NET Framework 4.6.1 installed on all other Windows OS versions

source : https://msdn.microsoft.com/fr-fr/library/hh925568(v=vs.110).aspx)

The release value on our system is 394271, so .NET Framework 4.6.1 is really installed on our system. This is the accurate way to determine which .NET Framework are installed on a given system.

CLR and .NET Framework

.NET Framework is a set of assemblies while the Common Language Runtime is the fundamental component which manages and executes our codes (Garbage collector management, resources allocations, environment execution, threads priorities,… ). The CLR is contained in each .NET Framework version. The following grid shows each .NET Framework and the underlying CLR version.

.NET Framework version

Major new features

CLR Version

1.0

1.0

1.1

ASP.NET, ADO.NET,…

1.1

2.0

Generics,…

2.0

3.0

WPF, WCF, WF,…

2.0

3.5

Linq

2.0

4

Expanded base class libraries

  • Cross-platform development with Portable Class Library
  • MEF, DLR, code contracts

4

4.5

Support for Windows Store apps

  • WPF, WCF, WF, ASP.NET updates

4

4.5.1

Support for Windows Phone Store apps

4

4.5.2

New APIs for transactional systems and ASP.NET

4

4.6

Compilation using .NET Native

  • ASP.NET Core 5

4

4.6.1

4

4.6.2

4

You can get more details at https://msdn.microsoft.com/fr-fr/library/bb822049(v=vs.110).aspx

Major components of .NET Framework

_net_src4

.NET Framework is composed by 4 major components which are:

ASP.NET for building and hosting web applications (IIS Webserver). At the earlier stage of .NET Framework, only Webform existed then came the MVC pattern and finally the WebAPI for RestFull architecture.

Windows Presentation Framework (WPF) which is the technology to develop rich desktop client applications, the classical Windows forms application still be available in .NET Framework

Windows Communication Foundation (WCF) is a new concept to expose and consume services. It is a complete framework to design a service oriented architecture with a bunch of supported protocols and tools to handle your data exchange through endpoints.

Windows Workflow Foundation (WWF) is all about workflow and business process management. You can easily design a complex data flow and decision paths with WWF. Some major BPM Software is based on WWF like K2 BlackPearl products.

Visual Studio is the most famous IDE in .NET world. It has been improved along the years and a solid community supports it development. Nowadays you can download a free version of Visual Studio for your development purpose, some editions with enterprise-level functionalities are also available with charges. You can find a complete information at https://www.visualstudio.com/

 

.NET Core

The next expectation for many developers is definitely the ability to work and run their apps outside any Microsoft environment. It may be a Linux workstation, a OSX system, may be a Nintendo console or something else. That was impossible with the .NET Framework since it only supports Microsoft Windows platforms. This becomes a reality with the .NET Core. The .NET Core is designed to develop and run apps on any platforms.

Unlike .NET Framework, .NET Core is totally free and open-source, under MIT license. The full source code is available and can be downloaded. You can even recompile the entire framework if needed. However, we don’t need to rebuild it because there’s already a compiled and ready to use binary for all supported platforms.

 

Tips on .net core

These are some terms that you will often heard when dealing with the new .NET Core

.NET Core: is actually .NET Core runtime and framework

.NET Core SDK: is the whole .NET Core + Command Line Interface tools (see below).

.CLI tools: a set of utilities that allows interactions between the developer and the framework with the use of command lines. The program “dotnet” is one of its main component. We will see a concrete use case later.

: .Net Core Common Language Runtime is the runtime of .NET Core. The full source can be downloaded at https://github.com/dotnet/coreclr

.CoreFX: is a set of resources like base type, collections, threads,…You can read more at https://github.com/dotnet/coreclr

CoreCLR and CoreFX are inseparable things in order to run your program correctly. The first is the runtime which manages the execution environment, memory management, garbage collector,… and the second is where the first can find resources’ type – when the program needs to create an integer type, it can be found the integer structure inside the CoreFX not in the CoreCLR.

As said so far, .NET Core is a cross-platform environment. Each supported platform has its own version of the coreCLR and CoreFX.

Create .NET Core apps for Linux and Windows

To understand how those things are used in real life, we’ll show you how to create your first .NET Core application, generate executable for both Windows and Linux platforms. We suppose that you already have Visual Studio 2015 Community

1. Create the project

Go to File > New > Project

In the New Project windows

_net_src5

The default solution looks like to the figure below

_net_src6

There’s only two files in the solution:

Program.cs: contains the main entry for our program.

using System;
namespace MyFirstNetCoreApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console .WriteLine("Hello .NET Core app");
	    Console .ReadLine();
        }
    }
}

Nothing’s particular in this file, it only displays a text to the console yet.

project.json: is now the new file where we declare dependencies, versions etc…

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.1"
    }
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  }
}

Those stuffs were before located in the file .csproj (or vbproj). They were in XML format and parsed with the MsBuild utility during the build time. With .NET Core, engineer’s choice goes for JSON format.

Tips: The Visual Studio auto-completion still be available in the new JSON format.

Multi-targeting:

The actual project.json file is targeting the coreCLR with the lines:

"frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  }

The “dependencies” section is applicable at a global level, the modified file below shows a nested dependency which only apply for the .NET Core version. We also introduced two new targets which are the .NET framework 4.5.2 and the former .NET Framework 3.5

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },
  "dependencies": {},

  "frameworks": { 
    "netcoreapp1.0": {
      "imports": "dnxcore50",
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.1"
        }
      }
    },
    "net452": {},
    "net35": {}
  }
}

You can read more about target-frameworks at

https://docs.nuget.org/ndocs/schema/target-frameworks

Tips: Each time the project.json file is modified, Visual studio is calling the CLI tools “dotnet” to sync the dependencies according to the current content of the json file. It actually calls the command “dotnet restore” which may remove all unused dependencies or try to resolve newly added dependencies.

We can see that in the figure below

_net_src7

The output window also shows what operation was performed during the restore process.

_net_src8

Note: If you expand the project.json node, you will see an auto-generated file named project.lock.json.

You shouldn’t directly modify this file because it is used internally by the dotnet command utility.

Building apps for multi-targeting framework

The build process generates as many as executable there’s targeted frameworks

_net_src11

They can be found in the bin/Debug directory

_net_src12

If you look inside the net35 and net452 folders, the build process generates the application files which are the executable files. In .NET Core, there’s no longer any .exe files. Instead, we have a .dll file extension.

Running the application

Before you run the application, you have to define the default framework since there are no multiple choices yet.

_net_src9

In the above figure, we’ve selected .NET Core (.NETCoreApp, Version=v1.0). Once selected, we can fire by clicking the green arrow.

Running from command line

Open a command line and go to the folder containing the .NET Core dll, then

dotnet MyFirstNetCoreApp.dll

_net_src13

How to publish .Net Core apps to Linux platforms ?

One of the reasons we use .NET Core is the portability. Therefore we can publish a Linux binary of our app.

We need to do the following steps:

1- Modify the project.json

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },
  "dependencies": {},

  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50",
      "dependencies": {
        "Microsoft.NETCore.App": {
          // "type": "platform",
          "version": "1.0.1"
        }
      }
    },
    "net452": {},
    "net35": {}
  },
  //Go to https://docs.microsoft.com/en-us/dotnet/articles/core/rid-catalog for all available RID
  // or here for the lastest version
  //https://github.com/dotnet/corefx/blob/master/pkg/Microsoft.NETCore.Platforms/runtime.json
  "runtimes": {
    "ubuntu.16.04-x64": {},
    "win81-x64": {}
  }
}

 

We remove first the directive type:platform and add the “runtimes” key where we enumerate all targeted platforms: ubuntu 16.04 (Xenial) and windows 8.1 64 bits in our case. By removing the key [type:platform], we instruct to the compiler that this will become a self-contained app – all needed components will be copied into a final package.

Configure the publishing process

Right click the project > Publish

_net_src14

Select filesystem as publish target and give it a profile name

_net_src15

Select the Target location then Next

_net_src16

Select .NETCoreApp, Version=v1.0 as the target framework

Select ubuntu.16.04-x64 as the target runtime

You can notice that all runtimes configured in the project.json file are listed here

_net_src17

Click the Next button

_net_src18

Finally, you can publish the project.

If something goes wrong, you can always use the CLI to manually publish your app.

Publishing .NET Core cross-platform app using CLI command dotnet

1-Open a console (a powershell console is better)

2-Make the app folder as the console working directory (at the same level as project.json file)

3-Run the following commands:

dotnet restore
dotnet build
dotnet publish -r ubuntu.16.04-x64

A publish directory is now created at

C:\Users\dev\MyFirstNetCoreApp\bin\Debug\netcoreapp1.0\ubuntu.16.04-x64\publish

It contains all components to make self-contained apps, the size (~55MB) is quite high compared to any .NET Framework assembly.

You can copy this file to a Ubuntu workstation and the program can be run with using the following shell command (using the same CLI command)

dotnet MyFirstNetCoreApp.dll

The app executed on Ubuntu workstation

_net_src19

Note: In order to export to a specific platform, we should check if it exists at https://github.com/dotnet/corefx/blob/master/pkg/Microsoft.NETCore.Platforms/runtime.json

The platform name is case sensitive so beware of mistype.

Troubleshoots:

If you encounter an error like this

Error : Could not find a part of the path ‘C:\Users\dev\MyFirstNetCoreApp\bin\Realese\netcoreapp1.0\ubuntu.16.04-x64\MyFirstNetCoreApp.dll’, you can manually create the missing folder (eg. ubuntu.16.04-x64)

 

Building .NET Core app with Linux step by step

As we’ve seen so far .NET Core is designed to run on any platforms and will allow developing on any platforms too. That was impossible with .NET Framework since it is the only support Microsoft Windows platforms.

It’s now time to you developers to do your first step in Linux environment. We’ll show you how to setup your development box step by step. We’ll choose the Ubuntu Linux distro 16.04 LTS. Don’t mind if you have a different distribution, the process is almost the same.

Installing .NET Core on Ubuntu

This process only involve a couple of steps

1- Update your source library by updating your /etc/apt/source.list

2- Install .NET Core package

3- Check the installation

Step 1: The official package are hosted at https://apt-mo.trafficmanager.net/repos/dotnet-release/

If you open to the previous URL you will see a folder named dists which contain three inner folders Trusty, Xenial and Yakkety. Each of them corresponds to a specific ubuntu version: Trusty is for Ubuntu 14.04, Xenial for Ubuntu 16.04 and Yakkety for Ubuntu 16.10. Future Ubuntu distribution may be added to this folder.

In our case, we have the Xenial version, so we copy and append the following text at the end of the /etc/apt/source.list

deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ xenial main

Note: Be sure you have the permission to modify this file. If not, you have to use sudo command (see below)

You can also use the following command line:

sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ xenial main" &amp;amp;amp;gt;&amp;amp;amp;gt; /etc/apt/sources.list'

 

Update the package source repository by the command

sudo apt-get update

 

It may take a while to fetch all package’s metadata.

Step 2: Install the .NET Core

Let’s now list all dotnet available packages. Run the command

sudo apt-cache search dotnet

_net_src32

At the time of writing, the stable version is dotnet-dev-1.0.0-preview2-1-003177

We install the .NET Core 1.1.0 Sdk by the following command (CoreCLR)

sudo apt-get install dotnet-dev-1.0.0-preview2-1-003177 -y --allow-unauthenticated

This command downloads and installs the dotnet package into our system.

Step 3:Checking the installation
On a command shell, enter:

dotnet --version

If everything goes well, you should have

_net_src20

Note: the dotnet command is officially named the driver of the .NET Core Command-Line interface (CLI). It is now the new utility to manage the .NET Core processing. The former utilities are:
-dnvm : utility that manages the .NET component version on the host
-dnu : Dotnet utility to resolve references, build and compile source code
-dnx : dotnet excecution environement, run the compiled source code ( creates the runtime environment, GC…)

Run the first app

You can run your first ‘Hello world’ app by the following command sequences:

You create the new working directory MyFirstDotNetCoreApp

mkdir ~/MyFirstDotNetCoreApp
cd&amp;nbsp;~/MyFirstDotNetCoreApp/

Create the minimal project files : Program.cs and project.json

dotnet new

The project.json file contains references and resolve dependencies ( in the same way that the file *.csproj did in classical .NET app). Get all references mentioned in the file. This command should be executed after each modification on the file project.json

dotnet restore

Compile and run

dotnet run

The GAC in .NET Core

The Global Assembly Cache is a well-known component for .NET developers. It is where all assemblies are located. On windows it is located at C:/windows/Assembly, assembly need to be loaded into the GAC in order to be callable and usable by a program. The GAC is very specific to windows so it can’t be used in cross-platform environment. That’s why it’s no longer apply in the .NET Core world. Instead the .NET Core created a hidden folder .dnx in the current user profile.

Installing the .NET Core IDE

The next question coming into developer’s mind is about IDE. Visual studio is only for windows computer. Hopefully, there’s now Visual Studio Code. It is free, cross-platform (run on windows, Linux as well as on OSX), lightweight, open-source IDE that allows editing and debugging .NET Core program on any OS.

The first step is to go to https://www.visualstudio.com/

Then click to Visual Studio Code link to go to the download page.

Download the suitable package for your system. In this tutorial, we choose the .deb package because we’re using an Ubuntu distribution.

The installation process is pretty simple

_net_src21

After the installation finishes up, you can access the icon launch as follows

_net_src22

The default Visual Studio Code IDE

_net_src23

You can add extensions to Visual Studio Code IDE by clicking the icon extension or Ctrl+Shift+X shortcut.

We add the C# extension

_net_src24

Then click the reload button to activate the new extension

_net_src25

Tips : The extensions marketplace is at https://marketplace.visualstudio.com/vscode. You can find here a lot of tools that can improve your productivity.

You’ve got all the stuffs you expect for an IDE: coloring, formatting, auto completion

Create a .NET Core project from Visual Code

At the time of writing, Visual Code has only few options in term of project creation.

_net_src26

If you have already an existing .NET Core project, you can use the “Open Folder” button to load the whole project into the IDE. In our case, we’re going to start from scratch so we have to create an initial folder first – outside Visual Studio Code. This folder will contain the main file Program.cs and the project.json file which is required for any .NET Core apps. They are the minimal required files.

Hopefully, for us, the CLI “dotnet” utility can create a minimal default app.
Open a shell command and type

cd /tmp
mkdir AppUbuntu
cd AppUbuntu
dotnet new
ls
dotnet restore 
ls

_net_src27

The initial project folder has been created, we can open it now from Visual Studio Code

_net_src28

The first time you open the project, you have to click on “Yes” to allow the auto configure of your IDE.

You can now run the program

_net_src30

First of all, you need to enter in debug mode. Then we need to select the runtime type. .NET Core launch (console) is the right choice and we can finally launch by clicking the debug start button.

You’ve seen how to start a .NET Core app development under Linux using Visual Studio Code. At the time of writing, Visual Studio Code is fully functional but there’s a lot of improvements to be done.

In the following section, we’ll take a tour with Mono project, an alternative to build .NET apps primarily under Linux.

The Mono project.

Mono is an open-source project intending to build cross-platform .NET Framework based applications. It comes with it’s own C# compiler and a runtime environment under the MIT license. Mono offers some interesting features:
– Binary compatibility: you can import CLR compliant executables or libraries, just add them as a reference into your Mono project and directly use them without any modifications and vice-versa.
This is possible because Mono was built on an implementation of the ECMA’s Common Language Infrastructure.
– Microsoft Compatible API: major .NET Framework components (ASP.NET, ADO.NET, Windows Forms) can run without recompilation
– C# from 1.0 to 5.0 full feature complete ( full support of Linq, dynamic,…)
– Mono SDK is available on Windows, Linux, OSX,BSD,…
– Available in x86, x64, ARM, power pc,… architectures

However, there are some compatibility limitations which are:
– Windows Presentation Foundation (WPF), Windows Workflow Foundation (WWF) are not supported at all
– Limited supports on Windows Communication Foundation (WCF)
– Limited supports on Asp.net 4.5 async task.
– If you’re using MVC4 or MVC5, some features aren’t working yet.

Before choosing Mono, be sure you read the compatibility pages at http://www.mono-project.com/docs/about-mono/compatibility/

Install Mono on linux Ubuntu 16.04

The “mono-complete” package contains the complete runtime, development tools and libraries. This process may take a while

apt-get install mono-complete 

Mono-develop is a full IDE available on Linux

apt-get install mono-develop 

_net_src31

Mono-develop is a complete IDE offering nice editing capabilities. An alternative is to use Xamarin studio.

The Mono-develop IDE is also very intuitive. If you’re ok with Visual Studio, working with Mono-develop is as well as simple too.

The chart below shows utilities to build and run .NET programs according the targeted version.

Tools

.NET version

.NET Framework

.NET Core

Mono

Build/Compile

csc

dotnet build

mcs

Run

cs

dotnet

mono

 

We’ve seen along this tutorial a quick tour on three independent technologies around Microsoft .NET :

– .NET Framework

– .NET Core

– the .NET Mono project

At the time of writing, .NET Framework is definitely the most stable, the most complete, the most used in enterprise solutions and will be for the next years. However, developers need to think on .NET Core possibilities when cross-platform applications are required, it is a good alternative to .NET Framework. You can also consider the Mono project if you mostly work on Linux workstation. Before making a definitive choice on the framework, it is always advised to stay tuned with the latest features. The .NET Core roadmap can be found at https://github.com/dotnet/core/blob/master/roadmap.md

 

 

The post .NET versions: review .net version (Mono, Core, etc) and what are the key differences appeared first on ByteScout.

Extracting data from tables in PDF

$
0
0

This article aims to show how to extract data  from PDF files including text, image, audio, video using C#. We all know that PDF format became the standard format in document exchanges and PDF documents are suitable for reliable viewing and printing of business documents. Almost of all office softwares like Microsoft Office, LibreOffice or OpenOffice.org had integrated the PDF format into them and them all had implemented the very useful feature known as “Export to PDF”. So exporting to a pdf file is now very easy, but what about the inverse process?
Let’s consider that you’ve received a document in PDF format and want to extract some information from it. At a first glance, the task seems to be quite easy with just copying from the document source and pasting it somewhere else. But thing becomes complicated when you’re dealing with a lot of data, this tremendous process will make your work life awful. Facing to that it’s appropriate to use dedicated tools or specialized frameworks to automate the whole of the job. Not only they will improve your productivity but also save your time. This article has four main sections:
– PDF extract data from tables
– Extract data from scanned docs
– Extract data with OCR
– Extract rich media contents

Extract PDF data from tables

Extract data from pdf tables with Adobe Acrobat Pro DC

As it’s name implies, Adobe Acrobat is a commercial app made by Adobe and it is the first and the official software to work with PDF files. You can download the 7 days trial version at https://acrobat.adobe.com/us/en/free-trial-download.html. At the time of writing, the released version is Adode Acrobat Pro DC 2015 Release.

You also have to download our case study files here (sample1) . It’s content looks like below

The table contain daily historical Microsoft and Facebook stock prices and volumes from the Nasdaq public website.

We need to manually extract the table’s content and export it to different formats like CSV, TXT,….

Step 1: Open the PDF file

In Adobe Acrobat Pro DC > File > Open

Step 2: Locate the table from which you want to extract data and drag a selection over the table as shown below

Step 3: Right click and select “Export Selection As…”

Step 4: Choose the export type

Adobe Acrobat Pro DC can handle up to 8 different formats:

  • – Word Document (*.docx)
  • – Word 97-2003 Document (*.doc)
  • – Excel Workbook (*.xlsx)
  • – PowerPoint Presentation *(*.pptx)
  • – Rich Text Format (*.rtf)
  • – XML Spreadsheet 2003 (*.xml)
  • – HTML (*.html, *.htm)
  • – Comma Separated Values (*.csv)

The exported CSV file looks like


"Date","Open","High","Low","Close / Last","Volume"
2017-01-04T00:00:00.000,62.48,62.75,62.12,62.3,21325140
2017-01-03T00:00:00.000,62.79,62.84,62.125,62.58,20655190
2016-12-30T00:00:00.000,62.96,62.99,62.03,62.14,25575720
2016-12-29T00:00:00.000,62.86,63.2,62.73,62.9,10248460
2016-12-28T00:00:00.000,63.4,63.4,62.83,62.99,14348340
2016-12-27T00:00:00.000,63.21,64.07,63.21,63.28,11743650
2016-12-23T00:00:00.000,63.45,63.54,62.8,63.24,12399540
2016-12-22T00:00:00.000,63.84,64.1,63.405,63.55,22175270
2016-12-21T00:00:00.000,63.43,63.7,63.12,63.54,17084370
2016-12-20T00:00:00.000,63.69,63.8,63.025,63.54,26017470
2016-12-19T00:00:00.000,62.56,63.77,62.42,63.62,34318500
2016-12-16T00:00:00.000,62.95,62.95,62.115,62.3,42452660

Adobe Acrobat Pro is the most powerful tools to manipulate PDF files. In few words, you can do whatever you want with your pdf file with it – except some limitations that we’re going to see at section 4 (dealing with rich media content).

Extract data manually with Adobe Reader

Adobe Reader PC is a simple software to read PDF files. It has some limitations compared to it’s counterpart Adobe Acrobat Pro. However, you can do some basic stuffs like copying table’s contents and pasting it into your favorite spreadsheet app.

Step 1: Open the file with Adobe Reader

Step 2: Select the table’s content by dragging any desired rows and columns

Step 3: Open your favorite spreadsheet app and paste the selection into it, we’re using LibreOffice Calc in this article

As seen in the figure below, we have to define column delimiter in order to correctly display the content.

Step 4: Click OK

Using our spreadsheet software, we can then export to many other formats. In our case, LibreOffice gives us 15 available formats.

Abode Reader is not as flexible as Adobe Acrobat Pro, it hasn’t actually no export features. It’s main utility is to visualize, to print and to fill out PDF documents.

The two previous sections show you two ways to manually extract data from tables. They both are working well and are very useful for small loads. The next section will show you how to extract data from PDF tables using programming tools. We will focus essentially on PDK Extractor SDK.

Extracting data from PDF tables using C#

Prerequisites

In order to run all the following programs, you have to install the PDF Extractor SDK. You can download it at https://bytescout.com/products/developer/pdfsdk/index.html

PDF Extractor SDK (https://bytescout.com/products/developer/pdfextractorsdk/index.html) is one of Bytescout’s products. It allows developers to convert/extract data from PDF and export them to other formats. This is important to know that we can do that without any additional softwares required unlike the actual Adobe SDK which mandatory needs Adobe Acrobat software to be installed.

After installing PDF Extractor SDK, all requisites dll can be found in the folder C:\Program Files\Bytescout PDF Extractor SDK

.NET Compatibility

PDF Extractor SDK supports the following .NET Frameworks:

  • .NET Framework 2.0
  • .NET Framework 3.5 / .NET Framework 3.5 Client Profile
  • .NET Framework 4.0 / .NET Framework 4.0 Client Profile

You then need to do “add a reference” to Bytescout.PDFExtractor.dll library.

PDF Extractor SDK, how does it works?

Prior to any data extraction processes, we need to locate the targeted table among all the tables in the PDF document. This task is done by the Bytescout.PDFExtractor.TableDetector object which can loop over existing tables in the document.

The program below shows how to locate the N-th table (targetTableNumber variable) in the P-th page (targetPageNumber variable) of the whole PDF document.

using Bytescout.PDFExtractor;

namespace Topic4.Sample1.TableDetectorSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //The path of the PDF file
            var pdfFile = @"sample1.pdf";

	    // this is the index of the page containing the targeted table
            int targetPageNumber = 1;

            // this is the value of the table we are looking for, 1 or 2 in the current example
            int targetTableNumber = 1;

            // Create an instance of a TableDetector
            TableDetector tdetector = new TableDetector();

            // License informations here
            tdetector.RegistrationKey = "demo";
            tdetector.RegistrationName = "demo";
          
            // Load the document file
            tdetector.LoadDocumentFromFile(pdfFile);

            // Count the number of pages in the actual PDF file
            int pageCount = tdetector.GetPageCount();            

            // Loop over document pages ...
            for (int i = 0; i&amp;amp;amp;lt; pageCount; i++)
            {

                //... we are only interested in the targetPageNumber-th page
                if (targetPageNumber != (i + 1)) continue;

                //... if tables are found in the current page...
                if (tdetector.FindTable(i))
                {
                    int tableLoopNumber = 1;
                
                    //... loop over the tables in the current page ...
                    do
                    {
                        if (tableLoopNumber == (targetTableNumber-1))
                        {
                    
                            //... targetTableNumber-th table in the targetPageNumber-th page is here
                            break;
                        }

                        tableLoopNumber++;
                    }
                    while (tdetector.FindNextTable());
                }
            }
        }
    }
}

Filters:

The TableDetector class offers some useful properties to filter the search:

  •  DetectionMinNumberOfColumns
  •  DetectionMinNumberOfRows

After locating the right table, we want to gather some data from it. This is achieved by an instance of extractor class: CSVExtractor, TextExtractor, JSONExtractor, XLSExctrator,…

Export PDF table to CSV format with C#

We need to export the first PDF table of our case study document to CSV format. The previous program is updated as following

using Bytescout.PDFExtractor;

namespace Topic4.Sample1.TableDetectorSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //The path of the PDF file
            var pdfFile = @"sample1.pdf";
            
            // this is the index of the page containing the targeted table
            int targetPageNumber = 1;

            // this is the value of the table we are looking for, 1 or 2 in the current example
            int targetTableNumber = 1;

            //Create an instance of a TableDetector
            TableDetector tdetector = new TableDetector();

            //License informations here
            tdetector.RegistrationKey = "demo";
            tdetector.RegistrationName = "demo";

            //Add some filters. Only tables meeting those criterias are considered
            tdetector.DetectionMinNumberOfColumns = 1;
            tdetector.DetectionMinNumberOfRows = 10; 

            //Load the document file
            tdetector.LoadDocumentFromFile(pdfFile);

            //Count the number of pages in the actual PDF file
            int pageCount = tdetector.GetPageCount();

           

            //Loop over document pages ...
            for (int i = 0; i&amp;amp;amp;lt; pageCount; i++)
            {

                //... we are only interested in the targetPageNumber-th page
                if (targetPageNumber != (i + 1)) continue;

                //... if tables are found in the current page...
                if (tdetector.FindTable(i))
                {
                    int tableLoopNumber = 0;

                    //... loop over the tables in the current page ...
                    do
                    {
                        if (tableLoopNumber == (targetTableNumber-1))
                        {

                            //Process the targetTableNumber-th table in the targetPageNumber-th page
                            

                            //Create the csv extractor object, set license information
                            CSVExtractor extractor = new CSVExtractor();                            
                            extractor.RegistrationName = "demo";
                            extractor.RegistrationKey = "demo";

                            //set the csv separator symbol - default value is comma
                            extractor.CSVSeparatorSymbol = ";";                            

                            //Load the pdf file into the extractor object
                            extractor.LoadDocumentFromFile(pdfFile);

                            // set extraction area for CSV extractor to rectangle given by table detector
                            extractor.SetExtractionArea(
                                tdetector.GetFoundTableRectangle_Left(),
                                tdetector.GetFoundTableRectangle_Top(),
                                tdetector.GetFoundTableRectangle_Width(),
                                tdetector.GetFoundTableRectangle_Height()
                            );

                            //Three methods to extract the table's content as csv 
                           
                            //returns a string using GetCSV method
                            string result_csv1 = extractor.GetCSV();

                            //returns a string using GetCSVFromPage method, page index is given as input parameter
                            string result_csv2 = extractor.GetCSVFromPage(targetPageNumber - 1);

                            // or directly save to the file system
                            extractor.SavePageCSVToFile(tableLoopNumber, "page-" + targetPageNumber + "-table-" + targetTableNumber + ".csv");

                            break;
                        }

                        tableLoopNumber++;
                    }
                    while (tdetector.FindNextTable());
                }
            }
        }
    }
}

Once the table is located, we create an extractor object to define the area inside which we want to extract data and the final csv looks like


"Date";"Open";"High";"Low";"Close / Last";"Volume";
"01/04/2017";"117.55";"119.66";"117.29";"118.69";"19,594,560";
"01/03/2017";"116.03";"117.84";"115.51";"116.86";"20,635,600";
"12/30/2016";"116.595";"116.83";"114.7739";"115.05";"18,668,290";
"12/29/2016";"117";"117.531";"116.06";"116.35";"9,925,082";
"12/28/2016";"118.19";"118.25";"116.65";"116.92";"11,985,740";
"12/27/2016";"116.96";"118.68";"116.864";"118.01";"12,034,590";
"12/23/2016";"117";"117.56";"116.3";"117.27";"10,885,030";
"12/22/2016";"118.86";"118.99";"116.93";"117.4";"16,226,770";
"12/21/2016";"118.92";"119.2";"118.48";"119.04";"10,747,610";
"12/20/2016";"119.5";"119.77";"118.8";"119.09";"13,673,570";
"12/19/2016";"119.85";"120.36";"118.51";"119.24";"15,871,360";
"12/16/2016";"120.9";"121.5";"119.27";"119.87";"25,316,220";

Extract PDF table column with C#

The next program shows how to extract a specific column from a given table.

The class Bytescout.PDFExtractor.TextExtractor is used to locate a specific text pattern in the PDF document. Then we define the extraction area and finally save the column content in a text file.

Bytescout.PDFExtractor.TextExtractor class is not only limited to PDF files, it can locate and extract text from PNG, JPEC, BMP, TIFF files.

We also need to add the System.Drawing (because we’re using the RectangleF class) assembly to our project.

using Bytescout.PDFExtractor;
using System.Drawing;

namespace Topic4.Sample1.TextExtractorSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //The path of the PDF file
            var pdffile = "sample1.pdf";

            // this is the index of the page containing the targeted table
            int targetPageNumber = 1;

            // this is the value of the table we are looking for, 1 or 2 in the current example
            int targetTableNumber = 1;

            //Create an instance of a TableDetector
            TableDetector tdetector = new TableDetector();

            //License informations here
            tdetector.RegistrationKey = "demo";
            tdetector.RegistrationName = "demo";

            //Add some filters. Only tables meeting those criterias are considered
            tdetector.DetectionMinNumberOfColumns = 1;
            tdetector.DetectionMinNumberOfRows = 10;

            //Load the document file
            tdetector.LoadDocumentFromFile(pdfFile);

            //Count the number of pages in the actual PDF file
            int pageCount = tdetector.GetPageCount();



            //Loop over document pages ...
            for (int i = 0; i &amp;amp;amp;lt; pageCount; i++)
            {

                //... we are only interested in the targetPageNumber-th page
                if (targetPageNumber != (i + 1)) continue;

                //... if tables are found in the current page...
                if (tdetector.FindTable(i))
                {
                    int tableLoopNumber = 0;

                    //... loop over the tables in the current page ...
                    do
                    {
                        if (tableLoopNumber == (targetTableNumber - 1))
                        {                            
                           
                            //use a text extractor in order to extract text from the pdf document
                            TextExtractor extractor = new TextExtractor();
                            extractor.RegistrationName = "demo";
                            extractor.RegistrationKey = "demo";

                            // Load sample PDF document
                            extractor.LoadDocumentFromFile(pdfFile);

                            // set to extract text column by column
                            extractor.ExtractColumnByColumn = true;                         

                            //Try to locate the "Close / Last" column header in the current page 
                            bool close_last_header_found = extractor.Find(targetPageNumber - 1, "Close / Lasts", true);

                            //if found
                            if (close_last_header_found)
                            {
                                // Retrieve the boundary of the text
                                RectangleF rectangle = extractor.FoundText.Bounds;

                                //Set the selection area of the extractor                               
                                extractor.SetExtractionArea(
                                    rectangle.Left
                                    , rectangle.Top
                                    , rectangle.Width
                                    , rectangle.Height * 20
                                    );
                                //Save to file
                                extractor.SaveTextToFile("output.txt");

                                //Dispose
                                extractor.Dispose();                              
                            }
                            break;
                        }

                        tableLoopNumber++;
                    }
                    while (tdetector.FindNextTable());
                }
            }
        }
    }
}

The content of the result file looks like:

Close / Last
62.3
62.58
62.14
62.9
62.99
63.28
63.24
63.55
63.54
63.54
63.62
62.3

More generally, the class Bytescout.PDFExtractor.TextExtractor uses a rectangle surface called extraction area. The extraction area is well defined by using four parameters:

  •  the left and top coordinates are used to locate to topleft corner of the extraction area
  •  the width is used to set the width of the extraction area
  •  the height parameter specifies the height of the extraction area

Only texts standing inside the extraction area are going to be gathered during the extraction phase.

 Parsing PDF table cell by cell with C# PDF API

With PDF Extractor SDK, we can navigate through the table’s cells using the Bytescout.PDFExtractor.StructuredExtractor class in the way of enumerating a matrix structure. The following program shows how to do that

using Bytescout.PDFExtractor;
using System;

namespace Topic4.Sample1.TableStructureSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //The path of the PDF file
            var pdfFile = "sample1.pdf";
            
            // this is the index of the page containing the targeted table
            int targetPageNumber = 1;
           
            // Create Bytescout.PDFExtractor.StructuredExtractor instance (former TableExtractor)
            StructuredExtractor extractor = new StructuredExtractor();
            extractor.RegistrationName = "demo";
            extractor.RegistrationKey = "demo";

            // Load sample PDF document
            extractor.LoadDocumentFromFile(pdfFile);

            //Define the extraction area
            extractor.SetExtractionArea(new System.Drawing.RectangleF(20,380,600,200));
            
            for (int ipage = 0; ipage &amp;amp;amp;lt;extractor.GetPageCount(); ipage++)
            {
                //In the current program, we only need the first page
                if ((ipage + 1) != targetPageNumber) continue;

                //Prepare the page structure
                extractor.PrepareStructure(ipage);

                //Count the actual table rows 
                int rowCount = extractor.GetRowCount(ipage);
                int CellsAlreadyScanned = 0;

                //Loop over the row count...
                for (int row = 0; row &amp;amp;amp;lt; rowCount; row++)
                {
                    // ...then loop over the column
                    int columnCount = extractor.GetColumnCount(ipage, row);

                    for (int col = 0; col&amp;amp;amp;lt; columnCount; col++)
                    {
                        //The text of the table cell[row,col]
                        var cellValue = extractor.GetCellValue(ipage, row, col);                        
                        Console.Write(string.Format("{0}\t", cellValue));
                    }
                    Console.WriteLine("\n");
                    CellsAlreadyScanned += columnCount;
                }
            }
            Console.WriteLine("Press any key..");
            Console.ReadKey();
        }
    }
}

The program output is

PDF table To JSON using C#

The following program shows how to extract data from PDF table and save them as a json file using the Bytescout.PDFExtractor.JSONExtractor class. We can also retrieve some metadata (like font name,font size, font style and position) informations in addition to the actual cell content value.

using Bytescout.PDFExtractor;

namespace Topie4.Sample1.JsonExtractorSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //The path of the PDF file            
            var pdfFile = @"sample1.pdf";

            // this is the index of the page containing the targeted table
            int targetPageNumber = 1;

            // this is the value of the table we are looking for, 1 or 2 in the current example
            int targetTableNumber = 1;

            //Create an instance of a TableDetector
            TableDetector tdetector = new TableDetector();

            //License informations here
            tdetector.RegistrationKey = "demo";
            tdetector.RegistrationName = "demo";

            //Add some filters. Only tables meeting those criterias are considered
            tdetector.DetectionMinNumberOfColumns = 1;
            tdetector.DetectionMinNumberOfRows = 10;

            //Load the document file
            tdetector.LoadDocumentFromFile(pdfFile);

            //Count the number of pages in the actual PDF file
            int pageCount = tdetector.GetPageCount();



            //Loop over document pages ...
            for (int i = 0; i &amp;amp;amp;lt; pageCount; i++)
            {

                //... we are only interested in the targetPageNumber-th page
                if (targetPageNumber != (i + 1)) continue;

                //... if tables are found in the current page...
                if (tdetector.FindTable(i))
                {
                    int tableLoopNumber = 0;

                    //... loop over the tables in the current page ...
                    do
                    {
                        if (tableLoopNumber == (targetTableNumber - 1))
                        {
                            //Process the targetTableNumber-th table in the targetPageNumber-th page


                            //Create the csv extractor object, set license information
                            JSONExtractor extractor = new JSONExtractor();
                            extractor.RegistrationName = "demo";
                            extractor.RegistrationKey = "demo";
                           
                            //Load the pdf file into the extractor object
                            extractor.LoadDocumentFromFile(pdfFile);

                            // set extraction area for CSV extractor to rectangle given by table detector
                            extractor.SetExtractionArea(
                                tdetector.GetFoundTableRectangle_Left(),
                                tdetector.GetFoundTableRectangle_Top(),
                                tdetector.GetFoundTableRectangle_Width(),
                                tdetector.GetFoundTableRectangle_Height()
                            );
                          
                            // or directly save to the file system
                            extractor.SaveJSONToFile(tableLoopNumber, "page-" + targetPageNumber + "-table-" + targetTableNumber + ".json");

                            break;
                        }

                        tableLoopNumber++;
                    }
                    while (tdetector.FindNextTable());
                }
            }
        }
    }
}

The result looks like

            {
             "text": {
                "@fontName": "Times",
                "@fontSize": "12.0",
                "@x": "59",
                "@y": "105",
                "@width": "54",
                "@height": "12",
                "#text": "01/04/2017"
              }
            },
            {
              "text": {
                "@fontName": "Times",
                "@fontSize": "12.0",
                "@x": "193",
                "@y": "105",
                "@width": "27",
                "@height": "12",
                "#text": "62.48"
              }
            }

Extract PDF table to XML using C#

The same process as exporting to JSON applies here. Instead of using JSONExtractor class we have to use XMLExtractor class. To save the XML into the file system we call the method XMLExtractor.SaveXMLToFile

Extract data from scanned documents / OCR

The rest of this article is about extracting data from scanned documents and OCR capabilities. We’ll see how to extract data with Adobe Acrobat DC and we’ll also see how to handle the data extraction process using C# and PDF Extractor SDK.

You can find below five scanned files that we’re going to use.

scan_sample1_600dpi_normal.pdf : document scanned at 600 dpi

scan_sample1_600dpi_handwritingnote.pdf : document scanned at 600dpi with handwriting note at the bottom of the page

scan_sample1_70dpi_handwritingnote.pdf: document scanned at 70 dpi with handwriting note

scan_sample1_600dpi_badqualityprinting.pdf : printed with a very poor quality and scanned at 600dpi

scan_sample1_600dpi_badorientation.pdf : scanned at 600dpi with bad orientation during the scan process

Extract data with Adobe Acrobat DC

When we open the pdf scanned file with Adobe Acrobat DC, we see that it automatically tries to convert the page to editable contents. It pops out the message below

Once the pattern recognition is done each cell of our table becomes editable. More generally Adobe Acrobat DC has a powerful built-in OCR to automatically detect characters and texts inside the scanned page.

We can then export the modified document to many other formats.

Go to File > Export To >

You can download here the “Text (Plain)” version of our document

Extract data from scanned document with poor quality of printing and handwriting note

The corresponding demo file is scan_sample1_70dpi_handwritingnote.pdf. The specificity of this file is that the scan is done at low resolution 70 dpi and having a handwriting note at the bottom of the table.

Despite of the low accuracy of the OCR at 70 dpi, the major part of the data has been well reconstructed. However, it seems to have a trouble to detect all cell borders, the result file is available here. The pattern recognition over the handwriting note had also failed.

The same process applied to the same document scanned at 600dpi is very accurate. The extraction process has performing well and all of the cells data are successfully gathered (here)

The file scan_sample1_600dpi_badqualityprinting.pdf (scan at 600 dpi with poor ink quality) had definitely failed through the extraction process. Adobe Acrobat DC didn’t recognized any patterns and had  considered it as a blank page.

The last file we’re trying to extract is scan_sample1_600dpi_badorientation.pdf. The particularity of this file is the bad orientation during the scan process.

However Adobe Acrobat automatically adjusts the document page orientation during the pattern recognition process as seen in the figure below

The data extraction result is available here We can see that almost all of the data are well retrieved.

Extract data with OCR from scanned documents using C# and PDF Extractor SDK

The following program extracts data from the pdf document file scanned at 600dpi under normal conditions

using Bytescout.PDFExtractor;

namespace OCRExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var pdfFile = @"scan_sample1_600dpi_normal.pdf";
            
            // Create Bytescout.PDFExtractor.TextExtractor instance
            JSONExtractor extractor = new JSONExtractor();
            extractor.RegistrationName = "demo";
            extractor.RegistrationKey = "demo";

            //Load the pdf document file
            extractor.LoadDocumentFromFile(pdfFile);

            //We are only interested in text
            extractor.OCRMode = OCRMode.TextFromImagesAndFonts;
            
            //Define the language data folder
            extractor.OCRLanguageDataFolder = @"C:\\Program Files\\Bytescout PDF Extractor SDK\\net4.00\\tessdata\\";
            
            //The actual language is eng for english
            extractor.OCRLanguage = "eng";

            //We set the resolution to 600dpi
            extractor.OCRResolution = 600;

            //Save the file
            extractor.SaveJSONToFile("OCR_JSON_scan_sample1_600dpi_normal.json");
            
        }
    }
}

For each pattern, the OCR engine associates the property named @OCRConfidence which indicates how good or bad the recognition was, higher the value more accurate is the result. The OCR engine also returns the predicted font name, the size, the coordinate of the data, it’s width and height in the PDF document and the text value of course.

The figure below shows a partial output

{
              "text": {
                "@fontName": "Times",
                "@fontSize": "30.0",
                "@OCRConfidence": "66.82",
                "@x": "184",
                "@y": "542",
                "@width": "32",
                "@height": "29",
                "#text": "115.921"
              }
            },
            {
              "text": {
                "@fontName": "Times",
                "@fontSize": "8.0",
                "@OCRConfidence": "86.21",
                "@x": "268",
                "@y": "555",
                "@width": "168",
                "@height": "8",
                "#text": "1192 ."
              }
            }

The OCR uses a set of language libraries (located at C:\\Program Files\\Bytescout PDF Extractor SDK\\net4.00\\tessdata\\ ), the default installation contains four languages: english,german, french and spanish. The property JSONExtractor. OCRLanguageDataFolder is set to the actual language of the document. The OCR process is active when the property JSONExtractor.OCRMode is different than OCRMode.Off. We can also apply multiple preprocessing algorithms to the OCRImagePreprocessingFilters property of the extractor object to help the OCR Engine to give better pattern recognition performance. We can mix between the following methods AddContrast(), AddDeskew(),AddDilate(), AddGammaCorrection(), AddHorizontalLinesRemover(), AddMedian(), AddVerticalLinesRemover(). According to the case, the time process may vary from a few seconds to one minute or even more per page.

Extract rich media contents with Adobe Acrobat DC

In the Adobe Acrobat glossary, rich media are audio and video contents. They can be a 3D animation, an audio file, a flash SWF animation or a video file in H264 compilant format. At the time of writing, extracting rich media contents isn’t a supported feature, this is one of the major lacks of Adobe Acrobat and you should use a third-party tools to do that. PDF Extractor SDK can fortunately do all the jobs for you just with only a few lines of code. This is exactly what we’ll show you in the next section.

Extract rich media contents from PDF with PDF Extractor SDK and C#

Pdf content is not only limited to text format. Most of the time PDF documents contain pictures or documents and even more complex objects like audio or video media files may be embedded into the document.
The following example shows you how to extract such objects using PDF extractor SDK
The basic steps to perform this process are:
1- Create the extractor object. The type actually depends on what kind of objects we’re going to extract
2- Locate the object in the document. We can loop over existing objects to find the index of the targeted object.
3- Call the appropriate method of the extractor object in step 1 to extract the data. The extractor object has also some interesting properties about the data as file type, data size,
4- Save the extracted data to the file system.
For more details about supported rich media contents, please visit the official adobe acrobat help page https://helpx.adobe.com/acrobat/using/rich-media.html

Extract audio file mp3 from PDF document with PDF extractor SDK and C#

The Bytescout.PDFExtractor.MultimediaExtractor is the most suitable component to extract an embedded audio file from a PDF document.
The file Pdf_with_mp3.pdf contains an audio mp3 object. We can extract the audio file using the following lines of code

            MultimediaExtractor extractor = new MultimediaExtractor();
            extractor.LoadDocumentFromFile(@"Pdf_with_mp3.pdf");
            bool audioFound = extractor.GetFirstAudio();
            if (audioFound)
            {
                string audiofileName = "eldorado" + extractor.GetCurrentAudioExtension();
                extractor.SaveCurrentAudioToFile(audiofileName);
            }

Note: The file extension was originally “.mp3”, however the method MultimediaExtractor. GetCurrentAudioExtension() returns “.mpa” file extension.

Some interesting methods are MultimediaExtractor.GetCurrentAudioBytesSize() to get the actual file size, MultimediaExtractor.GetDocumentAudioCount() returns the number of embedded audio files in the document and MultimediaExtractor.GetNextAudio() allows to switch to the next audio file.

Extract video file from PDF document with PDF extractor SDK and C#

You can extract any embeded videos files using the following steps.
1- Create an instance of Bytescout.PDFExtractor.MultimediaExtractor class to grab the video file
2- Save the file to disk using the method MultimediaExtractor .SaveCurrentVideoToFile.

The following program shows how to extract the embedded video file ( H264 compilant otherwise it will fail) in Pdf_with_video.pdf and save it into the file system.

	    MultimediaExtractor extractor = new MultimediaExtractor();
            extractor.LoadDocumentFromFile(@"Pdf_with_video.pdf");
            bool videoFound = extractor.GetFirstVideo();
            if (videoFound)
            {
                string videofileName = "abc" + extractor.GetCurrentVideoExtension();
                extractor.SaveCurrentVideoToFile(videofileName);
            }

The method MultimediaExtractor.GetFirstVideo() is where we locate the targeted video. Some useful methods are:
– MultimediaExtractor.GetDocumentVideoCount() to get the total number of video objects in the current file.
– MultimediaExtract.GetNextVideo() to navigate to the next video file.

Extract images from PDF file using Adobe Acrobat DC

Adobe Acrobat DC can extract embedded images in the PDF document.

The following steps show you how to do that.

Step 1: Open the document in Adobe Acrobat DC

Step 2: Tools > Export PDF

Step 3: The last screen allows you to configure the image type

Extract images from PDF file using C#

Pdf extractor Sdk can extract any embedded images in the pdf document. It has a full support on Gif, Tiff, jpg… formats. You can achieve that in three steps:
1- Create an instance of Bytescout.PDFExtractor.ImageExtractor class
2- Load the PDF document with the method Locate Bytescout.PDFExtractor.ImageExtractor .LoadDocumentFromFile
3- Locate the image in the page
4- Save the image with the method Bytescout.PDFExtractor.ImageExtractor.SaveCurrentImageToFile

Note: We need to use System.Drawing.Imaging assembly in order to use ImageFormat class.

You can download the document here

ImageExtractor extractor = new ImageExtractor();
extractor.LoadDocumentFromFile(@"Pdf_with_image.pdf");
var firstImageFound = extractor.GetFirstImage();
if (firstImageFound)
{
extractor.SaveCurrentImageToFile("firstimage.png", ImageFormat.Png);
}

One interesting feature is the ability to choose the export format regardless of the initial format of the image. Depending on your need, you can pass here Png, Jpeg, Ico, gif, bmp, Exif they all are well handled by PDF Extractor SDK.

Extract embedded documents in PDF file

PDF Extractor can extract any embedded documents from pdf. This process involves four steps
1- Create an instance of Bytescout.PDFExtractor.AttachementExtractor class
2- Load the PDF file using Bytescout.PDFExtractor.AttachementExtractor.LoadDocumentFromFile method
3- Locate the file with Bytescout.PDFExtractor.AttachementExtractor.GetFileName with file’s index as input parameter.
4- Call the Save method to write to disk.

            AttachmentExtractor extractor = new AttachmentExtractor();
            extractor.LoadDocumentFromFile(@"Pdf_with_files.pdf");
            extractor.Save(0, extractor.GetFileName(0));

We’ve seen along this article several ways to extract data from PDF document. If you want to do it manually, Adobe Acrobat DC is definitely the best choice. However this product is not free and you have to pay to get the commercial license. An alternative is to use Adobe Reader but there’s some limitations using it. For automated extraction process, we’ve seen that PDF Extractor SDK is a simple, complete and reliable tools for pdf extraction data. It supports a lot of commonly used formats (xml, csv, json, html ,text and so on). For more complex OCR tasks, Adobe Acrobat is a very reliable software, the pattern recognition error rate is quite low and it also supports many export formats. PDF Extractor SDK offers a powerful OCR engine, many features are available to developers to optimize the character recognition process. PDF Extractor SDK is definitely a well placed tools when your business requires to deal with rich media contents. We’ve seen so far that it has a full support of extracting audios, videos from any PDF files and is compatible with any CLR compilant programming languages C# / VB.NET.

The post Extracting data from tables in PDF appeared first on ByteScout.

Bytescout released product updates!

$
0
0

Barcode Reader SDK 8.80.0.1621

Fixed malfunctioning MaxNumberOfBarcodesPerPage property when different (1D/2D/OMR) barcode types enabled.
Added Reader.DecoderSpecificOptions for fine tuning of specific decoders.
Added ScanStep property defining row scan interval for linear barcodes;
Code 128: Fixed zero-length false positives.
Improved DataMatrix decoding.
Intelligent Mail: Fixed zero-padding of value components.
Added support for profiles – quick way to apply multiple settings at once.
Improved Heuristic mode.
EXIF rotation tag in photo images is correctly handled now.
Improved handling of TIFF images with 204×98 DPI resolution.
Other minor improvements and bug fixes.

Bytescout PDF Extractor SDK 8.2.0.2697

Fixed Unwrap option.
Improved bordered tables detection.
Improved attachments extraction.
Added support for profiles – quick way to apply multiple settings at once.
OCR: Implemented rotation detection of wrongly oriented scanned PDF pages.
SearchablePDFMaker now able to automatically rotate wrongly oriented scanned PDF pages.
Fixed exception in SearchablePDFMaker when loading the document from the stream.
Fixed memory leaks in OCR.
TextExtractor and CSVExtractor: Added Save* methods overrides allowing to specify the characters encoding.
Improved media files extraction.
Improved Vertical Line Remover OCR preprocessing filter.
Other minor improvements and bug fixes.

ByteScout PDF Renderer SDK 8.2.0.2697

Improved rendering of special color spaces.
Improved rendering of special image masks.
Other minor improvements and bug fixes.

ByteScout PDF To HTML SDK 8.2.0.2697

Improved PDF to plain HTML conversion: it’s now possible to reflow newspaper layout to single-column HTML text.
Other minor improvements and bug fixes.

Spreadsheet SDK 2.80.1582

Improved conversion to PDF.
Added Spreadsheet.Options.CSVDetectDataTypes property allowing to disable the automatic data type detection when importing CSV file.
Added OLE/COM versions of Cell.FillPatternForeColor and Cell.FillPatternBackColor properties to use from VBScript and classic ASP.
Other minor improvements and bug fixes.

ByteScout PDF SDK 1.4.0.157

Added HTML to DOCX converter.
Fixed rare crush on encrypted documents.
FlattenDocument() method now use standard fonts if could not copy the control’s font for some reason.
Other minor improvements and bug fixes.

Barcode Generator SDK 4.56.0.911

Minor improvements and bug fixes.

ByteScout PDF Viewer SDK 8.2.0.2697

Improved PDF rendering.
Improved attachments extraction.
Find() method now returns boolean result and allows to specify the type of user feedback.
Other minor improvements and bug fixes.

ByteScout PDF Multitool 8.2.0.2697

Improved PDF to plain HTML conversion: it’s now possible to reflow newspaper layout to single-column HTML text.
Improved PDF rendering.
Fixed Unwrap option.
Improved bordered tables detection.
Improved attachments extraction.
OCR: Implemented rotation detection of wrongly oriented scanned PDF pages.
SearchablePDFMaker now able to automatically rotate wrongly oriented scanned PDF pages.
Fixed memory leaks in OCR.
Improved media files extraction.
Improved Vertical Line Remover OCR preprocessing filter.
Fixed file filters in Open File Dialog.
Other minor improvements and bug fixes.

Barcode Generator freeware 4.56.0.911

Minor improvements and bug fixes.

Barcode Reader Freeware 8.80.0.1621

Code 128: Fixed zero-length false positives.
Improved DataMatrix decoding.
Intelligent Mail: Fixed zero-padding of value components.
Improved Heuristic mode.
EXIF rotation tag in photo images is correctly handled now.
Improved handling of TIFF images with 204×98 DPI resolution.
Other minor improvements and bug fixes.

The post Bytescout released product updates! appeared first on ByteScout.

Best React Components in 2017

$
0
0

ReactJS is one of the most modern and powerful javascript libraries for building user interfaces. It was initially developed and maintained by Facebook.

In this article, we’ll see how to start with ReactJS using the minimal setup (no use of nodejs). We’ll also talk about each major parts of the library and finally, we’ll focus on existing ReactJS available components in the market.

Quick start with ReactJS

In this section, we’ll show you how to setup your rig to work with ReactJS.

Choose the text editor

In this tutorial, we’re going to use Atom text editor. It is a tool that you can download and use for free (https://atom.io/) . It has a lot of very interesting plugins that may help in your coding experience and most of all it is a multi-platform software.

Once installed, we need to add ReactJS plugins in order to get the most of it. The figure below shows the top 5 React plugins.

We’ll install “react 0.16.2” which is the most downloaded package and certainly the best one.

Writing your first ReactJS program

The particularity of this tutorial is that you’ll work with the minimal required setup. Unlike almost all ReactJS tutorials you may read over the world web, we’re not going to use any additional tools like
node package manager or something like APM, instead, we’ll use CDN. CDN are public remote repositories that you can reference directly in your web page.

1- Create your working directory and add the following two files:

– index.html : a classical html page

– script.jsx : a file with .jsx extension, we’ll see the main line of that later on

2- Open the file index.html with your web browser. For the sake and the simplicity, we use Mozilla Firefox web browser (see Troubleshot below).

Troubleshot:

If you’re using Google Chrome web browser you may encounter this error message [XMLHttpRequest cannot load file:///C:/Log/jsr/script.jsx. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.]

Please read the following thread :

http://stackoverflow.com/questions/20041656/xmlhttprequest-cannot-load-file-cross-origin-requests-are-only-supported-for-ht

For that reason, we only use Mozilla Firefox web browser along this tutorial.

Congratulations! You just run your first ReactJs app. Let see how does it work under the hood.

*index.html

It is just like any HTML documents.

The HTML part is easy to understand, we always have a couple of script imports and the main line importing EditorFor.jsx file.

ReactJS props

“Props” are properties that we pass to the component. For example, in the previous example, the label of the EditorFor component can be dynamically managed by the following declaration :

ReactDOM.render(<EditorFor MyLabel=”Name”/>,document.getElementById(“mydiv”));

We can then access the MyLabel props with the syntax {this.props.MyLabel}

var EditorFor = React.createClass({
  render:function(){
    return (





























&lt;div&gt;
      &lt;label&gt;{this.props.MyLabel}&lt;/label&gt;
      &lt;input type="text" placeholder="enter a text"/&gt;
      &lt;/div&gt;





























    );
  }
});
ReactDOM.render(&lt;EditorFor MyLabel="Name"/&gt;,document.getElementById("mydiv"));

We can add as many as props we need and this.props object contains all those available properties inside the ReactsJS component.

In order to do the data binding, we must enclose the property call with curly brackets { }, it tells ReactJS to replace this pattern to the actual prop’s value during the rendering time.

Note: Instead of using declarative component <EditorFor /> markup, you can use the method React.createElement to instantiate the component

ReactDOM.render(React.createElement(EditorFor,{ MyLabel:"Name"}),document.getElementById("mydiv"))

The createElement method takes the component name as it’s first argument and a list of props as it’s second arguments.

Props initialization

The method getDefaultProps is where you should initialize React’s component props. It is always a best practice to give a default value for each props and a well-initialized props guarantees that your component is free on unexpected behavior.

The following codes show how to do that:

var EditorFor = React.createClass({
  getDefaultProps:function(){
    return {
      MyLabel:"Default Name",
      //Enumerate here the list of props
    }
  },
  render:function(){
    return (



























&lt;div&gt;
      &lt;label&gt;{this.props.MyLabel}&lt;/label&gt;
      &lt;input type="text" placeholder="enter a text"/&gt;
      &lt;/div&gt;



























    );
  }
});
ReactDOM.render(React.createElement(EditorFor),document.getElementById("mydiv"))

If you don’t provide any value to your props, the component is going to initialize itself by calling the method getDefaultProps.

ReactsJS Props types

React has some built-in type checking abilities by using the component propTypes objects.

PropTypes helps to keep a strongly typed object in JS. We can tell that a props object is a string or a number by React.PropTypes.string or React.PropTypes.number. Other types are available for more complex data structure: React.PropTypes.array, React.PropTypes.object, React.PropTypes.symbol. PropTypes can be a virtual dom object , in this case we use React.PropTypes.node, React.PropTypes.element

Proptypes also checks data validation by using validator types (React.PropTypes.any.isRequired), you can even define a customized propType.

As stated in the official documentation, for performance reasons propTypes is only checked in development mode.

In the following example, we set the type of EditorFor’s MyLabel props to string.

EditorFor.propTypes={
  MyLabel:React.PropTypes.string
}

Reusable components React

An instance of React.createClass is actually an independent component that you can plug into your webpage. You can create as many as you need, each component has it’s own props, behavior and state. If you’re familiar with user controls (.ascx) in Microsoft Asp.net, React components are exactly the same.

React Native

React Native is another version of ReactJS that let you build indistinguishable mobile app from an app built using Java or Objective C.

You can build your native app with only Javascript and React. In addition to that, you can even mix Native Java or Objective-C code with React Native.

One of the big advantages is that React Native uses the same design as React, so don’t worry about your learning curve, once you learn React, you’ll use it everywhere.

React nested component

A component can be used inside another one, we call that a nested component.

The following code shows a nested component.A parent container named FieldSetFor contains two EditorFor components and initializes the MyLabel props.

The two nested components are independent each from other.

var EditorFor = React.createClass({
  getDefaultProps:function(){
    return {
      MyLabel:"Default Name",
      //Enumerate here the list of props
    }
  },
  render:function(){
    return (



























&lt;div&gt;
      &lt;label&gt;{this.props.MyLabel}&lt;/label&gt;
      &lt;input type="text" placeholder="enter a text"/&gt;
      &lt;/div&gt;



























    );
  }
});
var FieldSetFor =React.createClass({
  render:function(){
    return(   



























&lt;fieldset&gt;

&lt;legend&gt;{this.props.legend}&lt;/legend&gt;



























      &lt;EditorFor MyLabel="FirstName" &gt;&lt;/EditorFor&gt;
      &lt;EditorFor MyLabel="LastName" &gt;&lt;/EditorFor&gt;
    &lt;/fieldset&gt;



























  )
  }
});
ReactDOM.render(&lt;FieldSetFor legend="Personal information"/&gt;,document.getElementById("mydiv") )

Adding a “state” to ReactJS component

“State” reflects the component behavior at one point in time. State can change at any time along the component lives. A good candidate for state may be the value of a text input (for example text in search bar).

Unlike props objects, a React component can modify the state value. State is mutable while Props is immutable.

Note: The only place where props values are update is during the initialization.

In the program below, we define two initial states using the special function getInitialState – not mandatory but it’s better to use it.

– textstate =””

– chkstate =”false”

Each time the text value is changed we update each component’s states. when the typed value length is greater than 8 then the component automatically updates it’s internal state and reflects the changes in the UI by checking the checkbox or unchecking it.

We also add onChange event to the input text and bind it to the syncstate method by using {this.syncstate} syntax.

The syncstate private method is in charge of :

– getting the actual value (e.target.value)

– set the new state value with this.setState method and update the label text. You noticed that this state is linked to the label text.

– do some logic rules based on the length of the textState length

var StateSample = React.createClass({
  getInitialState:function(){
    return {
      textstate:"",
      chkstate:""
    }
  },
  syncstate:function(e){
    this.setState({ textstate: e.target.value})
    if (this.state.textstate.length &gt; 8){
      this.setState({chkstate : "checked"})
    }else{
      this.setState({chkstate : ""})
    }
  },
  render:function(){
    return (      





























&lt;div&gt;
      &lt;label&gt;Search text&lt;/label&gt;
      &lt;input type="text" placeholder="enter a text" onChange={this.syncstate}/&gt;
      Long text &lt;input type="checkbox" checked={this.state.chkstate} &gt;&lt;/input&gt;
      
        You typed:&lt;label&gt;{this.state.textstate}&lt;/label&gt;
      &lt;/div&gt;





























    );
  }
});
ReactDOM.render(React.createElement(StateSample),document.getElementById("mydiv") )

We’ve seen so far that props and state are two ways to pass parameters from outside to the React component. They are not actually doing the same thing. You may wonder yourself which one to choose in a specific case. There are some ideas that may help you to choose the best one:

-You can picture props as something immutable in the same way as configuration parameters of the component. Props should be managed by the outside and passed to the component. The component cannot change its props.

-State are something mutable, the component should manage the state change internally (never from the outside). State are private and only accessible by the component itself.

– They both can be initialized from parent component

– Only props can be changed by parent component

– They both can set default values inside component. If values are received from parents then default values are override

– Only state can be changed inside a component, props doesn’t

– The both can set initial values for Child components

– Only props can change in child component.

When changes occurs in Props or in State , the component automatically triggers the render method. In the previous example, that was exactly what happened: we’ve only update the state and ReactJS automatically updates the UI with the fresh value of state.

React stateless function components / React stateful function components

A component is stateless when it has only props, no state.

A stateful has both props and state ( also called state managers).

React Component lifecycle

The creation of a react component follows the next sequence :

– call of the built-in getDefaultProps method, you can redefine it if needed

– call of the built-in getInitialState method

– call of the built-in componentWillMount method before the render step

– call of the user-defined render method

– call of the built-in/redefined componentDidMount method. If you need to get data or update states, componentDidMount method is the right place to do those stuffs.

Note : If a state change occurs, the component invokes the render method to update the UI. This is even possible if you’re updating the state in async mode (for example using setTimeout function)

You can add the following componentDidMount method to the previous code, the chkstate is updated async 3 seconds after component loads and UI is refreshed after that interval.

componentDidMount:function(){
  var self = this;
  setTimeout(function(){
    self.setState({chkstate:"checked"});
  },3000);
}

Material UI React

Material UI is a graphical design specification suggested by Google. It states a set of design principles defining the UI design.

A complete detail is available at https://material.io/guidelines/

React Toolbox is a full set of ReactJS components and CSS modules that fill out Material UI specifications. It contains a lot of ready made Reacts basic controls like input, button, radio button,… and also provides advanced controls like tables, time_picker, progress bar…

The project is available on GitHub at https://github.com/react-toolbox/

Testing react components

Developers can do unit tests against their React components. There’s two things that you have to be acquainted in React testing: the testing library and the testing framework. The most popular test utilities in React is the package ReactTestUtils. The official page is available here . The testing framework runs generally on the server side using nodeJS. Facebook uses Jtest for Javascript testing.

The enzyme, a testing framework powered by Airbnb is also a very useful tool because it offers assert methods capabilities.

For example, you can test component events results, the behavior or the render output against an expected value.

In the majority of cases, those tests are fired at the server side.

You can also combine ReactJS and Redux to test your components. Redux architecture splits component’s parts into 4 layers :

-views, actions, dispatcher, and stores. You can mock data on each layer.

React and bootstrap

React-Bootstrap is a very promising front-end framework for building responsive app with React and Bootstrap.

The framework uses two main components which are :

bootstrap stylesheet

– bootstrap javascript named react-bootstrap.js contains all components

Those files are available on CDN making the use very easy. You just need to reference those CDN links and everything should be fine, you don’t need to install nodeJS to initialize your web app project in this case. According to the road map, all existing component in the classical version of bootstrap will be also available in react-bootstrap.

The project is available at https://react-bootstrap.github.io/ and is under active development at the time of writing.

Improving your development experience

Facebook offers a great tool to debug your ReactJS program. It is provided as a web browser plugin named “React Developer Tools”.

Since ReactJS dynamically adds HTML final outputs to the DOM, React Developer Tools allows us to revert back to the props and state objects and inspect their actual values.

It is available on most commonly used IDE and browsers as Chrome, Firefox, Atom, Nuclide and Electron. The standalone app is coming soon according to the official project’s GitHub page (https://github.com/facebook/react-devtools)

ES5, ES6 (ES2015), …

You will often see those terms when you’re reading ReactJS. They are referring to different ECMAScript version. ECMAScript is the specification of Javascript language and is implemented in all browser Javascript engines.

ES6 brought a lot of new features like arrow functions which are intensely used in ReactJS program. You may not be familiar to them because they are very recent. It may be confusing at the first time but after all, you can always keep your actual style of writing JS program because the difference is essentially at the syntactic level.

React and Angular

ReactJS is designed to manage the view in the MVC paradigm while Angular has a complete architecture to manage all three layers of MVC pattern.

However, Facebook’s engineer designed Flux, an architecture that aims to fulfill the MVC pattern.

Flux has four major components:

Views : view manages the render in the DOM, handles user events and triggers actions

Actions and Dispatcher : in MVC architecture, they are the controller C

Stores : contains data, acts as the Model in MVC pattern.

The GitHub fork is available here

React and URL Routing

URL Routing is an abstraction of the physical resource location into a logical resource.

Web sites use URL Routings to improve their SEO. Instead of directly exposing physical file (/index.html), URL Routing can make it more user-friendly readable like /Product-Discount. React-Router is a module that maps React Component to path.

React and Webpack

As the name implies, Webpack is the combination of two words Web and Pack. It acts as a bundler module that serves static components (css/js) into grouped packages.

Actually, it is more than that. Webpack is running at the server side (nodeJS). You can define configuration rule of how contents should be served to the client.

For example, you can tell it to combine a set of js files into one package and serves your css files together in one another package. Thus it allows to reduce incoming and out coming requests

to your server. Since ReactJS app may use a lot of modules, Webpack can improve the maintainability of your web app.

The official website is at http://webpack.github.io/docs/tutorials/getting-started/

ReactJS best practices

We share here some developers feedbacks and best practices

– keep your component small. The official “Think in react” article states that it is always

a good idea to make unitary component, never overload the component in functionalities split it to several smaller components instead. It is extremely easy to read and to maintain modular component.

avoid the use of state as possible as you can. Using a lot of state in your component will be an earlier source of confusing. State is used for interactivity so values can change many times. State also make component testing complicated. Sharing state with an upper component in the hierarchy becomes tricky, instead of using props is a better way to do that.

-Since ReactJS managed only the view, it’s a very big mistake to try to overload your component with data gathering calls or action invoking stuffs. A better workaround is to use Redux.js. As we’ve stated in this article, Redux.js provides a full MVC architecture to your React app.

-always use propTypes for the safety of the component. propTypes are able to check

that your props are in the correct data types. They are also data validator utilities. Remember that propTypes are only available during the development stage.

ReactJs is also suitable for UI TDD (Test driven development). You can build your component with minimal knowledge and test it to check that it satisfied the minimal requirements. When you get more complex details about the final UI component, you just add those specifications to the actually tested version and redo the test again.You repeat this process till the whole functionality are implemented.

-ReactJs is evolving quickly and a lot of third party frameworks come into the market .

Be sure you stay tuned with the latest news about them.

ReactJS & Babel

This is a frequent word that you’ll see every time. Babel is a javascript compiler and the official website is at babeljs.io.

Under the hood, Babel only transforms javascript syntax. For example, it takes as input a JSX file and gets native javascript out. But it is more than that. Babel has many different plugins

that allow you to transform many other formats even write your own transform rules. One

reason to use Babel is that some old vendor web browsers aren’t compliant with new

ECMAScript features. Babel is in charge of transforming those latest features to be compatible

with the former ECMAScript specifications.

A command line interface CLI (Babel-CLI) is also available to allow interactive program and you can even attach your program to the debugger engine.

One of the advantages of babel engine is that it has a full support of the latest version

ECMAScript ( it especially supports arrow functions syntax that are commonly used by many
developers ) A Babel program can run both at the server side (nodejs) or client side(web browser). Some developers tell that Babel is more efficient than JSXTransformers.

ReactJS and Node package manager

Npm as Node package manager is a utility that takes care of components dependencies and the versioning. If you are a beginner with that, you may wonder yourself the relationship between them. They are actually independent each from other. You can return ReactJS component without using Node package manager. Our first example shows that we didn’t use Npm, instead we directly use CDN resources.

This is true while your app is pretty simple but when it grows up it becomes extremely hard to work without node package manager. The reason is that most of ReactJS component use a lot of dependencies and npm is the best way to automatically resolve those dependencies with safety.

ReactJS and asp.net

If you are an asp.net developer, ReactJS.net is definitely complete tools to use ReactJS with your asp.net MVC project.

It is even the best place to start if you’re a pure C# asp.net developer and want to discover the ReactJS world.

One of the big advantages is that it is a cross-platform oriented framework allowing you to go for a classical asp.net MVC project or .net core MVC project. It is available on Nuget package manager via React.Web.MVC4 package for .NET Framework and React.AspNet for .NET Core.

The framework allows JSX server-side rendering (at the writing, they stated it as a super fast process) and offers a lot of MVC Razor Helpers like @Html.React*. For more details about this project, you can visit the project’s fork is at

https://github.com/reactjs/React.NET

ReactJS inline styles

This is also a frequent term in ReactJS world. Inline styles allow you to declare CSS style through a variable into you js or JSX files.

render:function(){
  var labelStyle = {
    color:'red'
  }
  return (




























&lt;div&gt;
    &lt;label style={labelStyle}&gt;{this.props.MyLabel}&lt;/label&gt;
    &lt;input type="text" placeholder="enter a text"/&gt;
    &lt;/div&gt;




























  );
}
});

We declare an inline style named labelStyle , it looks like a common css declaration with respecting that the key name should be in camel case version (for example backgroundImage instead of background-image, I is capitalized) We then assign the labelStyle to the label tag.

The previous example also shows you how can you deal with CSS in ReactJS.of course you can always use the old fashioned way of declaring css separately in the .css file. The advantage here is that we can dynamically change CSS property value.

ReactJS and Browserify

Most node modules require dependencies, those dependencies are declared in each js file with the keyword “require”.

This keyword is used by Node.js on the server side. Based on the required dependency, Nodejs engine resolves them by pre-loading those file before working the current file. Unfortunately for us, your browsers don’t know that NodeJS method and an error is thrown when we try to make directly link to any js files in the node_modules folder.

Here comes the utility of Browserify. The principle is to start with one unique js file and tries to recursively bundle all dependencies into one big file. The bundle file is then rendered to the client. It is also better to minify the bundle js file to reduce the http response size.

Other alternatives that are interesting are uglify, gulpjs, grunt.

Conclusion

We’ve covered along this tutorial a global view over ReactJS universe. There are a lot of existing tools and frameworks and there’s also a lot of incoming new tools in the nearest future. Some of them happen in the View layer, some others are done at the server side for example with NodeJS. We all know that it is a bit hard to have a full control on all of them, especially that some of them have a very good support and have a very active community. You should go for the one that is well supported. The best choice depends on your need and on your skill.

Before you decide to adopt definitely ReactJS as your main rendering framework, the following link is very helpful https://facebook.github.io/react/.

The post Best React Components in 2017 appeared first on ByteScout.

VS Code, Atom Editor – Alternative Editors for C#

$
0
0

VS Code, Atom Editor – How would be your c# development experience using them

Have you ever tried to use them in your work? Are they easy to use? Are they improving your productivity? If these words are meaningless for you, these are our feedbacks after using them.

VS Code, Atom are some of the new generation of IDE (Integrated Debugging Environment), to be more correct let’s say simply text editors or SUPER text editors, that become increasingly popular in recent years. They all are:

lightweight software: they are provided as a minimal component, the core or the kernel, above which can be plugged a lot of add-ons. The core package is quite small ~100MB compared to classical IDE like Visual Studio, IntelliJ, Netbeans

free and open-source software which has all a well broad support from their community

multi-platforms: this is one of the most interesting features about them. The developer can still use his favorite editor if he has to switch from windows to MacOSX or from Linux to windows later on.

This is a short list of what we expect for our text editor:

  • Syntax color management;
  • Document format;
  • Auto-completion ( an alternative to IntelliSence );
  • Integration language compiler and debugger;
  • Shortcuts (for example for «Go to Definition», selection comment/uncomment);
  • Source versioning plugin.

Atom – « A hackable text editor for the 21st Century »

As a C# developer, we’ll try to see how would be our programmer life if Atom is our IDE.

First of all we download it at https://atom.io/, the package size is ~85 MB and takes around ~270MB after installation. At the time of writing the version is 1.13.0

Quite promising isn’t it?

Everything seems to be customizable: Themes as well as Styling and snippets to only quote a few of them. We go straight to our point of interest : what about C# support.

We can search available packages at the website.

The two most relevant packages relating to C# development are :

language-csharp downloaded ~256.000 times till now

omnisharp-atom downloaded around 66.000 times

We’ll definitely go for the first one:

Atom syntax highlighting

Vscode

The following extensions are available in Vscode. Here we can see the OmniSharp C# extension has more that 1 millions of download, so we choose it as our main c# extension manager

Document format

Atom and Vscode tested plugins have almost the same features in document formatting. They both do well indentations, advanced styling, line numbering…

Auto-completion

Tested plugins managed well smart completion and they both are very fast and friendly interactive. They both can also display method definitions, snippets and so on. VS Code IntelliSense features are powered by a language service which is a serious advantage compared to the Atom plugin.

Integration language compiler & debugger

You can compile your project and do debug session. They both offer a great debugger experience.

Shortcuts

They both come with a ton a shortcut like definition navigation, parameter info, comment, tab switching. You can even define your own shortcuts.

Version control

As a developer, you may also need that your source code editor has the ability to use source versioning like Github, subversion, TFS.

Atom

Atom-TFS is right package for TFS integration. At the time of writing, the plugin is in a very active development. It offers you three basic commands check-in, get and undo. You must also need to have Visual studio and TFS Power Tools to be installed to use it. You also have to note that atom-TFS is not only the unique TFS plugin available on atom but it is the most featured one at the time of writing.

Vscode

Vscode has a full support of TFS 2015 update 2 and later. Compared to Atom, Vscode offers a lot of additional features like merge or resolve conflicts, branch controls, staging and unstaging commands and so on… the list if very long, you can get more details at https://code.visualstudio.com/Docs/editor/versioncontrol

 

Conclusion

At the end of the day, it is quite difficult to make the choice since both editors offer a great experience.  You have to know that they are not limited to only C# development, they include a large support of almost existing programming languages. The main advantage of Vscode when we talk about c# development is its ability to give better support of TFS and Vscode IntelliSense. They are not only the existing one, you can also discover Nuclide ( based on Atom but at the time of writing, the official website states that some features are not fully supported on Windows platform), SublimText (not free), Vim.

The post VS Code, Atom Editor – Alternative Editors for C# appeared first on ByteScout.

Viewing all 325 articles
Browse latest View live