1

mi pregunta es muy confusa espero darme a entender correctamente,

tengo el siguiente Json extraido de un PDF, cabe mencionar que esta simplificado, solo inclui la una pagina por cuestiones de limites de caracteres, pero deseo buscar en todas las pags, la estructura es la siguiente

{
    "meta": {
        "info": {
            "PDFFormatVersion": "1.4",
            "Language": null,
            "EncryptFilterName": null,
            "IsLinearized": false,
            "IsAcroFormPresent": false,
            "IsXFAPresent": false,
            "IsCollectionPresent": false,
            "IsSignaturesPresent": false,
            "Creator": "JasperReports (reporteSemanasCotizadas)",
            "Producer": "iText 2.1.7 by 1T3XT",
            "ModDate": "D:20220713094658-05'00'",
            "CreationDate": "D:20220713094658-05'00'"
        },
        "metadata": null
    },
    "pages": [
        {
            "pageInfo": {
                "num": 1,
                "scale": 1,
                "rotation": 0,
                "offsetX": 0,
                "offsetY": 0,
                "width": 612,
                "height": 792
            },
            "links": [],
            "content": [
                {
                    "x": 225.13,
                    "y": 108.78999999999996,
                    "str": "Instituto Mexicano del Seguro Social",
                    "dir": "ltr",
                    "width": 161.7399999999999,
                    "height": 10,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 438.82,
                    "y": 210.27999999999997,
                    "str": "DD",
                    "dir": "ltr",
                    "width": 8.664,
                    "height": 6,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 460.82800000000003,
                    "y": 210.27999999999997,
                    "str": "MM",
                    "dir": "ltr",
                    "width": 9.996,
                    "height": 6,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 484.16800000000006,
                    "y": 210.27999999999997,
                    "str": "YYYY",
                    "dir": "ltr",
                    "width": 16.008,
                    "height": 6,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 247.53,
                    "y": 282.04,
                    "str": "Tu detalle de semanas cotizadas",
                    "dir": "ltr",
                    "width": 116.94399999999999,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 201.57,
                    "y": 141.78999999999996,
                    "str": "Constancia de Semanas Cotizadas en el IMSS",
                    "dir": "ltr",
                    "width": 207.8699999999999,
                    "height": 10,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 462.83,
                    "y": 245.03999999999996,
                    "str": "363",
                    "dir": "ltr",
                    "width": 13.344000000000001,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 47,
                    "y": 226.03999999999996,
                    "str": "NSS:",
                    "dir": "ltr",
                    "width": 18.672,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 47,
                    "y": 205.03999999999996,
                    "str": "JUAN PEREZ GOMEZ",
                    "dir": "ltr",
                    "width": 154.24800000000002,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 70,
                    "y": 226.03999999999996,
                    "str": "21139854785",
                    "dir": "ltr",
                    "width": 48.928000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                }
            ]
        },
        {
            "pageInfo": {
                "num": 2,
                "scale": 1,
                "rotation": 0,
                "offsetX": 0,
                "offsetY": 0,
                "width": 612,
                "height": 792
            },
            "links": [],
            "content": [
                {
                    "x": 225.13,
                    "y": 108.78999999999996,
                    "str": "Instituto Mexicano del Seguro Social",
                    "dir": "ltr",
                    "width": 161.7399999999999,
                    "height": 10,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 312,
                    "y": 216.95000000000005,
                    "str": "17/09/2021",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 147,
                    "y": 196.95000000000005,
                    "str": "BAJA CALIFORNIA",
                    "dir": "ltr",
                    "width": 70.23999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 388,
                    "y": 216.95000000000005,
                    "str": "Salario Base de Cotización */",
                    "dir": "ltr",
                    "width": 103.59999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 216.95000000000005,
                    "str": "Fecha de alta",
                    "dir": "ltr",
                    "width": 48.472000000000016,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 232,
                    "y": 216.95000000000005,
                    "str": "Fecha de baja",
                    "dir": "ltr",
                    "width": 50.695999999999984,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 147,
                    "y": 216.95000000000005,
                    "str": "20/01/2020",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 196.95000000000005,
                    "str": "Entidad federativa",
                    "dir": "ltr",
                    "width": 64.48,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 518.86,
                    "y": 216.95000000000005,
                    "str": "$ 620.67",
                    "dir": "ltr",
                    "width": 31.13600000000005,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 156.95000000000005,
                    "str": "Nombre del patrón",
                    "dir": "ltr",
                    "width": 66.24800000000002,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 147,
                    "y": 156.95000000000005,
                    "str": "TCL MOKA MANUFACTURING",
                    "dir": "ltr",
                    "width": 113.33599999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 176.95000000000005,
                    "str": "Registro Patronal",
                    "dir": "ltr",
                    "width": 61.80000000000001,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 147,
                    "y": 176.95000000000005,
                    "str": "A086348210",
                    "dir": "ltr",
                    "width": 45.368,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 322.26,
                    "y": 252.03999999999996,
                    "str": "Fecha de movimiento",
                    "dir": "ltr",
                    "width": 76.47199999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 129.6,
                    "y": 252.03999999999996,
                    "str": "Tipo de movimiento",
                    "dir": "ltr",
                    "width": 69.79999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 479.32,
                    "y": 252.03999999999996,
                    "str": "Salario Base",
                    "dir": "ltr",
                    "width": 45.352,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 340.48,
                    "y": 272.03999999999996,
                    "str": "17/09/2021",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 154.5,
                    "y": 272.03999999999996,
                    "str": "BAJA",
                    "dir": "ltr",
                    "width": 20.008000000000003,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 486.43,
                    "y": 272.03999999999996,
                    "str": "$ 620.67",
                    "dir": "ltr",
                    "width": 31.135999999999992,
                    "height": 8,
                    "fontName": "Helvetica"
                },
            ]
        },
        {
            "pageInfo": {
                "num": 3,
                "scale": 1,
                "rotation": 0,
                "offsetX": 0,
                "offsetY": 0,
                "width": 612,
                "height": 792
            },
            "links": [],
            "content": [
                {
                    "x": 225.13,
                    "y": 108.78999999999996,
                    "str": "Instituto Mexicano del Seguro Social",
                    "dir": "ltr",
                    "width": 161.7399999999999,
                    "height": 10,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 322.26,
                    "y": 141.03999999999996,
                    "str": "Fecha de movimiento",
                    "dir": "ltr",
                    "width": 76.47199999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 129.6,
                    "y": 141.03999999999996,
                    "str": "Tipo de movimiento",
                    "dir": "ltr",
                    "width": 69.79999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 479.32,
                    "y": 141.03999999999996,
                    "str": "Salario Base",
                    "dir": "ltr",
                    "width": 45.352,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 340.48,
                    "y": 161.03999999999996,
                    "str": "01/07/2019",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 109.82,
                    "y": 161.03999999999996,
                    "str": "MODIFICACION DE SALARIO",
                    "dir": "ltr",
                    "width": 109.35199999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 486.43,
                    "y": 161.03999999999996,
                    "str": "$ 325.18",
                    "dir": "ltr",
                    "width": 31.135999999999992,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 340.48,
                    "y": 181.03999999999996,
                    "str": "24/06/2019",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 140.5,
                    "y": 181.03999999999996,
                    "str": "REINGRESO",
                    "dir": "ltr",
                    "width": 48.007999999999996,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 486.43,
                    "y": 181.03999999999996,
                    "str": "$ 324.74",
                    "dir": "ltr",
                    "width": 31.135999999999992,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 42,
                    "y": 201.03999999999996,
                    "str": "/* Valor del último salario base de cotización diario en pesos.",
                    "dir": "ltr",
                    "width": 215.64800000000008,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 312,
                    "y": 301.95,
                    "str": "26/06/2019",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 147,
                    "y": 281.95,
                    "str": "BAJA CALIFORNIA",
                    "dir": "ltr",
                    "width": 70.23999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 388,
                    "y": 301.95,
                    "str": "Salario Base de Cotización */",
                    "dir": "ltr",
                    "width": 103.59999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 301.95,
                    "str": "Fecha de alta",
                    "dir": "ltr",
                    "width": 48.472000000000016,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 232,
                    "y": 301.95,
                    "str": "Fecha de baja",
                    "dir": "ltr",
                    "width": 50.695999999999984,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 147,
                    "y": 301.95,
                    "str": "23/05/2018",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 281.95,
                    "str": "Entidad federativa",
                    "dir": "ltr",
                    "width": 64.48,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 518.86,
                    "y": 301.95,
                    "str": "$ 324.74",
                    "dir": "ltr",
                    "width": 31.13600000000005,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 241.95000000000005,
                    "str": "Nombre del patrón",
                    "dir": "ltr",
                    "width": 66.24800000000002,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 147,
                    "y": 241.95000000000005,
                    "str": "NOMINA INTEGRAL DE SOLUCIONES PRODUCTIVAS",
                    "dir": "ltr",
                    "width": 202.25600000000006,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 261.95000000000005,
                    "str": "Registro Patronal",
                    "dir": "ltr",
                    "width": 61.80000000000001,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 147,
                    "y": 261.95000000000005,
                    "str": "Z312983510",
                    "dir": "ltr",
                    "width": 44.92,
                    "height": 8,
                    "fontName": "Helvetica"
                }
            ]
        }
    ],
    "filename": "./Employees/123.pdf"
}

