.NET (1273)
Children categories
Extracting images from PDFs is a common task for many users, whether it's for repurposing visuals in a presentation, archiving important graphics, or facilitating easier analysis. By mastering image extraction using C#, developers can enhance resource management and streamline their workflow.
In this article, you will learn how to extract images from individual PDF pages as well as from entire documents using C# and Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Extract Images from a Specific PDF Page
The PdfImageHelper class in Spire.PDF for .NET is designed to help users manage images within PDF documents. It allows for various operations, such as deleting, replacing, and retrieving images.
To obtain information about the images on a specific PDF page, developers can utilize the PdfImageHelper.GetImagesInfo(PdfPageBase page) method. Once they have the image information, they can save the images to files using the PdfImageInfo.Image.Save() method.
The steps to extract images from a specific PDF page are as follows:
- Create a PdfDocument object.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Get a specific page using PdfDocument.Pages[index] property.
- Create a PdfImageHelper object.
- Get the image information collection from the page using PdfImageHelper.GetImagesInfo() method.
- Iterate through the image information collection and save each instance as a PNG file using PdfImageInfo.Image.Save() method.
- C#
using Spire.Pdf; using Spire.Pdf.Utilities; using System.Drawing; namespace ExtractImagesFromSpecificPage { class Program { static void Main(string[] args) { // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF document doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf"); // Get a specific page PdfPageBase page = doc.Pages[0]; // Create a PdfImageHelper object PdfImageHelper imageHelper = new PdfImageHelper(); // Get all image information from the page PdfImageInfo[] imageInfos = imageHelper.GetImagesInfo(page); // Iterate through the image information for (int i = 0; i < imageInfos.Length; i++) { // Get a specific image information PdfImageInfo imageInfo = imageInfos[i]; // Get the image Image image = imageInfo.Image; // Save the image to a png file image.Save("C:\\Users\\Administrator\\Desktop\\Extracted\\Image-" + i + ".png"); } // Dispose resources doc.Dispose(); } } }
Extract All Images from an Entire PDF Document
Now that you know how to extract images from a specific page, you can iterate through the pages in a PDF document and extract images from each page. This allows you to collect all the images contained in the document.
The steps to extract all images throughout an entire PDF document are as follows:
- Create a PdfDocument object.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Create a PdfImageHelper object.
- Iterate through the pages in the document.
- Get a specific page using PdfDocument.Pages[index] property.
- Get the image information collection from the page using PdfImageHelper.GetImagesInfo() method.
- Iterate through the image information collection and save each instance as a PNG file using PdfImageInfo.Image.Save() method.
- C#
using Spire.Pdf; using Spire.Pdf.Utilities; using System.Drawing; namespace ExtractAllImages { class Program { static void Main(string[] args) { // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF document doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf"); // Create a PdfImageHelper object PdfImageHelper imageHelper = new PdfImageHelper(); // Declare an int variable int m = 0; // Iterate through the pages for (int i = 0; i < doc.Pages.Count; i++) { // Get a specific page PdfPageBase page = doc.Pages[i]; // Get all image information from the page PdfImageInfo[] imageInfos = imageHelper.GetImagesInfo(page); // Iterate through the image information for (int j = 0; j < imageInfos.Length; j++) { // Get a specific image information PdfImageInfo imageInfo = imageInfos[j]; // Get the image Image image = imageInfo.Image; // Save the image to a png file image.Save("C:\\Users\\Administrator\\Desktop\\Extracted\\Image-" + m + ".png"); m++; } } // Dispose resources doc.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Background
PDF is now widely used to represent document in independent specification. It encapsulates a complete description of a fixed-layout flat document, including the text, fonts and graphics and so on. Due to its powerful functions, it is difficult for developers to parse its format. Or more specifically, to parse content out from PDF document and convert it to different image format is a tough task for some developers. This article will help you solve this problem by using PDF document viewer component Spire.PDFViewer for WPF by 5 easy steps. Firstly, you can download Spire.PDFViewer for WPF.
Target
To convert a specified or random page including frames of images from PDF file to TIFF programmatically.
Step 1: To create WPF application in Visual Studio and reference Spire.PdfViewer.WPF dlls.
Set .NET 4 as target framework
Step 2: Instance an object of Spire.PdfViewer.Wpf.PdfDocumentViewer
PdfDocumentViewer pdfViewer = new PdfDocumentViewer();
Step 3: Call the “LoadFromFile”of PdfDocumentViewer object and load a PDF file.
pdfViewer.LoadFromFile ("sample.pdf");
Step 4: Create an array and save all pages of this PDF file.
int[] pageNumbers=new int[pageCount]; for (int i=0;i
Step 5: Save it to Tiff image format
pdfViewer.SaveAsImage("sample.tiff",pageNumbers);
The following code snippet shows all the code when converting pdf page to tiff image:
private void Button_Click(object sender, RoutedEventArgs e) { // Instance an object of Spire.PdfViewer.Wpf.PdfDocumentViewer PdfDocumentViewer pdfViewer = new PdfDocumentViewer(); //Load a pdf file pdfViewer.LoadFromFile("sample.pdf"); int pageCount = pdfViewer.PageCount; // create an array and save all pages of this PDF file. int[] pageNumbers=new int[pageCount]; for (int i=0;i
Screenshot
Spire.PDFViewer for WPF is a powerful WPF PDF Viewer control which enables developers to display PDF documents with their WPF applications without Adobe Reader. It’s available to load and view PDF documents like PDF/A-1B, PDF/X1A, and even encrypted from stream, file and byte array with support for printing, zooming, etc.
XPS is a format similar to PDF but uses XML in layout, appearance and printing information of a file. XPS format was developed by Microsoft and it is natively supported by the Windows operating systems. If you want to work with your PDF files on a Windows computer without installing other software, you can convert it to XPS format. Likewise, if you need to share a XPS file with a Mac user or use it on various devices, it is more recommended to convert it to PDF. This article will demonstrate how to programmatically convert PDF to XPS or XPS to PDF using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Convert PDF to XPS in C# and VB.NET
Spire.PDF for .NET supports converting PDF to various file formats, and to achieve the PDF to XPS conversion, you just need three lines of core code. The following are the detailed steps.
- Create a PdfDocument instance.
- Load a sample PDF document using PdfDocument.LoadFromFile() method.
- Convert the PDF document to an XPS file using PdfDocument.SaveToFile (string filename, FileFormat.XPS) method.
- C#
- VB.NET
using Spire.Pdf; namespace ConvertPdfToXps { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load sample PDF document pdf.LoadFromFile("sample.pdf"); //Save it to XPS format pdf.SaveToFile("ToXPS.xps", FileFormat.XPS); pdf.Close(); } } }
Convert XPS to PDF in C# and VB.NET
Conversion from XPS to PDF can also be achieved with Spire.PDF for .NET. While converting, you can set to keep high quality image on the generated PDF file by using the PdfDocument.ConvertOptions.SetXpsToPdfOptions() method. The following are the detailed steps.
- Create a PdfDocument instance.
- Load an XPS file using PdfDocument.LoadFromFile(string filename, FileFormat.XPS) method or PdfDocument.LoadFromXPS() method.
- While conversion, set the XPS to PDF convert options to keep high quality images using PdfDocument.ConvertOptions.SetXpsToPdfOptions() method.
- Save the XPS file to a PDF file using PdfDocument.SaveToFile(string filename, FileFormat.PDF) method.
- C#
- VB.NET
using Spire.Pdf; namespace ConvertXPStoPDF { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample XPS file pdf.LoadFromFile("Sample.xps", FileFormat.XPS); //pdf.LoadFromXPS("Sample.xps"); //Keep high quality images when converting XPS to PDF pdf.ConvertOptions.SetXpsToPdfOptions(true); //Save the XPS file to PDF pdf.SaveToFile("XPStoPDF.pdf", FileFormat.PDF); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
PDF files have the advantage of being highly interactive and easy to transfer, but in certain cases, it is also necessary to convert PDF to images for embedding in web pages or displaying on some platforms that do not support PDF format. In this article, you will learn how to convert PDF to JPG, PNG or BMP image formats in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Convert a Specific PDF Page to an Image in C# and VB.NET
Spire.PDF for .NET offers the PdfDocument.SaveAsImage() method to convert a particular page in PDF to an image. Then, you can save the image as a JPEG, PNG, BMP, EMF, GIF or WMF file. The following are the detailed steps.
- Create a Document instance.
- Load a sample PDF document using PdfDocument.LoadFromFile() method.
- Convert a specific page to an image and set the image Dpi using PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY) method.
- Save the image as a PNG, JPG or BMP file using Image.Save(string filename, ImageFormat format) method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; using System.Drawing.Imaging; namespace PDFtoImage { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample PDF document pdf.LoadFromFile("E:\\Files\\input.pdf"); //Convert the first page to an image and set the image Dpi Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap, 500, 500); //Save the image as a JPG file image.Save("ToJPG.jpg", ImageFormat.Jpeg); //Save the image as a PNG file //image.Save("ToPNG.png", ImageFormat.Png); //Save the image as a BMP file //image.Save("ToBMP.bmp", ImageFormat.Bmp); } } }
Convert an Entire PDF Document to Multiple Images in C# and VB.NET
If you want to convert the whole PDF document into multiple individual images, you can loop through all the pages in the PDF and then save them as JPG, PNG or BMP images. The following are the detailed steps.
- Create a PdfDocument instance.
- Load a sample PDF document using PdfDocument.LoadFromFile() method.
- Loop through all pages of the document and set the image Dpi when converting them to images using PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY) method.
- Save images as PNG files using Image.Save() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Graphics; using System; using System.Drawing; using System.Drawing.Imaging; namespace PDFtoImage { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample PDF document pdf.LoadFromFile("input.pdf"); //Loop through each page in the PDF for (int i = 0; i < pdf.Pages.Count; i++) { //Convert all pages to images and set the image Dpi Image image = pdf.SaveAsImage(i, PdfImageType.Bitmap, 500, 500); //Save images as PNG format to a specified folder String file = String.Format("Image\\ToImage-{0}.png", i); image.Save(file, ImageFormat.Png); } } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Background
Excel is widely used to organize data manipulations like arithmetic operations. Excel provides many built-in functions which automate a number of types of calculation. Functions are pre-programmed formulate for example, the square-root function, trigonometric functions, logarithms etc. Excel has more than 300 functions covering a range of statistical, mathematical, financial and logical operations. There is no doubt that using a function offers a shortcut method.
Calculate Formulas in XLS Document
Microsoft Excel is a powerful tool which has many uses, the most basic feature of which is performing functions. The aim of this article is to help you perform simple arithmetic operations on values in programming by using excel functions. Spire.Xls for .NET can help you easily create a new excel document or load an existing excel document into program, and calculate data of designated cell by function. Applied in Console platform, WinForm and Asp.net, It provide different types of mathematical functions, statistical functions , logic functions ,and string functions to calculate data with C# codes.
The following is the method example of using Console application to show how Spire.XLS for .NET realizes the calculation formula:
Step 1: Build a console application, and add spire.XLS.dll, Spire.Common.dll assembly.
Step 2: Instantiate an object of Spire.Xls.WorkBook, and add a “WorkSheet” in WorkBook object.
Workbook workbook = new Workbook(); Worksheet sheet = workbook. Worksheets[0];
Step 3: Set the value and format in Cell A1 and Cell A3.veiwing the C# Code.
//set Column A, B, C width sheet.SetColumnWidth(1, 32); sheet.SetColumnWidth(2, 16); sheet.SetColumnWidth(3, 16); // Set value of Cell A1 sheet.Range[currentRow++, 1].Value = "Examples of formulas :"; // Set value of Cell A2. sheet.Range[++currentRow, 1].Value = "Test data:"; // Set text format Of Cell A1 CellRange range = sheet.Range["A1"]; range.Style.Font.IsBold = true; range.Style.FillPattern = ExcelPatternType.Solid; range.Style.KnownColor = ExcelColors.LightGreen1; range.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;
Step 4: Set some cells value and then to sum up some cells data and the results will be displayed in one of the cells.
sheet.Range[currentRow, 2].NumberValue = 7.3; sheet.Range[currentRow, 3].NumberValue = 5; sheet.Range[currentRow, 4].NumberValue = 8.2; sheet.Range[currentRow, 5].NumberValue = 4; sheet.Range[currentRow, 6].NumberValue = 3; sheet.Range[currentRow, 7].NumberValue = 11.3; //Create arithmetic expression string about cells currentFormula = "=Sheet1!$B$3 + Sheet1!$C$3+Sheet1!$D$3+Sheet1!$E$3+Sheet1!$F$3+Sheet1!$G$3"; //Caculate arithmetic expression about cells formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value;
Step 5: Respectively set value and text format of Cell A4, B4.
sheet.Range[++currentRow, 1].Value = "Formulas"; ; sheet.Range[currentRow, 2].Value = "Results"; range = sheet.Range[currentRow, 1, currentRow, 2]; range.Style.Font.IsBold = true; range.Style.KnownColor = ExcelColors.LightGreen1; range.Style.FillPattern = ExcelPatternType.Solid; range.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;
Step 6: Realize calculation simple expression.
// Create arithmetic tables enclosed type string currentFormula = "=33*3/4-2+10"; sheet.Range[++currentRow, 1].Text = currentFormula; // Caculate arithmetic expression formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value;
Step 7: Realize some mathematic functions.
//absolute value function . currentFormula = "=ABS(-1.21)"; sheet.Range[currentRow, 1].Text = currentFormula; sheet.Range[currentRow++, 2].Formula = currentFormula;
Step 8: Realize some logic function.
//NOT function //Create NOT function string currentFormula = "=NOT(true)"; sheet.Range[currentRow, 1].Text = currentFormula; //Caculate NOT function formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value; sheet.Range[currentRow, 2].HorizontalAlignment = HorizontalAlignType.Right;
Step 9: Realize some string handling functions.
//Get the substring // Build substring function currentFormula = "=MID(\"world\",4,2)"; sheet.Range[++currentRow, 1].Text = currentFormula; //Caculate substring function formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value; sheet.Range[currentRow, 2].HorizontalAlignment = HorizontalAlignType.Right;
Step 10: Realize a random function.
// Random function // Create random function string. currentFormula = "=RAND()"; sheet.Range[++currentRow, 1].Text = currentFormula; //Caculate random function formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value;
Step 11: Save workbook object as file.
workbook.SaveToFile("formulaTest.xls",ExcelVersion.Version97to2003);
Viewing the full c# code
using System; using System.Collections.Generic; using System.Text; using Spire.Xls; namespace XlsCalculateFormula { class Program { static void Main(string[] args) { //Instanitate an object of Spire.Xls.Workbook Workbook workbook = new Workbook(); // Add a Spire.Xls.Worksheet to Spire.Xls.Workbook Worksheet sheet = workbook.Worksheets[0]; int currentRow = 1; string currentFormula = string.Empty; object formulaResult = null; string value = string.Empty; // Set width respectively of Column A ,Column B,Column C sheet.SetColumnWidth(1, 32); sheet.SetColumnWidth(2, 16); sheet.SetColumnWidth(3, 16); //Set the value of Cell A1 sheet.Range[currentRow++, 1].Value = "Examples of formulas :"; // Set the value of Cell A2 sheet.Range[++currentRow, 1].Value = "Test data:"; // Set the style of Cell A1 CellRange range = sheet.Range["A1"]; range.Style.Font.IsBold = true; range.Style.FillPattern = ExcelPatternType.Solid; range.Style.KnownColor = ExcelColors.LightGreen1; range.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium; // Additive operation of mutiple cells sheet.Range[currentRow, 2].NumberValue = 7.3; sheet.Range[currentRow, 3].NumberValue = 5; ; sheet.Range[currentRow, 4].NumberValue = 8.2; sheet.Range[currentRow, 5].NumberValue = 4; sheet.Range[currentRow, 6].NumberValue = 3; sheet.Range[currentRow, 7].NumberValue = 11.3; // Create arithmetic expression string about cells currentFormula = "=Sheet1!$B$3 + Sheet1!$C$3+Sheet1!$D$3+Sheet1!$E$3+Sheet1!$F$3+Sheet1!$G$3"; //Caculate arithmetic expression about cells formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value; // Set the value and format of two head cell sheet.Range[++currentRow, 1].Value = "Formulas"; ; sheet.Range[currentRow, 2].Value = "Results"; sheet.Range[currentRow, 2].HorizontalAlignment = HorizontalAlignType.Right; range = sheet.Range[currentRow, 1, currentRow, 2]; range.Style.Font.IsBold = true; range.Style.KnownColor = ExcelColors.LightGreen1; range.Style.FillPattern = ExcelPatternType.Solid; range.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium; // Expression caculation // Create arithmetic tables enclosed type string currentFormula = "=33*3/4-2+10"; sheet.Range[++currentRow, 1].Text = currentFormula; // Caculate arithmetic expression formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value; /// The mathematics function /// //Absolute value function // Create abosolute value function string currentFormula = "=ABS(-1.21)"; sheet.Range[++currentRow, 1].Text = currentFormula; // Caculate abosulte value function formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value; /// Statistical function/// // Sum function // Create sum function string currentFormula = "=SUM(18,29)"; sheet.Range[++currentRow, 1].Text = currentFormula; // Caculate sum function formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value; ///logic function/// //NOT function // Create NOT function string currentFormula = "=NOT(true)"; sheet.Range[currentRow, 1].Text = currentFormula; //Caculate NOT function formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value; sheet.Range[currentRow, 2].HorizontalAlignment = HorizontalAlignType.Right; ///String Manipulation function/// //Get the substring // Build substring function currentFormula = "=MID(\"world\",4,2)"; sheet.Range[++currentRow, 1].Text = currentFormula; //Caculate substring function formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value; sheet.Range[currentRow, 2].HorizontalAlignment = HorizontalAlignType.Right; // Random function // Create random function string. currentFormula = "=RAND()"; sheet.Range[++currentRow, 1].Text = currentFormula; //Caculate random function formulaResult = workbook.CaculateFormulaValue(currentFormula); value = formulaResult.ToString(); sheet.Range[currentRow, 2].Value = value; // Save Spire.Xls.Workbook as exel file workbook.SaveToFile("formulaTest2.xls",ExcelVersion.Version97to2003); System.Diagnostics.Process.Start("formulaTest2.xls"); } } }
Screenshot:
How to dynamically create excel file and save it to stream in your .NET applications?
2013-08-17 07:36:24 Written by daisy zhangThis article reveals using Spire.XLS for .NET to create a new Excel file dynamically and save it to stream. Alternatively, loading Excel file from stream in C# will also be fully described in this article as an additional function of Spire.XLS for .NET.
First we need to complete the preparatory work:
- Download the latest Spire.XLS and install it on your machine.
- Add the Spire.XLS.dll files as reference.
- Open bin folder and select the three dll files under .NET 4.0.
- Right click property and select properties in its menu.
- Set the target framework as .NET 4.
Here comes to the explanation of the code:
Dynamically create Excel file and save it to stream
Firstly you can initiate an object of Spire.XLS.workbook
Workbook wbToStream= new Workbook();
Add Spire.XlS.Worksheet object by using the WorkSheet properties of Spire.XlS.Workbook. After that, write text in cell by take advantage of Range properties of Worksheet.
Worksheet sheet = wbFromStream.Worksheets[0]; sheet.Range["C10"].Text = "The sample demonstrates how to save an Excel workbook to stream.";
Then call the method SaveToStream of the Spire.XLS.Workbook object and save all the data which is in XLS format to stream.
wbToStream.SaveToStream(file_stream);
Let’s preview the sample Excel:
Load Excel file from stream in C#
You can initiate an object of Spire.Xls.Workbook
Workbook wbFromStream = new Workbook();
Load data which is in .xls format from steam by calling the method "LoadFromStream" of the Spire.XLS.Workbook object.
wbFromStream.LoadFromStream(fileStream);
Save the object of Spire.XLS.Workbook as an .xls file.
wbFromStream.SaveToFile("From_stream.xls",ExcelVersion.Version97to2003);
Look at this screenshot:
And what below is the full code used in the two functions:
static void Main(string[] args) { //A: Dynamically create Excel file and save it to stream Workbook wbToStream= new Workbook(); Worksheet sheet = wbToStream.Worksheets[0]; sheet.Range["C10"].Text = "The sample demonstrates how to save an Excel workbook to stream."; FileStream file_stream = new FileStream("To_stream.xls", FileMode.Create); wbToStream.SaveToStream(file_stream); file_stream.Close(); System.Diagnostics.Process.Start("To_stream.xls"); //B. Load Excel file from stream Workbook wbFromStream = new Workbook(); FileStream fileStream = File.OpenRead("sample.xls"); fileStream.Seek(0, SeekOrigin.Begin); wbFromStream.LoadFromStream(fileStream); wbFromStream.SaveToFile("From_stream.xls",ExcelVersion.Version97to2003); fileStream.Dispose(); System.Diagnostics.Process.Start("From_stream.xls"); }
Create PDF Dynamically and Send it to Client Browser Using ASP.NET
2013-08-08 07:38:36 Written by AdministratorAbout PDF
Portable Document Format (PDF)is a fixed-layout document as an independent specification by Adobe. It encapsulates a complete description including the text fonts, graphics, and other information needed to display it.
Create PDF dynamically and send it to client browser
To generate a PDF file dynamically and then send it to client browser, you can use Spire.PDF for .NET to finish this task. In addition, Spire.PDF supports loading an existing PDF file and send it to client browser as well. In this technical article, we will combine both two functions to made a fully description about how Spire.PDF make it work. Below are the two tasks:
- Task1 Create PDF dynamically and send it to client browser.
- Task2 Load an Existing PDF file and send it to client browser(This is an additional function of Spire.PDF for .NET)
Firstly create an Asp.net application and add Spire.PDF.dll assembly. You can add two buttons on an Aspx page in VS. Appoint one of them for Task 1, and the other for Task 2.
In terms of Task 1, firstly you need initiate an object of Spire.PdfDocument
PdfDocument doc = new PdfDocument();
And add a new page in this new PDF document
PdfPageBase page = newDoc.Pages.Add();
Pay attention that related auxiliary object are need while drawing string on this pdf page.
string message = "Hello world!"; PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 13f); PdfBrush brush = PdfBrushes.Red; PointF location = new PointF(20, 20);
Then you can draw a string in pdf page, something like this:
page.Canvas.DrawString(message, font, brush, location);
Finally you can open this newly generated PDF document in Client browser:
newDoc.SaveToHttpResponse("sample.pdf",HttpContext.Current.Response, HttpReadType.Open);
When it comes to Task 2, 3 lines of code can work it out directly.
Initiated an object of Spire.PdfDocument
pdfDocument doc = new PdfDocument();
Load a pdf file
doc.LoadFromFile(this.Server.MapPath("/sample.pdf"));
Load a pdf document ,after that ,send it to client browser as an attachment.
doc.SaveToHttpResponse("sample.pdf", this.Response, HttpReadType.Save);
To summarize above, the following is the complete code snippet needed in this two tasks:
C# using System; using System.Collections.Generic; using System.Drawing; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Spire.Pdf; using Spire.Pdf.Graphics; namespace SendPdfToWebBrowser { public partial class WebForm_SendPdf : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } // load a pdf document ,after that ,send it to client browser as an attachment protected void btnClientSavePdf_Click(object sender,EventArgs e) { // initiated an object of Spire.PdfDocument PdfDocument doc = new PdfDocument(); // Load a pdf file doc.LoadFromFile(this.Server.MapPath("/sample.pdf")); // send the pdf document to client browser as an attachment doc.SaveToHttpResponse("sample.pdf",this.Response, HttpReadType.Save); } // Create an pdf document ,then open it in the client browser protected void btnClientOpenPdf_Click(object sender, EventArgs e) { // Initiate an object of Spire.PdfDocument PdfDocument newDoc = new PdfDocument(); // Add a new page in this newly created pdf file PdfPageBase page = newDoc.Pages.Add(); string message = "Hello world!” ; PdfFont font = new PdfFont(PdfFontFamily.Helvetica,13f); PdfBrush brush = PdfBrushes.Red; PointF location = new PointF(20, 20); // Draw a string with designated brush, a font, position in pdf page page.Canvas.DrawString(message, font, brush, location); //To open this pdf document in client browser. newDoc.SaveToHttpResponse("sample.pdf",HttpContext.Current.Response, HttpReadType.Open); } } }
In the end, you can run it, and get things like this:
Screenshot of creating PDF dynamically and sending it to client browser
Screenshot of Loading an Existing PDF file and sending it to client browser
XPS (XML Paper Specification) is a fixed-layout document format designed to preserve document fidelity and provide device-independent document appearance. It is similar to PDF, but is based on XML rather than PostScript. If you want to save a Word document to a fixed-layout file format, XPS would be an option. This article will demonstrate how to convert Word documents to XPS in C# and VB.NET using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Convert Word to XPS in C# and VB.NET
The following are the detailed steps to convert a Word document to XPS using Spire.Doc for .NET:
- Initialize an instance of Document class.
- Load a Word document using Document.LoadFromFile() method.
- Save the Word document to XPS using Document.SaveToFile(string filePath, FileFormat fileFormat) method.
- C#
- VB.NET
using Spire.Doc; namespace ConvertWordToXps { class Program { static void Main(string[] args) { //Create a Document instance Document doc = new Document(); //Load a Word document doc.LoadFromFile("Sample.docx"); //convert the document to XPS doc.SaveToFile("ToXPS.xps", FileFormat.XPS); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
XPS is short for XML Paper Specification developed by Microsoft, which is a specification for a page description language and a fixed-document format. It comes out by Microsoft’s initiative to associate file creation with reading in its Windows operating system. Like PDF, XPS plays a loyal role to preserve document with offering device-independent document appearance. Editing in XPS or in PDF seems difficult.
As a flexible and professional component, Spire.PDF for .NEToffers a large variety conversion, among which the conversion from XPS to PDF is one of its popular feature. In addition, Spire.PDF for .NET can be applied in WinForm, ASP.NET and Console Application.
The following code example shows how to convert XPS files to PDF document.
Step 1: Introduce a class named pdfDocument which is used to initialize a Spire.PDF.PdfDocument, and load a XPS file by calling the method of LoadForm File.
PdfDocument doc = new PdfDocument(); doc.LoadFromFile(xpsFile,FileFormat.XPS);
Step 2: Only needs one row of simple code. Call the SavetoFile method of Spire.PDF.pdfDocument to save all the data as PDF formart.
doc.SaveToFile(pdfFile, FileFormat.PDF);
After this code, run this application and you will see the PDF converted from XPS.
Screenshot before converting XPS to PDF:
Screenshot after converting XPS to PDF:
Programme Guide for Spire.Barcode
Spire.BarCode for .NET is a professional barcode component specially designed for .NET developers (C#, VB.NET, ASP.NET) to generate, read 1D & 2D barcodes. Developers and programmers can use Spire.BarCode to add Enterprise-Level barcode formats to their .net applications (ASP.NET, WinForms) quickly and easily. Below is how to use Spire.BarCode for .NET.
Step 1: Create Project
Create a C#/VB.NET Windows Forms Application project in visual studio, name it Barcode.
Step 2: Add Spire.Barcode.dll
- In Toolbox, right-click the blank area, select "Add Tab", name it "Spire.Barcode Controls".
- Right-click "Spire.Barcode Controls", select "Choose Items", select ".NET Framework Components", Click "Browse", find the Spire.Barcode.dll and double-click it.
- Then you will see "BarCodeControl" shown in "Spire.Barcode Controls" in Toolbox.
Step 3: Add Controls
Here is what the window looks like:
Step 4: Generate Barcode Image
btnCreate_Click is the method to generate barcode image. There are two import classes-BarCodeControl and BarCodeGenerator in this method. BarCodeControl stores information about barcode.
Here are some introductions about some of its properties:
Name of Property | Description |
Data | Stores the data that is to be encoded to one-dimension barcode. |
Data2D | Stores the data that is to be encoded to two-dimension barcode. |
Type | Indicates the type of barcode that is to be generated. |
HasBorder | Indicates whether barcode image has border. |
BorderDashStyle | Stores the type of border barcode image has. |
BarHeight | Stores the height of barcode image. |
CheckB_BarcodeText | Indicates whether to show the barcode text. |
TextFont | Stores the font of barcode text. |
ForeColor | Stores the fore color of barcode image. |
CheckB_Sum | Indicates whether to show the checksum digit in Code128 and EAN128 Barcodes. |
BarCodeGenerator is the class to generate barcode image. Its constructor takes one parameter – a BarCodeControl instance. It has a method called GenerateImage() whose return value is Image object to generate image.
//Generate the barcode based on the this.barCodeControl1 BarCodeGenerator generator = new BarCodeGenerator(this.barCodeControl1); Image barcode = generator.GenerateImage(); //save the barcode as an image barcode.Save("barcode.png");
'Generate the barcode based on the barCodeControl1 Dim generator As New BarCodeGenerator(barCodeControl1) Dim barcode As Image = generator.GenerateImage() 'save the barcode as an image barcode.Save("barcode.png")
Step 5: Scan Barcode Image
BarcodeScanner is the class to scan barcode image. Call its method Scan with the Bitmap object containing the barcode image, it returns a string [] value where the scanning result is stored.
And btnScan_Click uses the class BarcodeScanner to scan barcode image in its code.
Here is the code in btnScan_Click.
private void btnScan_Click(object sender, EventArgs e) { //scan the barcode string[] datas = Spire.Barcode.BarcodeScanner.Scan("barcode.png"); //show the scan result this.TextB_ScanResult.Text = datas[0]; }
Private Sub btnScan_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnScan.Click 'scan the barcode Dim datas() As String = Spire.Barcode.BarcodeScanner.Scan("barcode.png") 'show the scan result Me.TextB_ScanResult.Text = datas(0) End Sub
Step 6. Running
Run the project. You will see a window opened.
Put in some settings and click the button "Create". You will see the generated barcode image.
Click the button "Scan". You will see the barcode text shown in TextB_ScanResult.