Pergunta

O Word 2007 salva seus documentos no formato .docx, que na verdade é um arquivo zip com um monte de coisas, incluindo um arquivo xml com o documento.

Quero poder pegar um arquivo .docx e soltá-lo em uma pasta em meu aplicativo da web asp.net e fazer com que o código abra o arquivo .docx e renderize o documento (parte xml do) como uma página da web.

Tenho pesquisado na web mais informações sobre isso, mas até agora não encontrei muita coisa.Minhas perguntas são:

  1. Você (a) usaria XSLT para transformar XML em HTML ou (b) usaria bibliotecas de manipulação de xml em .net (como XDocument e XElement em 3.5) para converter em HTML ou (c) outro?
  2. Você conhece alguma biblioteca/projeto de código aberto que tenha feito isso e que eu possa usar como ponto de partida?

Obrigado!

Foi útil?

Solução

Experimente isso publicar?Não sei, mas pode ser o que você está procurando.

Outras dicas

escrevi mamute.js, que é uma biblioteca JavaScript que converte arquivos docx em HTML.Se você quiser fazer a renderização do lado do servidor em .NET, também existe uma versão .NET do Mammoth disponível no NuGet.

Mammoth tenta produzir HTML limpo observando informações semânticas - por exemplo, mapeando estilos de parágrafo no Word (como Heading 1) para tags e estilos apropriados em HTML/CSS (como <h1>).Se você deseja algo que produza uma cópia visual exata, então Mammoth provavelmente não é para você.Se você tem algo que já está bem estruturado e deseja convertê-lo em HTML organizado, o Mammoth pode resolver o problema.

O Word 2007 possui uma API que você pode usar para converter para HTML.Aqui está um post que fala sobre isso http://msdn.microsoft.com/en-us/magazine/cc163526.aspx.Você pode encontrar documentação sobre a API, mas lembro que existe uma função de conversão para HTML na API.

Este código ajudará a converter .docx arquivo para texto

function read_file_docx($filename){

    $striped_content = '';
    $content = '';

    if(!$filename || !file_exists($filename)) { echo "sucess";}else{ echo "not sucess";}

    $zip = zip_open($filename);

    if (!$zip || is_numeric($zip)) return false;

    while ($zip_entry = zip_read($zip)) {

        if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

        if (zip_entry_name($zip_entry) != "word/document.xml") continue;

        $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

        zip_entry_close($zip_entry);
    }// end while

    zip_close($zip);

    //echo $content;
    //echo "<hr>";
    //file_put_contents('1.xml', $content);     

    $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
    $content = str_replace('</w:r></w:p>', "\r\n", $content);
     //header("Content-Type: plain/text");


    $striped_content = strip_tags($content);


      $striped_content = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$striped_content);

    echo nl2br($striped_content); 
}

Estou usando o Interop.É um tanto problemático, mas funciona bem na maioria dos casos.

using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;

Este retorna a lista de caminhos dos documentos convertidos em HTML

public List<string> GetHelpDocuments()
    {

        List<string> lstHtmlDocuments = new List<string>();
        foreach (string _sourceFilePath in Directory.GetFiles(""))
        {
            string[] validextentions = { ".doc", ".docx" };
            if (validextentions.Contains(System.IO.Path.GetExtension(_sourceFilePath)))
            {
                sourceFilePath = _sourceFilePath;
                destinationFilePath = _sourceFilePath.Replace(System.IO.Path.GetExtension(_sourceFilePath), ".html");
                if (System.IO.File.Exists(sourceFilePath))
                {
                    //checking if the HTML format of the file already exists. if it does then is it the latest one?
                    if (System.IO.File.Exists(destinationFilePath))
                    {
                        if (System.IO.File.GetCreationTime(destinationFilePath) != System.IO.File.GetCreationTime(sourceFilePath))
                        {
                            System.IO.File.Delete(destinationFilePath);
                            ConvertToHTML();
                        }
                    }
                    else
                    {
                        ConvertToHTML();
                    }

                    lstHtmlDocuments.Add(destinationFilePath);
                }
            }


        }
        return lstHtmlDocuments;
    }

E este para converter doc para html.

private void ConvertToHtml()
    {
        IsError = false;
        if (System.IO.File.Exists(sourceFilePath))
        {
            Microsoft.Office.Interop.Word.Application docApp = null;
            string strExtension = System.IO.Path.GetExtension(sourceFilePath);
            try
            {
                docApp = new Microsoft.Office.Interop.Word.Application();
                docApp.Visible = true;

                docApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                object fileFormat = WdSaveFormat.wdFormatHTML;
                docApp.Application.Visible = true;
                var doc = docApp.Documents.Open(sourceFilePath);
                doc.SaveAs2(destinationFilePath, fileFormat);
            }
            catch
            {
                IsError = true;
            }
            finally
            {
                try
                {
                    docApp.Quit(SaveChanges: false);

                }
                catch { }
                finally
                {
                    Process[] wProcess = Process.GetProcessesByName("WINWORD");
                    foreach (Process p in wProcess)
                    {
                        p.Kill();
                    }
                }
                Marshal.ReleaseComObject(docApp);
                docApp = null;
                GC.Collect();
            }
        }
    }

Matar a palavra não é divertido, mas não dá para deixar ela ficar pendurada aí e bloquear outras, né?

No web/html eu renderizo html para um iframe.

Há um menu suspenso que contém a lista de documentos de ajuda.Valor é o caminho para a versão HTML e texto é o nome do documento.

private void BindHelpContents()
    {
        List<string> lstHelpDocuments = new List<string>();
        HelpDocuments hDoc = new HelpDocuments(Server.MapPath("~/HelpDocx/docx/"));
        lstHelpDocuments = hDoc.GetHelpDocuments();
        int index = 1;
        ddlHelpDocuments.Items.Insert(0, new ListItem { Value = "0", Text = "---Select Document---", Selected = true });

        foreach (string strHelpDocument in lstHelpDocuments)
        {
            ddlHelpDocuments.Items.Insert(index, new ListItem { Value = strHelpDocument, Text = strHelpDocument.Split('\\')[strHelpDocument.Split('\\').Length - 1].Replace(".html", "") });
            index++;
        }
        FetchDocuments();

    }

no índice selecionado alterado, ele é renomeado para quadro

    protected void RenderHelpContents(object sender, EventArgs e)
    {
        try
        {
            if (ddlHelpDocuments.SelectedValue == "0") return;
            string strHtml = ddlHelpDocuments.SelectedValue;
            string newaspxpage = strHtml.Replace(Server.MapPath("~/"), "~/");
            string pageVirtualPath = VirtualPathUtility.ToAbsolute(newaspxpage);// 
            documentholder.Attributes["src"] = pageVirtualPath;
        }
        catch
        {
            lblGError.Text = "Selected document doesn't exist, please refresh the page and try again. If that doesn't help, please contact Support";
        }
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top