El Json contiene un historial laboral mediante tablas que siempre tienen los mismos encabezados y que siempre tiene la misma estructura pero puede cambiar su tamaño dependiendo de los movimientos del usuario consultado en el reporte, el JSON contiene las coordenadas de cada string en X,Y, deseo crear un loop con todos los empleos que el usuario tuvo, debido a que el numero de empleos por cada usuario varia, no es correcto extraer el texto mediante sus coordenadas, puesto que dependiendo del numero de empleos que tiene un usuario las coordenadas variaran.

Para intentar solucionarlo tengo la siguiente funcion que consulte en este link busca un valor como el encabezado de la tabla en el JSON y extrae el valor anterior al localizado:

function searchByPrev(pages, txt) {
    /*// Init txt
    txt = txt.toLowerCase();*/

    // Loop in all pages
    for (let i = 0; i < pages.length; i++)

        // Loop in all content
        for (let j = 0; j < pages[i].content.length; j++)

            // Test text  and if match return next content
            // (If you write j-1, you can have searchByNext function)
            if (pages[i].content[j].str == txt && pages[i].content[j + 1])

                // Return result
                return pages[i].content[j + 1].str;

    // No results found
    return 'NotFound';
}

El problema que me encuentro al usar esta funcion es que el JSON se imprime desordenado y en ocasiones tengo dos valores buscados uno seguido del otro, los valores que busco pertenecen a los encabezados siguientes, es el bloque por cada uno de los empleos:

