Click here to Skip to main content
12,629,383 members (35,602 online)
Click here to Skip to main content

Stats

368.8K views
9.3K downloads
258 bookmarked
Posted

Generate PDF Using C#

, 1 Feb 2009 CPOL
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)

Share

About the Author

lepipele
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.

Bitcoin wallet:
1ARXmh58S6aRiZPCbneDCzrB1HUU6PLmDQ

Blogs I enjoy:
http://blog.codinghorror.com/

You may also be interested in...

Pro
Pro
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.161205.3 | Last Updated 2 Feb 2009
Article Copyright 2008 by lepipele
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid