Click or drag to resize

UseOfficeCloseOffice Method

Releases MS Office® library (MS Word, Excel, PowerPoint) from memory

Namespace: SautinSoft
Assembly: UseOffice (in UseOffice.dll) Version: 2024.6.26
Syntax
public void CloseOffice()
Example
ASP.Net - Convert Word Excel PowerPoint to PDF files in C#
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            convDir.DataSource = Enum.GetNames(typeof(SautinSoft.UseOffice.eDirection));
            convDir.DataBind();
        }
        resultMessage.Text = "";
        fileMessage.Text = "";
    }
    protected void convDir_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (uploadedDocument.PostedFile.FileName.Length == 0)
        {
            resultMessage.Text = "Please select an input document at first!";
            return;
        }


    }

    protected void convert_Click(object sender, EventArgs e)
    {
        if (uploadedDocument.PostedFile.FileName.Length == 0)
        {
            resultMessage.Text = "Please select an input document at first!";
            return;
        }

        // 1. Prepare a directory for converting and storing temporary files
        // Remove all files in this directory
        string workDirectory = @"/converted/";
        string workPath = Server.MapPath(".") + workDirectory;

        string[] allFiles = Directory.GetFiles(workPath, "*.*");
        foreach (string file in allFiles)
            File.Delete(file);



        // 2. Save a document from FileUpload control to a temporary file: "Hour-Min-Sec-MSec.xxx", e.g. "9-34-12-807.doc".
        // Because UseOffice .Net can convert only documents as files
        string fileName = String.Format("{0: h-m-s-f}", DateTime.Now);
        string tempFilePath = Path.Combine(workPath, fileName + Path.GetExtension(uploadedDocument.PostedFile.FileName));
        File.WriteAllBytes(tempFilePath, uploadedDocument.FileBytes);


        resultMessage.Text = "Converting ...";


        // 3. Get a converting direction which user has just choosed
        // Get a file extension for a resulting file.
        string ext = ".rtf";
        //get extension
        int pos = convDir.Text.LastIndexOf('_');
        pos++;
        ext = (convDir.Text.Substring(pos, convDir.Text.Length - pos)).ToLower();


        if (ext.CompareTo("text") == 0)
        {
            ext = "txt";
        }
        ext = "." + ext;

        // 4. Create a path for a resulted file.
        string resultPath = Path.Combine(workPath, Path.ChangeExtension(uploadedDocument.FileName, ext));

        // 5. Launch UseOffice .Net and start converting
        SautinSoft.UseOffice u = new SautinSoft.UseOffice();

        //only Word                                           
        if (convDir.Text == "DOC_to_RTF" || convDir.Text == "DOCX_to_RTF" || convDir.Text == "DOC_to_HTML" || convDir.Text == "DOCX_to_HTML" || convDir.Text == "DOC_to_Text" || convDir.Text == "HTML_to_DOC" || convDir.Text == "HTML_to_RTF" || convDir.Text == "HTML_to_Text" || convDir.Text == "RTF_to_Text" || convDir.Text == "RTF_to_HTML" || convDir.Text == "RTF_to_DOC" || convDir.Text == "DOC_to_PDF" || convDir.Text == "DOCX_to_PDF" || convDir.Text == "RTF_to_PDF")
        {
            u.InitWord();
        }
        //only Excel
        if (convDir.Text == "XLS_to_HTML" || convDir.Text == "XLS_to_XML" || convDir.Text == "XLS_to_CSV" || convDir.Text == "XLS_to_Text")
        {
            u.InitExcel();
        }
        //Word + Excel
        if (convDir.Text == "XLS_to_RTF" || convDir.Text == "XLS_to_PDF" || convDir.Text == "XLSX_to_RTF" || convDir.Text == "XLSX_to_PDF")
        {
            u.InitWord();
            u.InitExcel();
        }
        //only PowerPoint
        if (convDir.Text == "PPT_to_PDF" || convDir.Text == "PPT_to_HTML" || convDir.Text == "PPT_to_RTF" || convDir.Text == "PPTX_to_PDF")
        {
            u.InitPowerPoint();
        }
        SautinSoft.UseOffice.eDirection convDirection = (SautinSoft.UseOffice.eDirection)Enum.Parse(typeof(SautinSoft.UseOffice.eDirection), convDir.SelectedValue);

        if (File.Exists(resultPath))
        {
            File.Delete(resultPath);
        }


        // 6. Convert a temporary file to a desired result
        int result = u.ConvertFile(tempFilePath, resultPath, convDirection);        

        switch (result)
        {
                // 7. Show a resulted file as a link
            case 0: resultMessage.Text = "Converting successfully!";
                string href = Request.UrlReferrer.AbsoluteUri;
                href = href.Remove(href.LastIndexOf("/"));                
                href+= workDirectory + Path.GetFileName(resultPath);
                fileMessage.NavigateUrl = href;
                fileMessage.Target = "_blank";
                fileMessage.Text = Path.GetFileName(resultPath);
                break;

            case 1: resultMessage.Text = "Can't open input file."; break;
            case 2: resultMessage.Text = "Can't create output file."; break;
            case 3: resultMessage.Text = "Converting error!"; break;
            default: break;
        }


        //u.KillProcesses("WINWORD");
        //u.KillProcesses("EXCEL");
        //u.KillProcesses("POWERPNT");
        u.CloseOffice();

        //Remove temporary file
        File.Delete(tempFilePath);
    }    
}
ASPX - code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>UseOffice .Net - You will likely be surprised at the amount of conversion ways!</title>
    <style type="text/css">
