Thursday, 05 September 2013 07:27

Convert PDF Page to Image in C#

Image is one of the major data components except for text information, so convert PDF to image is a common need for users. Due to the complexity of PDF format, it is difficult to parse, draw and display content from PDF document. This article offers you a solution of convert PDF page to image in C# by using Spire.PDF.

By using Spire.PDF, you can easily convert any specific page of PDF document to BMP and Metafile image in .NET applications like console, Win Forms and ASP.NET. Make sure Spire.PDF for .NET has been installed correctly. The following steps demonstrate how to convert PDF to image with C# code in detail.

Step 1: Firstly Create a Console application, and reference System. Drawing.dll, Spire. Pdf.dll.

Step 2: Initiate an object of Spire. Pdf. PdfDocument

PdfDocument doc = new PdfDocument();

Step3: Call Spire. Pdf. PdfDocument object LoadFromFile method, and load a PDF document.

doc.LoadFromFile("sample.pdf");

Step 4: Now you can call SaveAsImage method of Spire. Pdf. PdfDocument object and save particular page as System.Drawing.Image object.

Image bmp = doc.SaveAsImage(0);

Step 5: Next, call another reload method of SaveAsImage from object of Spire.Pdf.PdfDocument, and save the particular page in the PDF file as System.Drawing.Imaging.Metafile object.

Image emf = doc.SaveAsImage(0,Spire.Pdf.Graphics.PdfImageType.Metafile);
Image zoomImg = new Bitmap((int)(emf.Size.Width * 2), (int)(emf.Size.Height * 2));
using (Graphics g = Graphics.FromImage(zoomImg))
{
  g.ScaleTransform(2.0f, 2.0f);
  g.DrawImage(emf, new Rectangle(new Point(0, 0), emf.Size), new Rectangle(new Point(0, 0), emf.Size), GraphicsUnit.Pixel);              
}

The following is the full code snippet used to display complete code needed when convert PDF to Image:

static void Main(string[] args)
{
 PdfDocument doc = new PdfDocument();
 doc.LoadFromFile("sample.pdf");
 Image bmp = doc.SaveAsImage(0);
 Image emf = doc.SaveAsImage(0,Spire.Pdf.Graphics.PdfImageType.Metafile);
 Image zoomImg = new Bitmap((int)(emf.Size.Width * 2), (int)(emf.Size.Height * 2));
 using (Graphics g = Graphics.FromImage(zoomImg))
  {
   g.ScaleTransform(2.0f, 2.0f);
   g.DrawImage(emf, new Rectangle(new Point(0, 0), emf.Size), new Rectangle(new Point(0, 0), emf.Size), GraphicsUnit.Pixel);              
  }
 bmp.Save("convertToBmp.bmp", ImageFormat.Bmp);
 System.Diagnostics.Process.Start("convertToBmp.bmp");
 emf.Save("convertToEmf.png", ImageFormat.Png);
 System.Diagnostics.Process.Start("convertToEmf.png");
 zoomImg.Save("convertToZoom.png", ImageFormat.Png);
 System.Diagnostics.Process.Start("convertToZoom.png");
 }

Run it, then you will get the image like the following:

Convert PDF Page to Image in C#

Published in Conversion
Monday, 29 July 2013 06:31

Convert XPS Files to PDF format in C#

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.

