Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

Generate PDF Using C#

, 1 Feb 2009
Using OpenOffice to convert different document types to PDF.
article_src.zip
Solution
!Ref
cli_basetypes.dll
cli_cppuhelper.dll
cli_types.dll
cli_ure.dll
OpenOfficeService
ClassDiagram1.cd
OpenOfficeService.csproj.user
Properties
Settings.settings
OpenOfficeService.Objects
Properties
OpenOfficeWrapper
Properties
Settings.settings
PDFWeb
App_Data
ExcelSheet.xls
PDFWeb.csproj.user
Properties
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

Predrag Tomasevic
Chief Technology Officer Atama Group
United States United States
http://www.linkedin.com/in/ptomasevic
 
Bitcoin wallet: 1ARXmh58S6aRiZPCbneDCzrB1HUU6PLmDQ

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 2 Feb 2009
Article Copyright 2008 by Predrag Tomasevic
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid