Showing posts with label VB.Net. Show all posts
Showing posts with label VB.Net. Show all posts

Monday, February 4, 2008

Convert a Multipage TIFF to PDF in .NET

Introduction
This article shows you how to create a PDF document from a multipage TIFF document in both C# and VB.NET using TallPDF.NET 2.0.

Sample Files

Download Code

Download code + resources (C# and VB.NET)

How it works
Basically, there three steps involved in the conversion:
  1. Get the number of frames.
  2. Add each frame to a document.
  3. Write the document.

1. Get the number of frames
A TIFF image can have multiple frames (pages). The input TIFF document in this sample has 4 frames. To retrieve the number of frames, use ImageShape.GetFrameCount(). This method has three overloads, allowing you to specify the image as a path, a stream or a System.Drawing.Bitmap object.

2. Add each frame to a document.
The next step is to create a new document and add a new page for each frame. We already know the number of frames so we can use a for-next loop to iterate over the frames.

3. Write the document.
Call Document.Write to write the PDF document to disk.

TallPDF.NET Sample Code
The easiest way to implement this using TallPDF is to create a new section for each frame. This ensures the original size of each image is retained and no scaling or clipping will occur.

[C# Sample Code]


//1. Get number of pages/images used in TIFF file
int frameCount = ImageShape.GetFrameCount( tiffPath );

//2. Add a section for each frame

// Create new (Pdf)document
Document doc = new Document();

// Iterate over frames
for ( int frameIndex=0; frameIndex < frameCount; frameIndex++ )
{
//Create a section and add it to the document.
Section section = doc.Sections.Add();
section.StartOnNewPage = true;

//Set Margins to zero; the image will span the entire page
section.LeftMargin = 0;
section.RightMargin = 0;
section.TopMargin = 0;
section.BottomMargin = 0;

// Load the frame into an Image paragraph
Image frame = new Image( tiffPath, frameIndex );

//Set PageSize from the Image dimensions
section.PageSize.Width = frame.Width;
section.PageSize.Height = frame.Height;

//Add the image to the section
section.Paragraphs.Add( frame );
}

// 3. Stream the PDF to a file
using( FileStream fs = new FileStream( "out.pdf", FileMode.Create ) )
{
//Write the file
doc.Write( fs );
}
[VB.NET]

'1. Get number of pages/images used in TIFF file
Dim frameCount As Integer = ImageShape.GetFrameCount(tiffPath)

' 2. Add a section for each frame

' Create a new TallPDF document
Dim doc As Document = New Document

' Iterate over the frames
Dim frameIndex As Integer
For frameIndex = 0 To frameCount - 1 Step 1

'Create a section and add it to the document.
Dim section As Section = doc.Sections.Add()
section.StartOnNewPage = True

'Set Margins to zero; the image will span the entire page
section.LeftMargin = 0
section.RightMargin = 0
section.TopMargin = 0
section.BottomMargin = 0

' Load the frame into an Image paragraph
Dim frame As New Image(tiffPath, frameIndex)

' Set PageSize from the Image dimensions
section.PageSize.Width = frame.Width
section.PageSize.Height = frame.Height

' Add the image to the section
section.Paragraphs.Add(frame)

Next frameIndex

'3. Stream the PDF to a file
Dim fs As FileStream = New FileStream("out.pdf", FileMode.Create)

Try

'Write the file
doc.Write(fs)

Finally

fs.Close()

End Try

Using PDFKit.NET
To implement this with PDFKit.NET we need a slightly different approach. PDFKit.NET has a page-based object model as opposed to TallPDF.NET's flow model. So we'll add a new page for each frame and use an ImageShape to place the frame on that page.

[C#]

//1. Get number of pages/images used in TIFF file
int frameCount = ImageShape.GetFrameCount( tiffPath );

//2. Add a page for each frame
// Create new (Pdf)document
Document doc = new Document();
// Iterate over frames
for ( int frameIndex=0; frameIndex < frameCount; frameIndex++ )
{
// Load the frame into an Image paragraph.
ImageShape frame = new ImageShape( tiffPath, frameIndex );

// Create a new page with the same size as the image.
Page page = new Page( frame.Width, frame.Height );
doc.Pages.Append( page );

//Add the image to the page
page.Underlay.Add( frame );
}

// 3. Stream the PDF to a file
using( FileStream fs = new FileStream( "out.pdf", FileMode.Create ) )
{
//Write the file
doc.Write( new BinaryWriter( fs ) );
}

[VB.NET]

'1. Get number of pages/images used in TIFF file
Dim frameCount As Integer = ImageShape.GetFrameCount(tiffPath)

' 2. Add a section for each frame

' Create a new TallPDF document
Dim doc As Document = New Document

' Iterate over the frames
Dim frameIndex As Integer
For frameIndex = 0 To frameCount - 1 Step 1

' Load the frame into an Image paragraph.
Dim frame As New ImageShape(tiffPath, frameIndex)

' Create a new page with the same size as the image.
Dim page As New Page(frame.Width, frame.Height)
doc.Pages.Append(page)

'Add the image to the page
page.Underlay.Add(frame)

Next frameIndex

'3. Stream the PDF to a file
Dim fs As FileStream = New FileStream("out.pdf", FileMode.Create)

Try

'Write the file
doc.Write(New BinaryWriter(fs))

Finally

fs.Close()

End Try

Imaging considerations
In this article we've used images based on files because TallPDF.NET and PDFKit.NET are highly optimized to work with files and streams. Older versions of both components (before TallPDF.NET 2.0.24 and PDFKit.NET 1.0.24) were based on GDI+ Bitmaps (System.Drawing.Bitmap). While quite flexible, GDI+ also introduces performace and quality issues. GDI+ uses a lot of resources to hold entire bitmaps in memory, often uncompressed (!). In addition to this, GDI+ has a nasty habit of converting image data to whatever format is best suited for on screen display, meaning that the actual color values in the image may change (!).

Using files and streams allows for efficient seeking and caching, resulting in greater performance. In addition to this, the image processing subsystem is specificaly designed not to modify the image data itself. So, when ever possible, use images from files or streams.

About TallComponents
TallComponents specializes in .NET PDF components. You can visit TallComponents at http://www.tallcomponents.com/. Here you can download evaluations for all our PDF-related .NET components and get support.


Copyright © 2001-2005 TallComponents BV

Sunday, January 6, 2008

Free eBooks from Microsoft Press

Microsoft Press has made three books available in PDF format to download for free. These books include:

Tuesday, October 16, 2007

Calling a Stored Procedure from your VB.Net Program


This is a very simple video showing how to call a stored procedure from your VB.Net program or application.

Sunday, September 23, 2007

Free eBooks from Apress

Apress has made a number of their books available as free ebooks. Here is a current list of the free ebooks available:

  • Practical Common Lisp
  • Enterprise Java Development on a Budget: Leveraging Java Open Source Technologies
  • Beginning J2EE 1.4: From Novice to Professional
  • Google, Amazon, and Beyond: Creating and Consuming Web Services
  • Pro JSP, Third Edition
  • Writing Perl Modules for CPAN
  • XML Programming: Web Applications and Web Services With JSP and ASP
  • COM and .NET Interoperability
  • Programming VB .NET: A Guide For Experienced Programmers
  • A Programmer's Introduction to PHP 4.0

These ebooks are available to download for free in PDF format from the Apress web site.

Saturday, August 25, 2007

Dream.In.Code Releases VB.NET Cheat Sheet

Just in time for back-to-school, Dream.In.Code® has released their free VB.NET cheat sheet. The VB.NET reference sheet is a full color, printable document with the most commonly used VB.NET syntax. The reference sheet may be downloaded and printed at the following URL: http://www.dreamincode.net/forums/showtopic31908.htm

"The new VB.NET cheat sheet is perfect for students" said Richard McCutchen, a Dream.In.Code member. The cheat sheet includes over 20 different syntaxes including data types, arrays, if/else statements, loops, and error handling.

This is not the first reference sheet from Dream.In.Code. They have four others: C++, Java, Visual Basic 6, and ColdFusion. "Several more reference sheets are in the works including an advanced VB.NET and PHP" said Chris Kenworthy, Dream.In.Code owner. All the reference sheets may be downloaded at the following URL: http://www.dreamincode.net/forums/showtopic17947.htm

To date, over 100,000 people have downloaded the free reference sheets from Dream.In.Code.

About Dream.In.Code
Dream.In.Code is a leading programming and web development community with over 40,000 members. Membership is free and visitors have access to forums, code snippets, blogs, tutorials, and resources. URL: http://www.DreamInCode.net

Saturday, May 19, 2007

Convert an Excel Chart to Image

Introduction
Charts are visually appealing and make it easy for users to see comparisons, patterns, and trends in data. For instance, rather than having to analyze several columns of worksheet numbers, you can see at a glance whether sales are falling or rising over quarterly periods, or how the actual sales compare to the projected sales.

Sometimes, you do need to present the chart in your applications or web pages. You might need to insert it into a Word Document, a PDF file, a Power Point Presentation or in some other scenario. Simply you want the chart should be rendered as an image, so that you may paste it into your applications with ease. A Picture is worthwhile. Frequently, in the course of work, one has to present statistical and graphical information in an easy to understand and an easy to maintain manner.

You might try Office Automation but Office automation has its own drawbacks. There are several reasons and issues involved: e.g., Security, Stability, Scalability/Speed, Price, Features etc. In Short, there are many reasons, with the top one being that Microsoft themselves strongly recommends against Office automation from software solutions.

There is another option which you can use to convert an Excel Chart to an image using Aspose.Cells. This is a brand new feature offered by Aspose.Cells which is more advanced and of the essence from many of its Features List. In this article, we create some console applications in Visual Studio.Net, that will convert the Excel Charts to render the image files with a few and simplest lines of code using Aspose.Cells API. The conversion is performed with precision and accuracy.

Aspose.Cells: The Real Product
I would take this opportunity to introduce the product to you. Aspose.Cells is an Excel® spreadsheet reporting component that enables you to read and write Excel® spreadsheets without utilizing Microsoft Excel® installed either on the client or server side. Aspose.Cells is a very feature rich component that offers much more than just basic exporting of data. With Aspose.Cells developers can export data, format spreadsheets in every detail and at every level, import images, import charts, create charts, manipulate charts, stream Excel® data, save in various formats including XLS, CSV, SpreadsheetML, TabDelimited, TXT, XML (Aspose.Pdf integrated) and many more. All the Aspose components are totally independent and are not affiliated with, nor authorized, sponsored by Microsoft Corporation. To know more about the product information, features and for a programmer’s guide, check Aspose.Cells Decumentation and online featured demos. You may download its evaluation version for free.

Performing the Task
For demonstration, I choose some common tasks here. I have created two charts (a pie chart and a column chart) in MS Excel and covert these charts to image files using the simplest API of Aspose.Cells with a few lines of code. For conversion we shall create two console applications.

Following is the task list:

  • Converting a Pie Chart to an Image File.
  • Converting a Column Chart to an Image File.
Converting a Pie Chart to an Image File

First we create a pie chart in MS Excel and next we convert the chart to an image file.

Creating a Pie Chart in MS Excel
I opened a new workbook in MS Excel and input some sales data of the different regions into a worksheet. I, then, created a pie chart based on the data and save the excel file. Following is the screenshot of the file created in MS Excel:



Converting Chart to Image
Now I convert the chart to an image file.

Download and Install Aspose.Cells
First, you need to download Aspose.Cells for .Net. Install it on your development computer. All Aspose components, when installed, work in evaluation mode. The evaluation mode has no time limit and it only injects watermarks into produced documents.

Create a Project
Start Visual Studio. Net and create a new console application. This example will show a C# console application, but you can use VB.NET too.

Add References
This project will use Aspose.Cells. So, you have to add reference to Aspose.Cells component in your project. E.g., add a reference to ….\Program Files\Aspose\Aspose.Cells\Bin\Net1.0\Aspose.Cells.dll



Code Snippet
Following is the actual code (Written in C#) used by the component to accomplish the task. You may see that very few lines of code are used to accomplish the task.
//Create a new workbook.
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
//Open the existing excel file which contains the pie chart.
workbook.Open("d:\\piechart.xls");
//Get the designer chart (first chart) in the first worksheet.
//of the workbook.
Chart chart = workbook.Worksheets[0].Charts[0];
//Convert the chart to an image file.
System.Drawing.Bitmap bitmap = chart.ToImage();
//Save the chart image (jpg) file to disk.
bitmap.Save(@"d:\PieChart.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);

Additionally I write its parallel VB.Net code here for your convenience:
'Create a new workbook.
Dim workbook As Aspose.Cells.Workbook = New Aspose.Cells.Workbook()
'Open the existing excel file which contains the pie chart.
workbook.Open("d:\piechart.xls");
'Get the designer chart (first chart) in the first worksheet.
'of the workbook.
Dim chart As Chart = workbook.Worksheets(0).Charts(0)
'Convert the chart to an image file.
Dim bitmap As System.Drawing.Bitmap = chart.ToImage()
'Save the chart image (jpg) file to disk.
bitmap.Save("d:\PieChart.jpg",System.Drawing.Imaging.ImageFormat.Jpeg)

After executing the above code, a jpg file is created based on the pie chart in the template excel file. Here is the screenshot of the output file:



Converting a Column Chart to an Image File

First we create a column chart in MS Excel and next we convert the chart to an image file as we did it before.

Creating a Column Chart in MS Excel
I opened a new workbook in MS Excel and input some marketing costs of the different regions into a worksheet. I, then, created a column chart based on the data and save the excel file. Following is the screenshot of the file created in MS Excel:




Converting Chart to Image
Now I convert the chart to an image file. I‘ll skip the conventional steps here like creating a new project in Visual Studio.Net or adding reference to Aspose.Cells.dll file. I already did it in the first task. I only write here the actual code with presentation of the output image file.

Code Snippet

Following is the actual code (Written in C#) used by the component to accomplish the task. The code is similar to the previous one:
//Create a new workbook.
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
//Open the existing excel file which contains the column chart.
workbook.Open("d:\\columnchart.xls");
//Get the designer chart (first chart) in the first worksheet.
//of the workbook.

Chart chart = workbook.Worksheets[0].Charts[0];
//Convert the chart to an image file.
System.Drawing.Bitmap bitmap = chart.ToImage();
//Save the chart image (jpg) file to disk.
bitmap.Save(@"d:\ColumnChart.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);

Additionally I write its parallel VB.Net code here for your convenience:
'Create a new workbook.
Dim workbook As Aspose.Cells.Workbook = New Aspose.Cells.Workbook()
'Open the existing excel file which contains the column chart.
workbook.Open("d:\columnchart.xls");
'Get the designer chart (first chart) in the first worksheet.
'of the workbook.

Dim chart As Chart = workbook.Worksheets(0).Charts(0)
'Convert the chart to an image file.
Dim bitmap As System.Drawing.Bitmap = chart.ToImage()
'Save the chart image (jpg) file to disk.
bitmap.Save("d:\ColumnChart.jpg",System.Drawing.Imaging.ImageFormat.Jpeg)

After executing the above code, a jpg file is created based on the column chart in the template excel file. Here is the screenshot of the output file:



Summary
In this article I have presented how can we convert an excel chart to render an image file using Aspose.Cells component. Hopefully, it will give you some insight, and you will be able to utilize it some scenarios. Since the Chart2Image feature was really demanding and required by some of Aspose customers. And this is the result of some workout by Aspose.Cells Product Team. The feature is still young, so there might be some precision and accuracy issues occurred in some cases. We are working to enhance the conversion to make it more elegant and sophisticated and will mend any deficiency if found to strengthen it more.

Aspose.Cells can offer more flexibility than others for solutions and provides outstanding speed, efficiency and reliability to meet specific business application requirements. The results do show that Aspose.Cells has benefited from years of research, design and careful tuning.

We heartily welcome your queries, comments and suggestions at Aspose.Cells Forum. We warranty a prompt reply within minutes or hours, Thank you!