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