Com convertir JSON a PDF amb C#

Com convertir JSON a PDF amb C#

Convertir JSON a PDF és ideal per generar informes compartibles o documents de dades estructurades. Utilitzant Aspose.Cells per a .NET, es pot carregar el contingut jSON en un disseny d’estil de fletxa i exportar-lo com un PDF amb control complet sobre la formatació de les dades.

Per què convertir JSON en PDF?

  • Informació professional:- Generar documents politzats des de continguts JSON que es poden compartir o imprimir.

  • Web-to-PDF flux de treball:- Convertir JSON estructurat de les APIs web en taules PDF llegibles.

  • Elaboració flexible:- Utilitzeu les opcions de disseny per controlar la formatació, com tractar les arrels com a taules o ignorar els valors zero.

Guia de pas a pas per convertir JSON en PDF

Pas 1: Instal·lar Aspose.Cells a través de NuGet

Afegeix Aspose.Cells al teu projecte:

dotnet add package Aspose.Cells

Pas 2: Configuració de la llicència

Activar el producte:

Metered matered = new Metered();
matered.SetMeteredKey("PublicKey", "PrivateKey");

Pas 3: Iniciar el llibre de treball

Crear un nou llibre de treball per mantenir el contingut JSON:

Workbook workbook = new Workbook();

Etapa 4: Obra d’accés

Utilitza la taula de treball estàndard per importar:

Worksheet worksheet = workbook.Worksheets[0];

Pas 5: Carregar la entrada JSON

Llegeix la barra JSON del fitxer:

string jsonInput = File.ReadAllText("SampleJsonData.json");

Pas 6: Set JsonLayoutOptions

Defineix com s’ha de estructurar el JSON en la fulla:

JsonLayoutOptions layoutOptions = new JsonLayoutOptions();
layoutOptions.ArrayAsTable = true;

Pas 7: Importar JSON a la taula de treball

Població de la taula de treball amb dades JSON:

JsonUtility.ImportData(jsonInput, worksheet.Cells, 0, 0, layoutOptions);

Pas 8: Salvar com a PDF

Exportar el llibre de treball a PDF:

workbook.Save("output.pdf", SaveFormat.Pdf);

s

Problemes comuns i fixos

1 El format de taula no s’ha rendit

  • Solution: Set layoutOptions.ArrayAsTable = true to format array data as table rows.

2.Layout incorrecte en PDF

  • Solution: Tweak JsonLayoutOptions to include title styling, ignore nulls, or adjust numeric/date formats.

Errors d’accés al fitxer

  • Solució: confirma que la ruta d’entrada és vàlida i que l’aplicació té permissions escrites per al fitxer de sortida.
 Català