Este es el formato por cada uno de los empleos

El codigo que imprime la respuesta en la consola es el siguiente:

//almacenar en variable
let result = JSON.stringify({
    nombre: searchByPosition(reporte.pages, 47, 205),
    curp: searchByPosition(reporte.pages, 75, 246),
    nss: searchByPosition(reporte.pages, 70, 226),
    semanasCotizadas: {
        semanasCotizadas: searchByPosition(reporte.pages, 123, 322),
        semanasReintegradas: searchByPosition(reporte.pages, 303, 322),
        semanasDescontadas: searchByPosition(reporte.pages, 479, 322),
    },
    historialLaboral: [historial]
}, null, "\t");
// imprimir el resultado en la consola
console.log(result);

He creado un elemento que contendra el loop de los empleos y lo he agregado al codigo de arriba mediante la variable historial, se que esta mal, es solo un ejemplo, soy muy nuevo en Javascript y no se me ocurre una manera de obtener cada empleo en algo tan dinamico:

let historial = [reporte]
    .forEach((historial) => {
        {
            fechaAlta = searchByPrev(historial.pages, 'Fecha de baja')
            fechaBaja = searchByPrev(reporte.pages, ''),
                salarioBaseCotizacion = searchByPrev(historial.pages, 'Entidad federativa'),
                entidadFederativa = searchByPrev(reporte.pages, ''),
                nombrePatron = searchByPrev(historial.pages, 'Nombre del patrón'),
                registroPatronal = searchByPrev(historial.pages, 'Registro Patronal')
            movimientos =
            {
                "tipo": 'BAJA',
                "fechaMovimiento": '17/09/2021',
                "salarioBase": '$ 620.67'
            },
            {
                "tipo": "MODIFICACION DE SALARIO",
                "fechaMovimiento": '01/09/2021',
                "salarioBase": '$ 620.67'
            }
        }
    });