[C#]
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.

[C#]
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:

Published in Conversion
Thursday, 16 June 2011 06:31

Create PDF Converter

Spire.PDFConverter is created and designed by Spire.Office. With Spire.Offce, you can create a professional PDF Converter by yourself. Spire.Office includes Spire.Doc, Spire.XLS and Spire.PDF which can easily help you convert files from XLS/Xlsx to PDF, Doc/Docx to PDF, HTML to PDF, Text to PDF, XML to PDF, and Image to PDF. And Spire.PDF can help you encrypt the output PDF files and enable you add text/image watermark. Spire.Office for .NET is a compilation of every .NET component offered by e-iceblue. Using Spire.Office for .NET developers can create a wide range of applications. And this article will simply show you how to create a professional PDF Converter.

Install Spire.Office and follow the 4 steps below:

Step 1: Set Main Functions:

  • Convert files from Word Doc to PDF
  • Convert files from Excel to PDF
  • Convert files from HTML to PDF
  • Convert files from Text to PDF
  • Convert files from Image (all formats) to PDF
  • Encrypt output PDF files by setting password and permissions
  • Add text/image watermark
  • Batch conversion
  • Other friendly features

Step 2: Programming

PDFConverter classes relationship:

All converter classes inherit from abstract class, BaseConverter. And achieve IConvertable interface. There are 2 methods in BaseConverter: Encryption and Watermark

public void Encryption(PdfDocument pdfDocument)
        {
            Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (!string.IsNullOrEmpty(c.AppSettings.Settings["UserPassword"].Value))
            {
                pdfDocument.Security.UserPassword = c.AppSettings.Settings["UserPassword"].Value;
            }
            if (!string.IsNullOrEmpty(c.AppSettings.Settings["OwnPassword"].Value))
            {
                pdfDocument.Security.OwnerPassword = c.AppSettings.Settings["OwnPassword"].Value;
            }
            int Permissions;
            if (!string.IsNullOrEmpty(c.AppSettings.Settings["Permissions"].Value))
            {
                int.TryParse(c.AppSettings.Settings["Permissions"].Value, out Permissions);
                pdfDocument.Security.Permissions = (pdfSecurity.PdfPermissionsFlags)Permissions;
            }
        }

public void WaterMark(PdfPageCollection pages)
        {
            Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (!string.IsNullOrEmpty(c.AppSettings.Settings["TextWatermark"].Value))
            {
                foreach (PdfPageBase page in pages)
                {
                    TextWaterMark(page);
                }
            }
            if (!string.IsNullOrEmpty(c.AppSettings.Settings["ImageWatermark"].Value))
            {
                foreach (PdfPageBase page in pages)
                {
                    ImageWaterMark(page);
                }
            }
        }

Use ConverterFactory static method getConverter when need to get relevant Converter object.

          public static IConvertable GetConverter(string fileFullName)
        {
            FileInfo fi = new FileInfo(fileFullName);
            if (!File.Exists(fileFullName))
            {
                throw new Exception(fi.Name + " is not existed!");
            }
            switch (Path.GetExtension(fileFullName).ToLower())
            {
                case ".doc":
                case ".docx":
                case ".rtf":
                    return new WordConverter();
                case ".htm":
                case ".html":
                    return new HTMLConverter();
                case ".xls":
                case ".xlsx":
                    return new ExcelConverter();
                case ".txt":
                    return new TextConverter();
                case ".jpg":
                case ".png":
                case ".bmp":
                case ".gif":
                case ".tiff":
                    return new ImageConverter();
                default:
                    throw new Exception(fi.Name + " can not convert to pdf!");
            }
        }

Main Converter convert methods

          public class ExcelConverter : BaseConverter, IConvertable
    {
        #region IConvertable 

        public void Convert(string fileFullName)
        {
            if (!File.Exists(fileFullName))
            {
                throw new Exception(string.Format("{0} does not exist!", fileFullName));
            }
            Spire.Xls.Converter.PdfConverter pdfConverter = new Spire.Xls.Converter.PdfConverter(fileFullName);

            PdfDocument pdfDocument = new PdfDocument();
           
            pdfDocument.PageSettings.Orientation = pdf.PdfPageOrientation.Landscape;
            pdfDocument.PageSettings.Width = 970;
            pdfDocument.PageSettings.Height = 850;

            PdfConverterSettings settings = new PdfConverterSettings();
            settings.EmbedFonts = true;
            settings.TemplateDocument = pdfDocument;
            pdfDocument = pdfConverter.Convert(settings);
            //WaterMark(pdfDocument);
#if !FreeEdition
            WaterMark(pdfDocument.Pages);
            Encryption(pdfDocument);
#endif
            Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string savePath = Path.Combine(c.AppSettings.Settings["OutputFile"].Value, Path.GetFileName(fileFullName) + ".pdf");
            pdfDocument.SaveToFile(savePath);
            pdfDocument.Close();
        }

        #endregion
}


public class WordConverter : BaseConverter, IConvertable
    {
        #region IConvertable 

        public void Convert(string fileFullName)
        {
            if (!File.Exists(fileFullName))
            {
                throw new Exception(string.Format("{0} does not exist!", fileFullName));
            }
            Document document = new Document();
            document.LoadFromFile(fileFullName);
            Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string savePath = Path.Combine(c.AppSettings.Settings["OutputFile"].Value, Path.GetFileName(fileFullName) + ".pdf");
            using (MemoryStream stream = new MemoryStream())
            {
                document.SaveToStream(stream, FileFormat.PDF);
                document.Close();
                PdfDocument pdfdoc = new PdfDocument(stream);
                //WaterMark(pdfdoc);
#if !FreeEdition
                WaterMark(pdfdoc.Pages);
                Encryption(pdfdoc);
#endif

                pdfdoc.SaveToFile(savePath);
                pdfdoc.Close();
            }
        }

        #endregion
    }

public class HTMLConverter : BaseConverter, IConvertable
    {
        #region IConvertable 

        public void Convert(string fileFullName)
        {
            if (!File.Exists(fileFullName))
            {
                throw new Exception(string.Format("{0} does not exist!", fileFullName));
            }
            PdfDocument pdfdoc = new PdfDocument();
            //pdfdoc.Sections.Add().LoadFromHTML(fileFullName, true, true, new Spire.Pdf.HtmlConverter.PdfHtmlLayoutFormat() { FitToPage = Spire.Pdf.HtmlConverter.Clip.Width, Layout = pdfGraphics.PdfLayoutType.Paginate });
            pdfdoc.LoadFromHTML(fileFullName, true, true, true);
            //pdfdoc.LoadFromFile(url);
            FileInfo fi = new FileInfo(fileFullName);
            Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string savePath = Path.Combine(c.AppSettings.Settings["OutputFile"].Value, Path.GetFileName(fileFullName) + ".pdf");
            //WaterMark(pdfdoc);
#if !FreeEdition
            WaterMark(pdfdoc.Pages);
            Encryption(pdfdoc);
#endif
            pdfdoc.SaveToFile(savePath);
            pdfdoc.Close();
        }

        #endregion
    }

public class ImageConverter : BaseConverter, IConvertable
    {
      #region IConvertable 

        public void Convert(string fileFullName)
        {
            if (!File.Exists(fileFullName))
            {
                throw new Exception(string.Format("{0} does not exist!", fileFullName));
            }
            PdfDocument doc = new PdfDocument();
            PdfSection section = doc.Sections.Add();
           
            PdfPageBase page = doc.Pages.Add();
            PdfImage image = PdfImage.FromFile(fileFullName);

            float widthFitRate = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width;
            float heightFitRate = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height;
            float fitRate = Math.Max(widthFitRate, heightFitRate);
            float fitWidth = image.PhysicalDimension.Width / fitRate;
            float fitHeight = image.PhysicalDimension.Height / fitRate;

            page.Canvas.DrawImage(image, 0, 0, fitWidth, fitHeight);
            Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string savePath = Path.Combine(c.AppSettings.Settings["OutputFile"].Value, Path.GetFileName(fileFullName) + ".pdf");
            //WaterMark(doc);
#if !FreeEdition
            WaterMark(doc.Pages);
            Encryption(doc);
#endif
            doc.SaveToFile(savePath);
            doc.Close();
        } 
        #endregion
    }

Note: Spire.Doc and Spire.Pdf both have a namespace Spire.Pdf.Graphics. When use this namespace, use alias.

Step 3: Design Product Interface

When you finish programming, you need make your PDF Converter with a good appearance. If you are good at PS, your product should be very attractive.

Step 4: Test and fix bugs

At last, test the PDF converter. Make sure it's working well and with high performance.

Notes: Spire.PDFConverter is a tool and it can't be used as API in your applications. Only the components under Spire.Office can be used as API components in your applications. Spire.Office includes Spire.Doc (supports converting word to PDF, RTF to PDF), Spire XLS(supports converting XLS to PDF), Spire.PDF(supports converting HTML to PDF, Image to PDF), Spire.DataExport, Spire.PDFViewer, Spire.DocViewer and other components.

Published in Spire.PDFConverter
Monday, 30 May 2011 06:49

How to Convert Image to PDF

Spire.PDFConverter is a powerful PDF converting tool which enables to convert files from Doc to PDF, HTML to PDF, Image to PDF, Excel to PDF and Text to PDF. This article will show you how to use Spire PDF Converter to convert file from Image to PDF.

How to Convert Image to PDF?

Download Free Spire.PDFConverter, Only a few simple steps, you can finish a whole process of Image to PDF conversion by using Spire PDF Converter.

Step 1: Install and Run Spire PDF Converter

Step 2: Choose Image files

Click "Add File" button to select Image files which you want to convert to PDF format.

Step 3: Choose output file folder

Click "browse" button to select file folder where you want to place the output PDF files. Spire PDF Converter supports encrypt out PDF files and enables add watermark (Text/Image watermark).

Step 4: Run Image to PDF conversion

Click "Convert" button to start converting process.

Published in Spire.PDFConverter
Friday, 27 May 2011 05:42

How to Add PDF Watermark

Spire.PDFConverter allows users to add watermark after converting to PDF. The following steps will guide you how to add PDF watermark by using Spire.PDFConverter.

Step 1Download Spire.PDFConverter Install and Run

Step 2: Add Files

Click add file and choose the document which you want to convert and add watermark.

Step 3: Add PDF Watermark

Click Add Watermark and then a window pops up. If select Text Watermark, enter text. If select Image Watermark, click "Browse" to choose images. Then click "Watermark"

Step 4: Convert to PDF

Click "Convert". And the document will be converted to PDF with watermark added.

Published in Spire.PDFConverter