<!--
.style1 {
  font-family: Verdana, Arial, Helvetica, sans-serif;  
    font-size: 20px;
}
        .auto-style1 {
            height: 41px;
        }
-->
    </style>
</head>
<body style="margin-left: 20px;">
<form id="form1" runat="server">
    <table width="100%"  border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td colspan="2" class="auto-style1"><span class="style1"><strong>UseOffice .Net</strong> <span style="font-size: 10pt"> - Requires MS Office installed, any version: 2000, XP, 2003, 2007, 2010, 2013, 2016 or 2019.</span></span></td>
      </tr>
      <tr>
        <td width="247"><img src="box_useoffice_net.jpg" width="247" height="250" alt=""/></td>
        <td>
          <p class="style1">Before deploying this sample at your server, please take a look at:<br />
              <a href="https://www.sautinsoft.com/products/useoffice/examples/installation-on-server.php" target="_blank">How to install UseOffice .Net
          at Windows Servers.</a></p>             
        </td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td></td>
      </tr>
      <tr>
        <td colspan="2" style="height: 168px"><div style="font-size: 12pt; font-family: Verdana"><p><b>Step 1:</b> Select a document (PDF, DOC, DOCX, RTF, HTML, XLS, XLSX, Text, CSV, PPT, PPTX):</p>
            <asp:FileUpload ID="uploadedDocument" runat="server" Width="805px" style="font-size: 12pt; font-family: Verdana" />
            <p><b>Step 2:</b> Specify the direction: &nbsp;
            <asp:DropDownList ID="convDir" runat="server" Font-Names="Verdana" Font-Size="12pt"
                Width="173px" OnSelectedIndexChanged="convDir_SelectedIndexChanged" style="font-size: 12pt; font-family: Verdana">
            </asp:DropDownList></p>            
            <p><b>Step 3: </b>
            <asp:Button ID="convert" runat="server" Font-Names="Verdana" Font-Size="12pt" Text="Convert" OnClick="convert_Click" style="font-size: 12pt; font-family: Verdana; width: 150px; height: 35px;" /></p>
                        <p>
            <asp:HyperLink ID="fileMessage" runat="server">[fileMessage]</asp:HyperLink>
            <br />
            <asp:Label ID="resultMessage" runat="server" Font-Bold="True" Font-Names="Verdana" ForeColor="#FF8000" Width="1024px"></asp:Label></p>            

                                              </div></td>
      </tr>
    </table>

    <div>        
        <br />
        &nbsp;
                    &nbsp;</div>
    <div align="center"><br />
        <span style="font-size: 9pt; font-family: Verdana"><a href="https://www.sautinsoft.com" target="_blank">Copyright &copy; SautinSoft 2002 - <script>document.write(new Date().getFullYear())</script></a> </span>
    </div>
</form>
</body>
</html>
ASP.Net - Convert Word Excel PowerPoint to PDF files in VB.Net
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Drawing

Partial Public Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            convDir.DataSource = System.Enum.GetNames(GetType(SautinSoft.UseOffice.eDirection))
            convDir.DataBind()
        End If
        resultMessage.Text = ""
        fileMessage.Text = ""
    End Sub
    Protected Sub convDir_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        If uploadedDocument.PostedFile.FileName.Length = 0 Then
            resultMessage.Text = "Please select an input document at first!"
            Return
        End If


    End Sub
    Protected Sub convert_Click(ByVal sender As Object, ByVal e As EventArgs)
        If uploadedDocument.PostedFile.FileName.Length = 0 Then
            resultMessage.Text = "Please select an input document at first!"
            Return
        End If

        ' 1. Prepare a directory for converting and storing temporary files
        ' Remove all files in this directory
        Dim workDirectory As String = "/converted/"
        Dim workPath As String = Server.MapPath(".") & workDirectory
        Dim allFiles() As String = Directory.GetFiles(workPath, "*.*")
        For Each file As String In allFiles
            System.IO.File.Delete(file)
        Next file


        ' 2. Save a document from FileUpload control to a temporary file: "Hour-Min-Sec-MSec.xxx", e.g. "9-34-12-807.doc".
        ' Because UseOffice .Net can convert only documents as files
        Dim fileName As String = String.Format("{0: h-m-s-f}", Date.Now)
        Dim tempFilePath As String = Path.Combine(workPath, fileName & Path.GetExtension(uploadedDocument.PostedFile.FileName))
        File.WriteAllBytes(tempFilePath, uploadedDocument.FileBytes)


        resultMessage.Text = "Converting ..."


        ' 3. Get a converting direction which user has just choosed
        ' Get a file extension for a resulting file.
        Dim ext As String = ".rtf"
        'get extension
        Dim pos As Integer = convDir.Text.LastIndexOf("_"c)
        pos += 1
        ext = (convDir.Text.Substring(pos, convDir.Text.Length - pos)).ToLower()


        If ext.CompareTo("text") = 0 Then
            ext = "txt"
        End If
        ext = "." & ext

        ' 4. Create a path for a resulted file.
        Dim resultPath As String = Path.Combine(workPath, Path.ChangeExtension(uploadedDocument.FileName, ext))

        ' 5. Launch UseOffice .Net and start converting
        Dim u As New SautinSoft.UseOffice()

        'only Word                                           
        If convDir.Text = "DOC_to_RTF" OrElse convDir.Text = "DOCX_to_RTF" OrElse convDir.Text = "DOC_to_HTML" OrElse convDir.Text = "DOCX_to_HTML" OrElse convDir.Text = "DOC_to_Text" OrElse convDir.Text = "HTML_to_DOC" OrElse convDir.Text = "HTML_to_RTF" OrElse convDir.Text = "HTML_to_Text" OrElse convDir.Text = "RTF_to_Text" OrElse convDir.Text = "RTF_to_HTML" OrElse convDir.Text = "RTF_to_DOC" OrElse convDir.Text = "DOC_to_PDF" OrElse convDir.Text = "DOCX_to_PDF" OrElse convDir.Text = "RTF_to_PDF" Then
            u.InitWord()
        End If
        'only Excel
        If convDir.Text = "XLS_to_HTML" OrElse convDir.Text = "XLS_to_XML" OrElse convDir.Text = "XLS_to_CSV" OrElse convDir.Text = "XLS_to_Text" Then
            u.InitExcel()
        End If
        'Word + Excel
        If convDir.Text = "XLS_to_RTF" OrElse convDir.Text = "XLS_to_PDF" OrElse convDir.Text = "XLSX_to_RTF" OrElse convDir.Text = "XLSX_to_PDF" Then
            u.InitWord()
            u.InitExcel()
        End If
        'only PowerPoint
        If convDir.Text = "PPT_to_PDF" OrElse convDir.Text = "PPT_to_HTML" OrElse convDir.Text = "PPT_to_RTF" OrElse convDir.Text = "PPTX_to_PDF" Then
            u.InitPowerPoint()
        End If
        Dim convDirection As SautinSoft.UseOffice.eDirection = CType(System.Enum.Parse(GetType(SautinSoft.UseOffice.eDirection), convDir.SelectedValue), SautinSoft.UseOffice.eDirection)

        If File.Exists(resultPath) Then
            File.Delete(resultPath)
        End If


        ' 6. Convert a temporary file to a desired result
        Dim result As Integer = u.ConvertFile(tempFilePath, resultPath, convDirection)

        Select Case result
                ' 7. Show a resulted file as a link
            Case 0
                resultMessage.Text = "Converting successfully!"
                Dim href As String = Request.UrlReferrer.AbsoluteUri
                href = href.Remove(href.LastIndexOf("/"))
                href &= workDirectory & Path.GetFileName(resultPath)
                fileMessage.NavigateUrl = href
                fileMessage.Target = "_blank"
                fileMessage.Text = Path.GetFileName(resultPath)

            Case 1
                resultMessage.Text = "Can't open input file."
            Case 2
                resultMessage.Text = "Can't create output file."
            Case 3
                resultMessage.Text = "Converting error!"
            Case Else
        End Select


        'u.KillProcesses("WINWORD");
        'u.KillProcesses("EXCEL");
        'u.KillProcesses("POWERPNT");
        u.CloseOffice()

        'Remove temporary file
        File.Delete(tempFilePath)
    End Sub