Esta es la respuesta que actualmente me arroja la consola:

{                                            
  nombre: 'HERNANDEZ LOPEZ JUAN', 
  curp: 'HEHC960204HBMHR08',                
  nss: '2113254845',                        
  semanasCotizadas: {                        
    semanasCotizadas: '363',                 
    semanasReintegradas: '0',                
    semanasDescontadas: '0'                  
  },                                         
  historialLaboral: [ undefined ]            
}

Y asi es como lo necesito:

{
    "nombre": "HERNANDEZ LOPEZ JUAN",
    "curp": "HEHC960204HBMHR08",                
    "nss": "2113254845",
    "semanasCotizadas": {
        "semanasCotizadas": "363",
        "semanasReintegradas": "0",
        "semanasDescontadas": "0"
    },
    "historialLaboral": [
        {
            "fechaAlta": "01/10/2020",
            "fechaBaja": "Vigente",
            "salarioBaseCotizacion": "$148.1",
            "entidadFederativa": "NUEVO LEÓN",
            "nombrePatron": "VERTICAL CONNECTION SA DE CV",
            "registroPatronal": "Y393262110"
        },
        {
            "fechaAlta": "23/09/2020",
            "fechaBaja": "08/10/2020",
            "salarioBaseCotizacion": "$156.78",
            "entidadFederativa": "NUEVO LEÓN",
            "nombrePatron": "ROSTA CONSULTORES Y ASESORES SA DE CV",
            "registroPatronal": "Y404318210"
        },
        {
            "fechaAlta": "16/02/2019",
            "fechaBaja": "16/10/2020",
            "salarioBaseCotizacion": "$139.36",
            "entidadFederativa": "NUEVO LEÓN",
            "nombrePatron": "COMERCIALIZADORA SLS",
            "registroPatronal": "Y392535210"
        },
    ],
    "estatus": "OK",
    "claveMensaje": "0"
}
                                        
2
  • El problema que me encuentro al usar esta función es que el JSON se imprime desordenado Por favor agrega el JSON que se imprime por consola para poder entenderte. el 18 jul. 2022 a las 3:42
  • Andres, el Json que imprime desordenado es el del Pdf y es el que se encuentra al principio, ese json lo quiero trabajar para que quede como el que agregue al final, edite la pregunta y agregue la respuesta de la consola en cuanto al codigo final que tengo actualmente, ese seria el resultado y agregue tambien la manera en la que necesito que se imprima. el 18 jul. 2022 a las 5:33

2 respuestas 2

2
+350

Si están desordenados, ordénalos!

Aprovechando las coordenadas de los objetos puedes ordenarlos por su posición vertical, sabiendo que el primer elemento es la etiqueta y el siguiente es el valor correspondiente.

Usando una técnica de parseo mediante tokens, se detectan ciertas palabras (frases) clave. Al encontrarse la frase se asigna el token como si fuera una bandera para indicar que el próximo elemento es el valor de dicho token, que por cierto, es el nombre de la propiedad del empleado.

let empleado = { historial : [] } // Empleado inicializado
let tmp = null       // Elemento del historial
let token = null     // El token actual
var tokens = { "nombrePatron" : "Nombre del patrón"
             , "registroPatronal" : "Registro Patronal"
             , "entidadFederativa" : "Entidad federativa"
             , "fechaAlta" : "Fecha de alta"
             , "fechaBaja" : "Fecha de baja"
             , "salarioBaseCotizacion" : "Salario Base de Cotización"
             }
json.pages.forEach(
   function(pagina,i){
      // Eliminamos elementos vacíos
      let contenido = pagina.content.filter(
                        function(x){
                           return !( x 
                                    && Object.getPrototypeOf(x) === Object.prototype 
                                    && Object.keys(x).length === 0
                                   )
                        }
                      )
      contenido.sort(
         function(a,b){
            // Ordenamiento por posición Y
            if( a.y < b.y )
               return -1
            if( a.y > b.y )
               return 1
            // Misma posición Y, se orderna por posición X
            if( a.x < b.x )
               return -1
            if( a.x > b.x )
               return 1
            return 0
         }
      )
      
      // En la primer pagina estan los datos generales
      if( i === 0 ){ 
         console.log("Ordenado",contenido)
         empleado.nombre = contenido[2].str
         empleado.nss = contenido[7].str
         empleado.semanasCotizadas = { semanasCotizadas : contenido[8].str }
      }else{      
         contenido.forEach(
            function(x){
               if( token ){
                  if( tmp === null )
                     tmp = {}
                  tmp[token] = x.str
                  token = null
               }else{
                  token = Object.keys(tokens).find( k => tokens[k] === x.str ) 
                  if( token == tokens[0] )
                     if( tmp != null ){
                        empleado.historial.push(tmp)
                        tmp = null
                     }
                  if(token)
                     console.log('El siguiente es', token)
               }
            }
         )
         if( tmp != null ) // Último empleador remanente
            empleado.historial.push(tmp)
      }      
   }
)
console.log("Empleado",empleado)
<script>
  let json = {
    "meta": {
        "info": {
            "PDFFormatVersion": "1.4",
            "Language": null,
            "EncryptFilterName": null,
            "IsLinearized": false,
            "IsAcroFormPresent": false,
            "IsXFAPresent": false,
            "IsCollectionPresent": false,
            "IsSignaturesPresent": false,
            "Creator": "JasperReports (reporteSemanasCotizadas)",
            "Producer": "iText 2.1.7 by 1T3XT",
            "ModDate": "D:20220713094658-05'00'",
            "CreationDate": "D:20220713094658-05'00'"
        },
        "metadata": null
    },
    "pages": [
        {
            "pageInfo": {
                "num": 1,
                "scale": 1,
                "rotation": 0,
                "offsetX": 0,
                "offsetY": 0,
                "width": 612,
                "height": 792
            },
            "links": [],
            "content": [
                {
                    "x": 225.13,
                    "y": 108.78999999999996,
                    "str": "Instituto Mexicano del Seguro Social",
                    "dir": "ltr",
                    "width": 161.7399999999999,
                    "height": 10,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 438.82,
                    "y": 210.27999999999997,
                    "str": "DD",
                    "dir": "ltr",
                    "width": 8.664,
                    "height": 6,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 460.82800000000003,
                    "y": 210.27999999999997,
                    "str": "MM",
                    "dir": "ltr",
                    "width": 9.996,
                    "height": 6,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 484.16800000000006,
                    "y": 210.27999999999997,
                    "str": "YYYY",
                    "dir": "ltr",
                    "width": 16.008,
                    "height": 6,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 247.53,
                    "y": 282.04,
                    "str": "Tu detalle de semanas cotizadas",
                    "dir": "ltr",
                    "width": 116.94399999999999,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 201.57,
                    "y": 141.78999999999996,
                    "str": "Constancia de Semanas Cotizadas en el IMSS",
                    "dir": "ltr",
                    "width": 207.8699999999999,
                    "height": 10,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 462.83,
                    "y": 245.03999999999996,
                    "str": "363",
                    "dir": "ltr",
                    "width": 13.344000000000001,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 47,
                    "y": 226.03999999999996,
                    "str": "NSS:",
                    "dir": "ltr",
                    "width": 18.672,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 47,
                    "y": 205.03999999999996,
                    "str": "JUAN PEREZ GOMEZ",
                    "dir": "ltr",
                    "width": 154.24800000000002,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 70,
                    "y": 226.03999999999996,
                    "str": "21139854785",
                    "dir": "ltr",
                    "width": 48.928000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                }
            ]
        },
        {
            "pageInfo": {
                "num": 2,
                "scale": 1,
                "rotation": 0,
                "offsetX": 0,
                "offsetY": 0,
                "width": 612,
                "height": 792
            },
            "links": [],
            "content": [
                {
                    "x": 225.13,
                    "y": 108.78999999999996,
                    "str": "Instituto Mexicano del Seguro Social",
                    "dir": "ltr",
                    "width": 161.7399999999999,
                    "height": 10,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 312,
                    "y": 216.95000000000005,
                    "str": "17/09/2021",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 147,
                    "y": 196.95000000000005,
                    "str": "BAJA CALIFORNIA",
                    "dir": "ltr",
                    "width": 70.23999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 388,
                    "y": 216.95000000000005,
                    "str": "Salario Base de Cotización */",
                    "dir": "ltr",
                    "width": 103.59999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 216.95000000000005,
                    "str": "Fecha de alta",
                    "dir": "ltr",
                    "width": 48.472000000000016,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 232,
                    "y": 216.95000000000005,
                    "str": "Fecha de baja",
                    "dir": "ltr",
                    "width": 50.695999999999984,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 147,
                    "y": 216.95000000000005,
                    "str": "20/01/2020",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 196.95000000000005,
                    "str": "Entidad federativa",
                    "dir": "ltr",
                    "width": 64.48,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 518.86,
                    "y": 216.95000000000005,
                    "str": "$ 620.67",
                    "dir": "ltr",
                    "width": 31.13600000000005,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 156.95000000000005,
                    "str": "Nombre del patrón",
                    "dir": "ltr",
                    "width": 66.24800000000002,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 147,
                    "y": 156.95000000000005,
                    "str": "TCL MOKA MANUFACTURING",
                    "dir": "ltr",
                    "width": 113.33599999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 176.95000000000005,
                    "str": "Registro Patronal",
                    "dir": "ltr",
                    "width": 61.80000000000001,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 147,
                    "y": 176.95000000000005,
                    "str": "A086348210",
                    "dir": "ltr",
                    "width": 45.368,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 322.26,
                    "y": 252.03999999999996,
                    "str": "Fecha de movimiento",
                    "dir": "ltr",
                    "width": 76.47199999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 129.6,
                    "y": 252.03999999999996,
                    "str": "Tipo de movimiento",
                    "dir": "ltr",
                    "width": 69.79999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 479.32,
                    "y": 252.03999999999996,
                    "str": "Salario Base",
                    "dir": "ltr",
                    "width": 45.352,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 340.48,
                    "y": 272.03999999999996,
                    "str": "17/09/2021",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 154.5,
                    "y": 272.03999999999996,
                    "str": "BAJA",
                    "dir": "ltr",
                    "width": 20.008000000000003,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 486.43,
                    "y": 272.03999999999996,
                    "str": "$ 620.67",
                    "dir": "ltr",
                    "width": 31.135999999999992,
                    "height": 8,
                    "fontName": "Helvetica"
                },
            ]
        },
        {
            "pageInfo": {
                "num": 3,
                "scale": 1,
                "rotation": 0,
                "offsetX": 0,
                "offsetY": 0,
                "width": 612,
                "height": 792
            },
            "links": [],
            "content": [
                {
                    "x": 225.13,
                    "y": 108.78999999999996,
                    "str": "Instituto Mexicano del Seguro Social",
                    "dir": "ltr",
                    "width": 161.7399999999999,
                    "height": 10,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 322.26,
                    "y": 141.03999999999996,
                    "str": "Fecha de movimiento",
                    "dir": "ltr",
                    "width": 76.47199999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 129.6,
                    "y": 141.03999999999996,
                    "str": "Tipo de movimiento",
                    "dir": "ltr",
                    "width": 69.79999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 479.32,
                    "y": 141.03999999999996,
                    "str": "Salario Base",
                    "dir": "ltr",
                    "width": 45.352,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 340.48,
                    "y": 161.03999999999996,
                    "str": "01/07/2019",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 109.82,
                    "y": 161.03999999999996,
                    "str": "MODIFICACION DE SALARIO",
                    "dir": "ltr",
                    "width": 109.35199999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 486.43,
                    "y": 161.03999999999996,
                    "str": "$ 325.18",
                    "dir": "ltr",
                    "width": 31.135999999999992,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 340.48,
                    "y": 181.03999999999996,
                    "str": "24/06/2019",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 140.5,
                    "y": 181.03999999999996,
                    "str": "REINGRESO",
                    "dir": "ltr",
                    "width": 48.007999999999996,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 486.43,
                    "y": 181.03999999999996,
                    "str": "$ 324.74",
                    "dir": "ltr",
                    "width": 31.135999999999992,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 42,
                    "y": 201.03999999999996,
                    "str": "/* Valor del último salario base de cotización diario en pesos.",
                    "dir": "ltr",
                    "width": 215.64800000000008,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 312,
                    "y": 301.95,
                    "str": "26/06/2019",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 147,
                    "y": 281.95,
                    "str": "BAJA CALIFORNIA",
                    "dir": "ltr",
                    "width": 70.23999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 388,
                    "y": 301.95,
                    "str": "Salario Base de Cotización",
                    "dir": "ltr",
                    "width": 103.59999999999998,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 301.95,
                    "str": "Fecha de alta",
                    "dir": "ltr",
                    "width": 48.472000000000016,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 232,
                    "y": 301.95,
                    "str": "Fecha de baja",
                    "dir": "ltr",
                    "width": 50.695999999999984,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 147,
                    "y": 301.95,
                    "str": "23/05/2018",
                    "dir": "ltr",
                    "width": 40.032000000000004,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 281.95,
                    "str": "Entidad federativa",
                    "dir": "ltr",
                    "width": 64.48,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 518.86,
                    "y": 301.95,
                    "str": "$ 324.74",
                    "dir": "ltr",
                    "width": 31.13600000000005,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 241.95000000000005,
                    "str": "Nombre del patrón",
                    "dir": "ltr",
                    "width": 66.24800000000002,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 147,
                    "y": 241.95000000000005,
                    "str": "NOMINA INTEGRAL DE SOLUCIONES PRODUCTIVAS",
                    "dir": "ltr",
                    "width": 202.25600000000006,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {
                    "x": 44,
                    "y": 261.95000000000005,
                    "str": "Registro Patronal",
                    "dir": "ltr",
                    "width": 61.80000000000001,
                    "height": 8,
                    "fontName": "Helvetica"
                },
                {},
                {
                    "x": 147,
                    "y": 261.95000000000005,
                    "str": "Z312983510",
                    "dir": "ltr",
                    "width": 44.92,
                    "height": 8,
                    "fontName": "Helvetica"
                }
            ]
        }
    ],
    "filename": "./Employees/123.pdf"
}
</script>

La ventaja de ésta técnica es que después de ordenar los elementos, en un solo ciclo obtienes la información como la requieres.

1
  • Wow! es justo lo que necesitaba, realice algunos ajustes y funciono! ahora el codigo funciona tal cual lo necesitaba, eres un master! tome buen hombre su reputacion ganada el 19 jul. 2022 a las 3:25
0

Te comento Abdiel no es mi expertis javaScript pero talvez esto pueda ayudar.

Primero: entendamos que el Json para poder manejarlo debemos verlo como tipo objeto, así tendríamos un control total de como deseamos ya sea, estructurar para mostrar la información y manejar las data para insertarla en alguna BD.

Intenta lo siguiente:

Utiliza el Json.parse(), cabe destacar esto es teniendo en cuenta que extraes la información del documento en .PDF ya como un json String y llevar esa variable a la función en JavaScript.

function parseJSON(data) {
    return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); 
}

