Mostrando entradas con la etiqueta docx. Mostrar todas las entradas
Mostrando entradas con la etiqueta docx. Mostrar todas las entradas

sábado, 11 de octubre de 2025

WEBPROPv2 (XII). Mostrar ficheros en un control FastHTML

 Veamos el código que ejecuta en python  un uvicorn y muestra el fichero que le decimos:

El truco está en utilizar libreoffice para transformar los ficheros de ofimática ( ods,odt, xls,xlsx, doc,docx ..) a html y mostrar el html generado.

Si el fichero es grande puede enlentecer mucho la carga, conversión y muestra

import base64
import mimetypes
from fasthtml import common as fh
import uvicorn
from pathlib import Path
import subprocess
import shutil


app = fh.FastHTML()



def convertir_a_html(path: Path) -> Path | None:
    """Convierte el archivo a HTML usando LibreOffice y devuelve la ruta resultante."""
    output_dir = Path("/tmp")
    result = subprocess.run(
        ["libreoffice", "--headless", "--convert-to", "html", str(path), "--outdir", str(output_dir)],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    if result.returncode == 0:
        html_file = output_dir / (path.stem + ".html")
        if html_file.exists():
            return html_file
    return None

def generar_viewer(path: Path):
    mime_type, _ = mimetypes.guess_type(str(path))
    if not mime_type:
        mime_type = "application/octet-stream"

    data = path.read_bytes()
    b64 = base64.b64encode(data).decode("utf-8")

    # Imágenes
    if mime_type.startswith("image/"):
        return fh.Img(src=f"data:{mime_type};base64,{b64}", cls="img-fluid rounded shadow", alt=path.name)

    # PDF
    if mime_type == "application/pdf":
        return fh.Iframe(src=f"data:{mime_type};base64,{b64}",
                         style="width:100%; height:90vh;",
                         cls="border rounded shadow-sm",
                         title=path.name)

    # Texto
    if mime_type.startswith("text/"):
        content = data.decode("utf-8", errors="ignore")
        return fh.Pre(content, cls="bg-light p-3 border rounded")

    # ODS / XLSX / DOCX — convertir a HTML
    convertible_types = {
        "application/vnd.oasis.opendocument.spreadsheet",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/vnd.oasis.opendocument.text",
        'application/msword',
        'application/vnd.ms-excel',
    }
    if mime_type in convertible_types:
        html_file = convertir_a_html(path)
        if html_file:
            html_content = html_file.read_text(encoding="utf-8", errors="ignore")
            return fh.Div(fh.NotStr(html_content), cls="border p-2 bg-white shadow-sm")

    # Otros: ofrecer descarga
    return fh.Div(
        fh.P("El archivo no puede mostrarse directamente en el navegador.", cls="text-muted"),
        fh.A("Descargar archivo", href=f"data:{mime_type};base64,{b64}",
             download=path.name, cls="btn btn-primary mt-3"),
        cls="text-center"
    )

@app.get("/mostrarfichero")
async def mostrar_fichero(req):
    path_param = req.query_params.get("pathfichero")
    if not path_param:
        return fh.Html(fh.Body(fh.H4("⚠️ Falta el parámetro 'pathfichero'")))
    path = Path(path_param)
    if not path.exists():
        return fh.Html(fh.Body(fh.H4(f"❌ Archivo no encontrado: {path_param}")))
    viewer = generar_viewer(path)
    return fh.Html(
        fh.Head(fh.Link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css")),
        fh.Body(
            fh.Div(
                fh.H3(f"Mostrando: {path.name}", cls="text-center my-4"),
                viewer,
                cls="container"
            )
        )
    )

if __name__ == "__main__":
    print("🚀 Abre en el navegador: http://localhost:8000/mostrarfichero?pathfichero=/home/edu/kk/ODS01.ods")
    uvicorn.run(app, host="0.0.0.0", port=8000)


Y para ejecutarlo, tal como se dice en as últimas sentencias, ejecutamos el programa python desde visual studio code y en un navegador apuntamos a esa ruta donde en /home/kk/OSD01.ods está un fichero de hoja de cálculo

http://localhost:8000/mostrarfichero?pathfichero=/home/edu/kk/ODS01.ods


lunes, 9 de agosto de 2021

Convertir documentos a PDF con Java, LibreOffice y jodconverter

0.Introducción

Si se quiere opciones libres, hay pocas alternativas y gran parte de llas no funcionan bien en todos los casos.

Parece ser que se está optando por utilizar LibreOffice como motor de conversión y llamarlo desde Java.

La librería jodconverter es de gran ayuda pues simplifica el código.

1. Instalación de LibreOffice en un servidor Ubuntu sin GUI

Según askubuntu , la instalación en un servidor sin GUI se hace con este comando

apt-get install libreoffice --no-install-recommends

 

2. Crear un proyecto gradle y dar las dependencias

Aquí mostramos un ejemplo del build.gradle y se muestra las dependencias de jodconverter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java library project to get you started.
 * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
 * User Manual available at https://docs.gradle.org/7.0.2/userguide/building_java_projects.html
 */

plugins {
    // Apply the java-library plugin for API and implementation separation.
    id 'java-library'
}

repositories {
    mavenCentral()
    jcenter() // jcenter is deprecated, however the Gretty plugin still uses stuff from jcenter: https://github.com/gretty-gradle-plugin/gretty/issues/192
    maven { url "https://jitpack.io" } /*https://github.com/ralfstuckert/pdfbox-layout*/

}

// My customization 
//project.jar.destinationDirectory = file("$rootDir/mytarget")
project.jar.destinationDirectory = file("$rootDir/../mytargets")  
project.archivesBaseName = 'a-report-utils' 
project.version = '1.0'

dependencies {
    // Use JUnit test framework.
    testImplementation 'junit:junit:4.13.1'
    
    
    /* Jakarta */
    compileOnly "jakarta.annotation:jakarta.annotation-api:2.0.0"
    
    /***********************************************************************
    *********************** LOMBOK DEFINITION ******************************/
    compileOnly             'org.projectlombok:lombok:1.18.20'
    annotationProcessor     'org.projectlombok:lombok:1.18.20'
    testCompileOnly         'org.projectlombok:lombok:1.18.20'
    testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'
    /************************************************************************/
   
    
    /*JOD CONVERSOR */
    implementation 'org.jodconverter:jodconverter-core:4.4.2'
    implementation 'org.jodconverter:jodconverter-local:4.4.2'

    /* HIbernate */
    implementation "org.hibernate:hibernate-core:5.4.31.Final"
    implementation "org.hibernate:hibernate-validator:7.0.1.Final"
}

3. Programa simple de llamadas para la conversión

Aquí tenemos el código que es prácticamente calcado al de ejemplo de llamada local del wiki de jodconversion

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package tests;

import java.io.File;

import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.office.OfficeUtils;
import org.jodconverter.local.JodConverter;
import org.jodconverter.local.office.LocalOfficeManager;

public class KKLibreOffice {

	public static void main(String[] args) throws OfficeException {
		// TODO Auto-generated method stub
		
		/*
		OfficeManager officeManager =
			    LocalOfficeManager.builder()
			        .portNumbers(2002, 2003, 2004, 2005)
			        .build();
        */
		File inputFile = new File("/home/ximo/80244.docx");
		File outputFile = new File("/home/ximo/80244.docx.pdf");

		// Create an office manager using the default configuration.
		// The default port is 2002. Note that when an office manager
		// is installed, it will be the one used by default when
		// a converter is created.
		final LocalOfficeManager officeManager = LocalOfficeManager.install(); 
		try {

		    // Start an office process and connect to the started instance (on port 2002).
		    officeManager.start();

		    // Convert
		    JodConverter
		             .convert(inputFile)
		             .to(outputFile)
		             .execute();
		} finally {
		    // Stop the office process
		    OfficeUtils.stopQuietly(officeManager);
		}
		
	}

}