OpenXML HTML sang DOCX

Trong màn hình này, tôi trình bày cách bắt đầu từ con số không và xây dựng một ứng dụng như vậy bằng Visual Studio 2013. Lưu ý rằng không có gì về ứng dụng này dành riêng cho VS 2013. Cách tiếp cận và mã cũng sẽ hoạt động với VS 2012  hoặc 2010. Bên dưới màn hình, tôi liệt kê mã thú vị để bạn dễ dàng cắt và dán mã và xây dựng ứng dụng tương tự của riêng bạn

WebClient.ncoding has to be specified as UTF8, otherwise the downloaded HTML will be messy. Also above Grouping class is under Microsoft.FSharp.Linq.RuntimeHelpers namespace. This is the only IGrouping implementation that can be found in .NET libraries.

Thể hiện toàn bộ hướng dẫn dưới dạng một đoạn HTML duy nhất thông qua mẫu T4

Đoạn mã trên xây dựng và trả về một đối tượng Html, đại diện cho tất cả các chương và tất cả các phần của hướng dẫn. Loại Html thực sự là một mẫu T4 [Bộ công cụ chuyển đổi mẫu văn bản] cho toàn bộ hướng dẫn




    
        
        
            table {
                border-collapse: collapse;
            }

            table, th, td {
                border: 1px solid black;
            }
        
    
    

        


As fore mentioned.

represents each chapter title, and

represents each section title. A little CSS is used to unify all tables with 1 pixel solid border.  This Html.tt file will automatically generate a Html.cs file, containing above Html type.

Lớp Html được tạo là một lớp một phần, do đó một số mã tùy chỉnh có thể được thêm vào để trực quan hơn

internal partial class Html
{
    internal Html[string title, IEnumerable chapters]
    {
        this.Title = title;
        this.Chapters = chapters;
    }

    internal string Title { get; }

    internal IEnumerable Chapters { get; }
}

đơn giản. Để lấy chuỗi HTML, chỉ cần gọi Html. Phương thức TransformText, được xác định trong Html được tạo. cs

Chuyển đổi tài liệu HTML sang Word qua VSTO

Như đã đề cập trước đó, một cách khả thi là sử dụng Open XML SDK của Microsoft. Cực kỳ dễ dàng với trình trợ giúp của bên thứ ba HtmlToOpenXml, cũng có sẵn từ Nuget

Install-Package HtmlToOpenXml.dll

Đây là mã

private static byte[] HtmlToWord[string html, string fileName]
{
    using [MemoryStream memoryStream = new MemoryStream[]]
    using [WordprocessingDocument wordDocument = WordprocessingDocument.Create[
        memoryStream, WordprocessingDocumentType.Document]]
    {
        MainDocumentPart mainPart = wordDocument.MainDocumentPart;
        if [mainPart == null]
        {
            mainPart = wordDocument.AddMainDocumentPart[];
            new Document[new Body[]].Save[mainPart];
        }

        HtmlConverter converter = new HtmlConverter[mainPart];
        converter.ImageProcessing = ImageProcessing.AutomaticDownload;
        Body body = mainPart.Document.Body;

        IList paragraphs = converter.Parse[html];
        body.Append[paragraphs];

        mainPart.Document.Save[];
        return memoryStream.ToArray[];
    }
}

Thật không may, định dạng của tài liệu kết quả hoàn toàn bị rối. Không có thư viện trưởng thành nào khác cho việc này [Microsoft’s Power Tools for Open XML cung cấp API để chuyển đổi Open XML của tài liệu Word thành HTML, nhưng không có API để chuyển đổi HTML sang Open XML], vì vậy, theo cách khác, VSTO, sẽ là giải pháp

Microsoft word là một ứng dụng mạnh mẽ. Nó có thể trực tiếp mở tài liệu HTML và lưu nó dưới dạng tài liệu Word. Vì vậy, nhiệm vụ trở thành

  1. Lưu đối tượng Html ở trên dưới dạng tài liệu HTML
  2. Sử dụng ứng dụng Word để mở tài liệu HTML đã lưu
  3. Định dạng tài liệu
  4. Lưu tài liệu dưới dạng tài liệu từ
private static void ConvertDocument[
    string inputFile, WdOpenFormat inputFormat,
    string outputFile, WdSaveFormat outputFormat,
    Action format = null,
    bool isWordVisible = false]
{
    Application word = null;
    try
    {
        word = new Application { Visible = isWordVisible };

        Console.WriteLine[$"Opening {inputFile} as {inputFormat}."];
        word.Documents.Open[inputFile, Format: inputFormat];
        Document document = word.Documents[inputFile];

        format?.Invoke[document];

        Console.WriteLine[$"Saving {outputFile} as {outputFormat}"];
        document.SaveAs2[outputFile, outputFormat];
    }
    finally
    {
        word?.Documents?.Close[];
        word?.Quit[];
    }
}
Định dạng tài liệu từ qua VSTO

