How to Convert JSON to PDF using C#
How to Convert JSON to PDF using C#
Converting JSON to PDF is ideal for generating shareable reports or documents from structured data. Using Aspose.Cells for .NET, you can load JSON content into a spreadsheet-style layout and export it as a PDF with full control over the data formatting.
Why Convert JSON to PDF?
- Professional Reporting:
- Generate polished documents from JSON content that can be shared or printed.
- Web-to-PDF Workflow:
- Convert structured JSON from web APIs into readable PDF tables.
- Flexible Layouts:
- Use layout options to control formatting like treating arrays as tables or ignoring null values.
Step-by-Step Guide to Convert JSON to PDF
Step 1: Install Aspose.Cells via NuGet
Add Aspose.Cells to your project:
dotnet add package Aspose.Cells
Step 2: Configure License
Activate the product:
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:
Worksheet worksheet = workbook.Worksheets[0];
Step 5: Load JSON Input
Read the JSON string from file:
string jsonInput = File.ReadAllText("SampleJsonData.json");
Step 6: Set JsonLayoutOptions
Define how the JSON should be structured in the sheet:
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 PDF:
workbook.Save("output.pdf", SaveFormat.Pdf);
s
Common Issues and Fixes
1. Table Format Not Rendered
- Solution: Set
layoutOptions.ArrayAsTable = true
to format array data as table rows.
2. Incorrect Layout in PDF
- Solution: Tweak
JsonLayoutOptions
to include title styling, ignore nulls, or adjust numeric/date formats.
3. File Access Errors
- Solution: Confirm that the input path is valid and the application has write permissions for the output file.