2008-09-10 4 views
8

Word 2007은 .docx 형식으로 문서를 저장합니다.이 형식은 실제 문서와 함께 xml 파일을 포함하여 여러 가지 항목이 포함 된 zip 파일입니다.asp.net을 사용하여 .docx를 html로 변환하려면 어떻게해야합니까?

.docx 파일을 가져 와서 asp.net 웹 응용 프로그램의 폴더에 놓고 코드를 .docx 파일로 열고 (XML 부분) 문서를 웹으로 렌더링 할 수있게하려고합니다. 페이지.

나는 이것에 대해 더 많은 정보를 얻기 위해 웹을 검색해 왔지만 아직까지 많이 찾지 못했습니다. 내 질문은 :

  1. 는 (a)는 HTML에 XML을 변환하는 XSLT을 사용, 또는 (b)는 (HTML 또는로 변환 (예 : 3.5하여 XDocument 및 XElement를 같은) .NET의 XML 조작 라이브러리를 사용 c) 다른 사람?
  2. 이 작업을 수행 한 모든 오픈 소스 라이브러리/프로젝트에 대해 알고 계십니까?

고마워요!

답변

4

시험해보십시오. post? 나는 모르지만 당신이 찾고있는 것일 수 있습니다.

2

Word 2007에는 HTML로 변환하는 데 사용할 수있는 API가 있습니다. 여기에 그것에 대해 이야기하는 게시물은 http://msdn.microsoft.com/en-us/magazine/cc163526.aspx입니다. API에 대한 설명서를 찾을 수는 있지만 API에 HTML로 변환 기능이 있음을 기억합니다.

+0

어떤 API에 대해 더 구체적이고 어떤 "HTML로 변환"기능이 좋을까요? 아마도 당신은 패키지 클래스에 대해 이야기하고 있습니까? 이 "HTML로 변환"기능은 어디에 있습니까? – Jez

1

이 코드의 뜻은 내가 Interop를 사용하고

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\[email protected]\/\_\(\)]/","",$striped_content); 

    echo nl2br($striped_content); 
} 
0

을 텍스트로 .docx 파일을 변환하는 데 도움이됩니다. 그것은 다소 예지 적이지만 대부분의 경우에 잘 작동합니다.

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

이 하나의 문서 '경로

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; 
    } 

및 HTML로 문서를 변환하는이 하나의 변환 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(); 
      } 
     } 
    } 

단어를 죽이는 것은 재미 있지만, 거기에 매달 리거나 다른 사람들을 차단하게 할 수는 없습니까?

web/html에서 iframe에 html을 렌더링합니다.

도움말 문서 목록을 포함하는 드롭 다운이 있습니다. Value는 HTML 버전의 경로이고 text는 문서의 이름입니다. 선택된 인덱스에

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(); 

    } 

내가 mammoth.js, HTML에 DOCX 파일을 변환하는 자바 스크립트 라이브러리가 쓴

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"; 
     } 
    } 
+0

ASP.NET이나 다른 서버 기술에서 Office Interop을 사용하는 것은 끔찍한 생각입니다. 이 API는 데스크톱 응용 프로그램 (Office 응용 프로그램 제품군)을 자동화하기 위해 작성되었습니다. 서버 응용 프로그램은 여러면에서 서로 다르므로 Office Interop을 사용하는 것이 매우 바람직하지 않습니다. 또한 Microsoft에서 지원하지 않으며 Office 라이선스를 위반할 수도 있습니다. [서버 측 서버 자동화 고려 사항] (http://support.microsoft.com/kb/257757/ko) –

+0

@JohnSaunders, 나는 그것이 끔찍한 생각이지만 요구 사항이 범위에서 벗어나기 란 쉽지 않다는 것을 알고 있습니다. 나는이 질문에 대한 좋은 대안을 매우 고맙게 생각한다. –

3

프레임에 renedred되고, 변경되었습니다. .NET에서 렌더링 서버 측을 수행하려는 경우 .NET 버전 인 Mammoth available on NuGet도 있습니다.

맘모스는 Word의 단락 스타일 (예 : Heading 1)을 HTML/CSS의 적절한 태그 및 스타일 (예 : <h1>)에 매핑하는 등의 의미 정보를보고 깨끗한 HTML을 만들려고합니다.정확한 시각적 사본을 만들어내는 무언가가 원한다면, 맘모스는 아마 당신을위한 것이 아닙니다. 이미 잘 구조화되어 있고 깔끔한 HTML로 변환하려는 무언가가 있다면, Mammoth는 그 트릭을 할 것입니다.

+0

dotnet-mammoth는 유용한 라이브러리이므로 사용하고 있습니다. 난 당신이 그것을 볼 수있다면 배포시에만 문제가 [여기] (http://stackoverflow.com/questions/31885962/converting-docx-to-html-with-dotnet-mammoth-fails-at- 배포 서버). – zed

관련 문제