Nhiệm vụ có các bước sau [theo thứ tự]

  1. Download all referenced pictures [ tags in HTML], and save them along with the Word document, so that the document can be viewed offline.
  2. Áp dụng một mẫu được chỉ định [. dấu chấm] vào tài liệu Word. Đây là cách dễ nhất để định dạng tài liệu
    • chức vụ
    • mục lục
    • tiêu đề
    • chân trang [số trang]
    • vân vân
  3. Chèn mục lục chi tiết vào tài liệu Word, hiển thị tất cả các đề mục của hướng dẫn
  4. Insert a abstract table of contents to the Word document, which only shows chapter titles [“Heading 1” fields in Word, or

    tags in HTM].

  5. Insert a title to the Word document [“Title” field in word, or tag in HTML]
  6. Chèn tác giả bên cạnh tiêu đề
  7. Chèn số trang vào chân tài liệu Word
  8. Chèn chương [các trường có “Tiêu đề 1”] vào tiêu đề tài liệu Word qua FieldStyleRef

Và mã

private static void FormatDocument[Document document, Html html, string template, string author = "Dixin Yan"]
{
    document.InlineShapes
            .OfType[]
            .Where[shape => shape.Type == WdInlineShapeType.wdInlineShapeLinkedPicture]
            .ForEach[picture =>
            {
                Console.WriteLine[$"Downloading {picture.LinkFormat.SourceFullName}"];
                picture.LinkFormat.SavePictureWithDocument = true;
            }];

    Console.WriteLine[$"Applying template {template}"];
    document.set_AttachedTemplate[template];
    document.UpdateStyles[];

    Range range = document.Range[document.Content.Start, document.Content.Start];

    document.TablesOfContents.Add[range];

    TableOfContents table = document.TablesOfContents.Add[range, LowerHeadingLevel: 1];

    Console.WriteLine[$"Adding title {html.Title}"];
    Paragraph titleParagraph = document.Paragraphs.Add[range];
    titleParagraph.Range.Text = $"{html.Title}{Environment.NewLine}";
    range.set_Style["Title"];

    Console.WriteLine[$"Adding author {author}"];
    range = document.Range[table.Range.Start, table.Range.Start];
    Paragraph authorParagraph = document.Paragraphs.Add[range];
    authorParagraph.Range.Text = $"{author}{Environment.NewLine}";
    range.set_Style["Author"];

    range = document.Range[table.Range.End, table.Range.End];
    range.InsertBreak[WdBreakType.wdPageBreak];

    document.Sections.OfType[].ForEach[section =>
    {
        range = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
        range.Fields.Add[range, WdFieldType.wdFieldStyleRef, @"""Heading 1""", true];

        section.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add[
            WdPageNumberAlignment.wdAlignPageNumberCenter];
    }];
}

Lập trình VSTO không trực quan và API thiếu các ví dụ. Khá mất thời gian để chèn FieldStyleRef - tên kiểu không phải là “Heading 1”, mà là “"Heading 1"”, bắt buộc phải có dấu ngoặc kép xung quanh tên tham chiếu kiểu

Lưu dưới dạng tài liệu Word qua VSTO

Đây là phương pháp để lưu dưới dạng tài liệu Word [. tài liệu]

private static void SaveDocument[Html html, string outputDocument]
{
    string tempHtmlFile = Path.ChangeExtension[Path.GetTempFileName[], "htm"];
    string htmlContent = html.TransformText[];
    Console.WriteLine[$"Saving HTML as {tempHtmlFile}, {htmlContent.Length}."];
    File.WriteAllText[tempHtmlFile, htmlContent];

    string template = Path.Combine[PathHelper.ExecutingDirectory[], "Book.dot"];
    ConvertDocument[
        tempHtmlFile, WdOpenFormat.wdOpenFormatWebPages,
        outputDocument, WdSaveFormat.wdFormatDocument,
        document => FormatDocument[document, html, template]];
}

Và đây là cách gọi nó

private static void Main[string[] arguments]
{
    string outputDirectory = arguments.Any[] && !string.IsNullOrWhiteSpace[arguments.First[]]
        ? arguments.First[]
        : [PathHelper.TryGetOneDrive[out outputDirectory]
            ? Path.Combine[outputDirectory, @"Share\Book"]
            : Environment.GetFolderPath[Environment.SpecialFolder.DesktopDirectory]];

    Html html = DownloadHtml[];
    SaveDocument[html, Path.Combine[outputDirectory, $"{html.Title}.doc"]];
}

Theo mặc định, tài liệu được lưu vào thư mục OneDrive cục bộ của tôi, để người đọc và luôn nhận được phiên bản hướng dẫn mới nhất từ ​​đó. Nếu OneDrive không tồn tại, nó sẽ được lưu vào máy tính cục bộ

Làm cách nào để chuyển đổi HTML sang DOCX?

Cách chuyển đổi HTML sang DOCX .
Tải [các] tệp html lên Chọn tệp từ Máy tính, Google Drive, Dropbox, URL hoặc bằng cách kéo tệp trên trang
Kết quả là chọn "to docx" Chọn docx hoặc bất kỳ định dạng nào khác mà bạn cần [hơn 200 định dạng được hỗ trợ]
Tải xuống docx của bạn

Làm cách nào để chuyển đổi Docx sang HTML trong C#?

Cách chuyển đổi DOCX sang HTML .
Cài đặt 'Aspose. từ cho. NET'
Thêm tham chiếu thư viện [nhập thư viện] vào dự án C# của bạn
Mở tệp DOCX nguồn trong C#
Gọi phương thức 'Save[]', chuyển tên tệp đầu ra có phần mở rộng HTML
Nhận kết quả chuyển đổi DOCX dưới dạng HTML

Chủ Đề