Click here to Skip to main content
15,886,422 members
Articles / Programming Languages / XML

Generate PDF Using C#

Rate me:
Please Sign up or sign in to vote.
4.75/5 (41 votes)
1 Feb 2009CPOL9 min read 545.2K   11K   262  
Using OpenOffice to convert different document types to PDF.
using System;
using System.IO;
using System.Threading;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.lang;

namespace OpenOfficeWrapper
{
    public class ConversionToPDF
    {
        // For thread safety
        private static Mutex _openOfficeLock = new Mutex(false, "OpenOfficeMutexLock-MiloradCavic");

        /// <summary>
        /// Converts document to PDF
        /// </summary>
        /// <param name="wordMl">WordML document in binary form</param>
        /// <returns>PDF in binary form</returns>
        public static byte[] Generate(byte[] wordMl)
        {
            string tempDirectory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).TrimEnd('\\');

            if (!Directory.Exists(tempDirectory))
                Directory.CreateDirectory(tempDirectory);

            Random r = new Random();
            string sourcePath = string.Format("{0}\\gnr-source-{1}-{2}.xml",
                tempDirectory, r.Next(), DateTime.Now.Ticks);
            string destinationPath = string.Format("{0}\\gnr-destination-{1}-{2}.pdf",
                tempDirectory, r.Next(), DateTime.Now.Ticks);

            File.WriteAllBytes(sourcePath, wordMl);

            Generate(sourcePath, destinationPath);

            byte[] resulting = File.ReadAllBytes(destinationPath);

            File.Delete(sourcePath);
            File.Delete(destinationPath);

            return resulting;
        }

        /// <summary>
        /// Converts document to PDF
        /// </summary>
        /// <param name="sourcePath">Path to document to convert(e.g: C:\test.doc)</param>
        /// <returns>PDF in binary form</returns>
        public static byte[] Generate(string sourcePath)
        {
            string tempDirectory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).TrimEnd('\\');

            if (!Directory.Exists(tempDirectory))
                Directory.CreateDirectory(tempDirectory);

            Random r = new Random();
            string destinationPath = string.Format("{0}\\gnr-destination-{1}-{2}.pdf",
                tempDirectory, r.Next(), DateTime.Now.Ticks);

            Generate(sourcePath, destinationPath);

            byte[] resulting = File.ReadAllBytes(destinationPath);

            File.Delete(destinationPath);

            return resulting;
        }

        /// <summary>
        /// Converts document to PDF
        /// </summary>
        /// <param name="sourcePath">Path to document to convert(e.g: C:\test.doc)</param>
        /// <param name="destinationPath">Path on which to save PDF (e.g: C:\test.pdf)</param>
        /// <returns>Path to destination file if operation is successful, or Exception text if it is not</returns>
        public static string Generate(string sourcePath, string destinationPath)
        {
            bool obtained = _openOfficeLock.WaitOne(Properties.Settings.Default.RequestTimeoutInSeconds * 1000, false);
            try
            {
                if (!obtained)
                {
                    throw new Exception(string.Format("Request for using OpenOffice wasn't served after {0} seconds. Aborting...", Properties.Settings.Default.RequestTimeoutInSeconds));
                }

                sourcePath = PathConverter(sourcePath);
                destinationPath = PathConverter(destinationPath);

                OfficeController.StartOpenOffice();

                //Get a ComponentContext
                unoidl.com.sun.star.uno.XComponentContext xLocalContext =
                   uno.util.Bootstrap.bootstrap();

                //Get MultiServiceFactory
                unoidl.com.sun.star.lang.XMultiServiceFactory xRemoteFactory =
                   (unoidl.com.sun.star.lang.XMultiServiceFactory)
                   xLocalContext.getServiceManager();
                //Get a CompontLoader
                XComponentLoader aLoader =
                   (XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");
                //Load the sourcefile
                XComponent xComponent = aLoader.loadComponentFromURL(sourcePath, "_blank", 0,
                   new unoidl.com.sun.star.beans.PropertyValue[0]);

                //Wait for loading
                while (xComponent == null)
                {
                    System.Threading.Thread.Sleep(1000);
                }

                saveDocument(xComponent, destinationPath);
                //Wait for input
                Console.WriteLine("Conversation completed!");

                xComponent.dispose();


                return destinationPath;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
            finally
            {
                if (obtained)
                    _openOfficeLock.ReleaseMutex();
            }
        }


        /// <summary>
        /// Saves the document.
        /// </summary>
        /// <param name="xComponent">The x component.</param>
        /// <param name="fileName">Name of the file.</param>
        private static void saveDocument(XComponent xComponent, string fileName)
        {
            unoidl.com.sun.star.beans.PropertyValue[] propertyValue =
               new unoidl.com.sun.star.beans.PropertyValue[1];

            propertyValue[0] = new unoidl.com.sun.star.beans.PropertyValue();
            propertyValue[0].Name = "FilterName";
            propertyValue[0].Value = new uno.Any("writer_pdf_Export");

            ((XStorable)xComponent).storeToURL(fileName, propertyValue);
        }

        /// <summary>
        /// Convert into OO file format
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns>The converted file</returns>
        private static string PathConverter(string file)
        {
            try
            {
                file = file.Replace(@"\", "/");

                return "file:///" + file;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
United States United States
If you liked this article, consider reading other articles by me. For republishing article on other websites, please contact me by leaving a comment.

Comments and Discussions