// prueba de json String a la función parseJson()
obj = parseJSON('{"nombre":"Carlos Villarroel", "Salario":"B/618.79", "planilla":[{"planilla_obj":"OTP-SC002","min_salario":"B/1000.00","max_salario":"B/2500.00"}],"current_page":"1"}');

//Ejemplo visualizando objeto de primer nivel de json
alert(obj.nombre);


//Ejemplo visualizando objeto de segundo nivel del json
alert(obj.planilla[0].planilla_obj);

Te recomiendo anidar la misma en una función para obtener de retorno el resultado de la forma como deseas estructurarla.

Espero sea de ayuda mi amigo y el día que empieces con un backend en c# que es mi área de expertis a la orden!

2
  • El detalle de este método es el uso de las llaves, todas las llaves son llamadas str, no están definidas como nombre: y su valor, apellido: y su valor, etc, asi lo exporta la librería que utilizo para ello: Pdf.js-extract, lo único que cambia entre ellas es su valor, como podría entonces identificarlas cada una de ellas así? Además sumando que por cada nivel tendríamos varios datos con el mismo nombre, ejemplo: el movimiento de modificación de salario que se encuentra repetido y consecutivo el 18 jul. 2022 a las 19:28
  • Abdiel, hare el proceso que tienes definido, lo tengo visualizado en el lenguaje que tengo de expertis, más sin embargo, hare lo posible para apoyarte en esa resolución. Algo muy cierto que ya mencionaste arriba, es hacer un loop en los objetos de tipo Array. Intentare realizar lo que tienes allí por mi parte para brindarte una mejor resolución del Issue. el 18 jul. 2022 a las 20:02

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.