Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
A menudo se requiere la conversión de MHTML a DOCX para aprovechar el formato DOCX para tareas específicas. DOCX es un formato muy conocido para documentos de Microsoft Word. Puede contener una amplia gama de datos, incluidos texto, tablas, gráficos rasterizados y vectoriales, vídeos, sonidos y diagramas. Este formato es popular porque admite una amplia gama de funciones de formato y ofrece a los usuarios una variedad de opciones para escribir cualquier tipo de documento.
En este artículo, encontrará información sobre cómo convertir MHTML a DOCX usando los métodos ConvertMHTML() de la clase Converter y cómo aplicar DocSaveOptions y ICreateStreamProvider parámetros.
Puede convertir MHTML a DOCX con Aspose.HTML for .NET API en tiempo real. Cargue un archivo MHTML desde su sistema de archivos local, seleccione el formato de salida y ejecute el ejemplo. En este ejemplo, las opciones de guardar están configuradas de forma predeterminada. Recibirá inmediatamente el resultado de la conversión como un archivo separado.
Si desea convertir MHTML a DOCX mediante programación, consulte los siguientes ejemplos de código C#.
Los métodos estáticos de la clase Converter se utilizan principalmente como la forma más sencilla de convertir un código MHTML a varios formatos. Por ejemplo, puede convertir MHTML a DOCX en su aplicación C# literalmente con dos líneas de código.
1// Convert MHTML to DOCX in C#
2
3// Open an existing MHTML file for reading
4using FileStream stream = File.OpenRead(DataDir + "sample.mht");
5
6// Invoke the ConvertMHTML() method to convert MHTML to DOCX
7Converter.ConvertMHTML(stream, new DocSaveOptions(), Path.Combine(OutputDir, "convert-by-two-lines.docx"));Usar los métodos Converter.ConvertMHTML es la forma más común de convertir código MHTML a varios formatos. Con Aspose.HTML, puede convertir MHTML a formato DOCX mediante programación con control total sobre una amplia gama de parámetros de conversión.
El siguiente fragmento de código C# muestra cómo convertir MHTML a DOCX usando Aspose.HTML for .NET.
En el ejemplo, utilizamos el método OpenRead() de la clase System.IO.FileStream para abrir y leer archivos del sistema de archivos en la ruta especificada.
1// Convert MHTML to DOCX using C#
2
3// Open an existing MHTML file for reading
4using FileStream stream = File.OpenRead(DataDir + "sample.mht");
5
6// Prepare a path to save the converted file
7string savePath = Path.Combine(OutputDir, "sample-output.docx");
8
9// Create an instance of DocSaveOptions
10DocSaveOptions options = new DocSaveOptions();
11
12// Call the ConvertMHTML() method to convert MHTML to DOCX
13Converter.ConvertMHTML(stream, options, savePath);Aspose.HTML permite convertir MHTML a DOCX usando opciones de guardado predeterminadas o personalizadas. El uso de DocSaveOptions le permite personalizar el proceso de renderizado; puede especificar el tamaño de la página, márgenes, resoluciones, CSS, etc.
| Property | Description |
|---|---|
| FontEmbeddingRule | This property gets or sets the font embedding rule. Available values are Full and None. The default value is None. |
| Css | Gets a CssOptions object which is used for configuration of CSS properties processing. |
| DocumentFormat | This property gets or sets the file format of the output document. The default value is DOCX. |
| PageSetup | This property gets a page setup object and uses it for configuration output page-set. |
| HorizontalResolution | Sets horizontal resolution for output images in pixels per inch. The default value is 300 dpi. |
| VerticalResolution | Sets vertical resolution for output images in pixels per inch. The default value is 300 dpi. |
Para obtener más información sobre DocSaveOptions, lea el artículo Convertidores de ajuste fino.
Para convertir MHTML a DOCX con la especificación DocSaveOptions, debe seguir algunos pasos:
El siguiente ejemplo muestra cómo utilizar DocSaveOptions y crear un archivo DOCX con opciones de guardado personalizadas:
1// Convert MHTML to DOCX in C# with custom settings
2
3// Open an existing MHTML file for reading
4using FileStream stream = File.OpenRead(DataDir + "sample.mht");
5
6// Prepare a path to save the converted file
7string savePath = Path.Combine(OutputDir, "sample-options.docx");
8
9// Create an instance of DocxSaveOptions and set A5 as a page size
10DocSaveOptions options = new DocSaveOptions();
11options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(Length.FromInches(8.3f), Length.FromInches(5.8f)));
12
13// Call the ConvertMHTML() method to convert MHTML to DOCX
14Converter.ConvertMHTML(stream, options, savePath);En el ejemplo, utilizamos el método OpenRead() de la clase System.IO.FileStream para abrir y leer archivos fuente del sistema de archivos en la ruta especificada. El constructor
DocSaveOptions() inicializa una instancia de la clase DocSaveOptions que se pasa al método ConvertMHTML(). El método ConvertMHTML() toma la stream, las options, la ruta del archivo de salida savePath y realiza la operación de conversión. La clase DocSaveOptions proporciona numerosas propiedades que le brindan control total sobre una amplia gama de parámetros y mejoran el proceso de conversión de MHTML a formato DOCX. En el ejemplo, utilizamos la propiedad PageSetup que especifica el tamaño de página del documento DOCX.
Si es necesario guardar archivos en el almacenamiento remoto (por ejemplo, nube, base de datos, etc.), puede implementar la interfaz ICreateStreamProvider para tener control manual sobre el proceso de creación de archivos. Esta interfaz está diseñada como un objeto de devolución de llamada para crear una secuencia al comienzo del documento/página (según el formato de salida) y liberar la secuencia creada inicialmente después de renderizar el documento/página.
Aspose.HTML for .NET proporciona varios tipos de formatos de salida para operaciones de renderizado. Algunos de estos formatos producen un único archivo de salida (por ejemplo, PDF, XPS), otros crean varios archivos (formatos de imagen JPG, PNG, etc.).
El siguiente ejemplo muestra cómo implementar y utilizar su propio MemoryStreamProvider en la aplicación:
1// Implement a custom MemoryStream provider for advanced control over HTML rendering output streams
2
3class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider
4{
5 // List of MemoryStream objects created during the document rendering
6 public List<MemoryStream> Streams { get; } = new List<MemoryStream>();
7
8 public Stream GetStream(string name, string extension)
9 {
10 // This method is called when only one output stream is required, for instance for XPS, PDF or TIFF formats
11 MemoryStream result = new MemoryStream();
12 Streams.Add(result);
13 return result;
14 }
15
16 public Stream GetStream(string name, string extension, int page)
17 {
18 // This method is called when the creation of multiple output streams are required. For instance, during the rendering HTML to list of image files (JPG, PNG, etc.)
19 MemoryStream result = new MemoryStream();
20 Streams.Add(result);
21 return result;
22 }
23
24 public void ReleaseStream(Stream stream)
25 {
26 // Here you can release the stream filled with data and, for instance, flush it to the hard-drive
27 }
28
29 public void Dispose()
30 {
31 // Releasing resources
32 foreach (MemoryStream stream in Streams)
33 stream.Dispose();
34 }
35} 1// Convert MHTML to DOCX in C# using memory stream
2
3// Create an instance of MemoryStreamProvider
4using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
5
6// Open an existing MHTML file for reading
7using FileStream stream = File.OpenRead(DataDir + "sample.mht");
8
9// Prepare a path to save the converted file
10string savePath = Path.Combine(OutputDir, "stream-provider.docx");
11
12// Convert MHTML to DOCX by using the MemoryStreamProvider class
13Converter.ConvertMHTML(stream, new DocSaveOptions(), streamProvider);
14
15// Get access to the memory stream that contains the result data
16MemoryStream memory = streamProvider.Streams.First();
17memory.Seek(0, SeekOrigin.Begin);
18
19// Flush the result data to the output file
20using (FileStream fs = File.Create(savePath))
21{
22 memory.CopyTo(fs);
23}Aspose.HTML ofrece un Convertidor de MHTML a DOCX en línea gratuito que convierte archivos MHTML a DOCX con alta calidad, fácil y rápido. ¡Simplemente cargue, convierta sus archivos y obtenga resultados en unos segundos!
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.