Converting JSON data into professional, shareable PDF documents is a common requirement in many applications. With Aspose.Cells for .NET, you can easily load JSON content into a spreadsheet-style layout and export it as a PDF file with full control over the formatting.

Introduction

Transforming structured JSON data into well-formatted PDF reports or documents is a powerful feature that enhances the usability of your application’s output. This guide will walk you through the process of converting JSON to PDF using Aspose.Cells for .NET, providing detailed steps and code examples.

Why Convert JSON to PDF?

  1. Professional Reporting: Generate polished reports from JSON content that can be shared or printed easily.
  2. Web-to-PDF Workflow: Convert structured JSON data received from web APIs into readable PDF tables.
  3. Flexible Layouts: Control the formatting of your JSON data in the PDF, such as treating arrays as table rows and ignoring null values.

Step-by-Step Guide to Convert JSON to PDF

Step 1: Install Aspose.Cells via NuGet

Add the Aspose.Cells package to your project using the following command:

dotnet add package Aspose.Cells

Step 2: Configure License

Activate the product license by setting up a metered key. This is necessary for commercial use.

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

Step 3: Initialize Workbook

Create a new workbook to hold the JSON content:

Workbook workbook = new Workbook();

Step 4: Access Worksheet

Use the default worksheet for importing the JSON data:

Worksheet worksheet = workbook.Worksheets[0];

Step 5: Load JSON Input

Read the JSON string from a file or any other source:

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

Step 6: Set JsonLayoutOptions

Define how the JSON should be structured in the sheet. For example, treat arrays as tables and ignore null values.

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

Step 7: Import JSON into Worksheet

Populate the worksheet with JSON data:

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

Step 8: Save as PDF

Export the workbook to a PDF file:

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

Common Issues and Fixes

Table Format Not Rendered

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

Incorrect Layout in PDF

  • Solution: Adjust the JsonLayoutOptions settings to include title styling, ignore null values, or adjust numeric/date formats.

File Access Errors

  • Solution: Ensure that the input path is valid and the application has write permissions for the output file.

More in this category