End Class
ASPX - code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>UseOffice .Net - You will likely be surprised at the amount of conversion ways!</title>
    <style type="text/css">
<!--
.style1 {
  font-family: Verdana, Arial, Helvetica, sans-serif;  
    font-size: 20px;
}
        .auto-style1 {
            height: 41px;
        }
-->
    </style>
</head>
<body style="margin-left: 20px;">
<form id="form1" runat="server">
    <table width="100%"  border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td colspan="2" class="auto-style1"><span class="style1"><strong>UseOffice .Net</strong> <span style="font-size: 10pt"> - Requires MS Office installed, any version: 2000, XP, 2003, 2007, 2010, 2013, 2016 or 2019.</span></span></td>
      </tr>
      <tr>
        <td width="247"><img src="box_useoffice_net.jpg" width="247" height="250" alt=""/></td>
        <td>
          <p class="style1">Before deploying this sample at your server, please take a look at:<br />
              <a href="https://www.sautinsoft.com/products/useoffice/examples/installation-on-server.php" target="_blank">How to install UseOffice .Net
          at Windows Servers.</a></p>             
        </td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td></td>
      </tr>
      <tr>
        <td colspan="2" style="height: 168px"><div style="font-size: 12pt; font-family: Verdana"><p><b>Step 1:</b> Select a document (PDF, DOC, DOCX, RTF, HTML, XLS, XLSX, Text, CSV, PPT, PPTX):</p>
            <asp:FileUpload ID="uploadedDocument" runat="server" Width="805px" style="font-size: 12pt; font-family: Verdana" />
            <p><b>Step 2:</b> Specify the direction: &nbsp;
            <asp:DropDownList ID="convDir" runat="server" Font-Names="Verdana" Font-Size="12pt"
                Width="173px" OnSelectedIndexChanged="convDir_SelectedIndexChanged" style="font-size: 12pt; font-family: Verdana">
            </asp:DropDownList></p>            
            <p><b>Step 3: </b>
            <asp:Button ID="convert" runat="server" Font-Names="Verdana" Font-Size="12pt" Text="Convert" OnClick="convert_Click" style="font-size: 12pt; font-family: Verdana; width: 150px; height: 35px;" /></p>
                        <p>
            <asp:HyperLink ID="fileMessage" runat="server">[fileMessage]</asp:HyperLink>
            <br />
            <asp:Label ID="resultMessage" runat="server" Font-Bold="True" Font-Names="Verdana" ForeColor="#FF8000" Width="1024px"></asp:Label></p>            

                                              </div></td>
      </tr>
    </table>

    <div>        
        <br />
        &nbsp;
                    &nbsp;</div>
    <div align="center"><br />
        <span style="font-size: 9pt; font-family: Verdana"><a href="https://www.sautinsoft.com" target="_blank">Copyright &copy; SautinSoft 2002 - <script>document.write(new Date().getFullYear())</script></a> </span>
    </div>
</form>
</body>
</html>
See Also