How to: Export a Workbook to PDF
- 9 minutes to read
Important
The Workbook class is defined in the DevExpress.Docs.v24.1.dll assembly. Add this assembly to your project to use the Workbook API. You need a license for the DevExpress Office File API Subscription or DevExpress Universal Subscription to use this assembly in production code.
Export a Workbook
Use the Workbook.ExportToPdf method overloads to export a workbook to PDF. The following code sample saves a document to a stream in PDF format:
using DevExpress.Spreadsheet;
using System.IO;
// ...
// Create a new Workbook object.
using (Workbook workbook = new Workbook())
{
// ...
// Edit document content.
// ...
// Export the workbook to PDF.
using (FileStream pdfFileStream = new FileStream("Documents\\Document_PDF.pdf",
FileMode.Create))
{
workbook.ExportToPdf(pdfFileStream);
}
}
Export a Workbook to Accessible PDF
You can save a workbook as a tagged (accessible) PDF document. Accessible PDF formats allow users with disabilities to use screen readers and other assistive technologies to read information from PDF documents.
You can generate PDF files that conform to the following standards:
- PDF/UA
- PDF/A-1a
- PDF/A-2a
- PDF/A-3a
Generate PDF/UA Documents
The PDF/UA (Universal Accessibility) standard contains requirements for PDF documents to ensure accessibility and support for assistive technology. Requirements for PDF/UA compliance are consistent with the Web Content Accessibility Guidelines (WCAG) 2.0.
Below are some of the constraints the standard defines for PDF documents:
All meaningful content should be tagged and included in the structure tree of document tags. Objects that are not relevant for understanding document content are marked as artifacts (for example, background and decorative images, repeating information in headers and footers, page numbers).
The structure tree generated by document tags must reflect the document’s logical reading order.
Information should not be conveyed by visual means alone (for example, contrast, color, or position on the page).
All pictorial elements (image objects and other non-text objects such as vector objects or object groups) should have alternative text.
All fonts should be embedded.
To generate a document that conforms to the PDF/UA standard, create a PdfExportOptions class instance and set the PdfExportOptions.PdfUACompatibility property to PdfUA1. Pass the class instance to the Workbook.ExportToPdf method to save a workbook as a PDF/UA document.
using DevExpress.Spreadsheet;
using DevExpress.XtraPrinting;
// ...
// Create a new Workbook object.
using (Workbook workbook = new Workbook())
{
// ...
// Specify PDF export options.
PdfExportOptions options = new PdfExportOptions();
// Specify document compatibility with the PDF/UA specification.
options.PdfUACompatibility = PdfUACompatibility.PdfUA1;
// Export the workbook to PDF.
workbook.ExportToPdf(@"Documents\Output_Workbook.pdf", options);
}
Generate Accessible PDF/A Documents
PDF/A is an archival PDF format used for long-term preservation of electronic documents. The PDF/A standard includes the following restrictions:
- All PDF/A versions implicitly prohibit encryption.
- All fonts that are used in PDF/A documents should be embedded.
- The PDF/A-1 and PDF/A-2 standards do not support attachments.
- The PDF/A-1 standard does not support transparency (the alpha channel in images is ignored).
To export a workbook to a PDF document that supports the PDF/A Conformance Level A (Accessible), create a PdfExportOptions class instance and set the PdfExportOptions.PdfACompatibility property to one of the following values: PdfA1a, PdfA2a, or PdfA3a. Pass the class instance to the Workbook.ExportToPdf method to generate a PDF file.
The following code sample saves a workbook as a PDF file that conforms to the PDF/A-3a standard:
using DevExpress.Spreadsheet;
using DevExpress.XtraPrinting;
// ...
// Create a new Workbook object.
using (Workbook workbook = new Workbook())
{
// ...
// Specify PDF export options.
PdfExportOptions options = new PdfExportOptions();
// Specify document compatibility with the PDF/A-3a specification.
options.PdfACompatibility = PdfACompatibility.PdfA3a;
// Export the workbook to PDF.
workbook.ExportToPdf(@"Documents\Output_Workbook.pdf", options);
}
Export Individual Worksheets
The Workbook.ExportToPdf method overload allows you to save individual worksheets in PDF format.
The code sample below defines PDF export options and generates a PDF file from the specified worksheets.
using DevExpress.Spreadsheet;
using DevExpress.XtraPrinting;
using System.IO;
// ...
// Create a new Workbook object.
using (Workbook workbook = new Workbook())
{
// ...
// Specify export options.
PdfExportOptions options = new PdfExportOptions();
options.DocumentOptions.Author = "John Smith";
options.ImageQuality = PdfJpegImageQuality.Medium;
// Export specific worksheets in PDF format.
using (FileStream pdfFileStream = new FileStream("Document_PDF.pdf", FileMode.Create))
{
workbook.ExportToPdf(pdfFileStream, options, "Sheet1", "Sheet2");
}
}
Tip
Handle the Workbook.BeforePrintSheet event to cancel export for specific worksheets.
Export Cell Ranges
You can define a print area that designates one or more cell ranges as the only region to export to PDF. A worksheet can have multiple print areas. Each print area is exported on a separate page.
Use the Worksheet.SetPrintRange to define the print area. When you call the Workbook.ExportToPdf method and pass the required worksheet name as a parameter, only the specified print area will be exported.
The following code sample exports to PDF:
using DevExpress.Spreadsheet;
using DevExpress.XtraPrinting;
// ...
// Create a new Workbook object.
using (Workbook workbook = new Workbook())
{
workbook.LoadDocument(@"Data\InvestmentPortfolio.xltx");
Worksheet worksheet = workbook.Worksheets[0];
// Define a print area on a worksheet.
CellRange printArea = worksheet["C1:F39"];
worksheet.SetPrintRange(printArea);
// Specify print options
PdfExportOptions options = new PdfExportOptions();
options.DocumentOptions.Author = "John Smith";
options.ImageQuality = PdfJpegImageQuality.Medium;
workbook.ExportToPdf("Test.pdf", options, worksheet.Name);
}
Asynchronous Export
Use the Workbook.ExportToPdfAsync methods to export a workbook or individual sheets to PDF asynchronously. The method overloads allow you to define export options, implement progress notifications, or cancel the operation if needed.
Important
Take into account the following when you call this method:
The events fired by this method call may occur in a different thread than the target operation.
The operation is not thread safe (the document should not be accessed simultaneously by different threads). Wait until the operation is completed before you continue to work with the document (for example, use the
await
operator).
The following code sample asynchronously converts an XLSX file to PDF and cancels the operation if it takes longer than 10 seconds:
using DevExpress.Spreadsheet;
using System;
using System.Threading;
using System.Threading.Tasks;
// ...
private async void ConvertXlsx2PdfWithCancellation()
{
// Specify the cancellation token.
using (CancellationTokenSource source = new CancellationTokenSource(10000))
{
// Create a new Workbook object.
using (Workbook workbook = new Workbook())
{
try
{
// Asynchronously load the XLSX file.
await workbook.LoadDocumentAsync("Document.xlsx", source.Token);
// Asynchronously convert the XLSX file to PDF.
await workbook.ExportToPdfAsync("Result.pdf", source.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancelled by timeout.");
}
}
}
}
Calculate Formulas Before Export
The default calculation mode for a Workbook is Manual. This mode implies that the Spreadsheet component does not recalculate formulas before it generates a PDF document. Call the Workbook.Calculate or Workbook.CalculateFull method to calculate all formulas in the workbook before you export it to PDF.
using DevExpress.Spreadsheet;
//...
// Create a new Workbook object.
using (Workbook workbook = new Workbook())
{
// Load a document.
// ...
// Modify the document.
// ...
// Calculate formulas in the document.
workbook.Calculate();
// Export the document to PDF.
workbook.ExportToPdf("Document_PDF.pdf");
}
Export Workbooks with 3-D Charts to PDF in .NET Core Apps on Linux
If you run your .NET Core app on a Linux server distribution or Docker Linux Container, use the following terminal command to install additional libraries to export spreadsheets with 3-D charts to PDF:
sudo apt install libosmesa6 libglu1-mesa
If you use Linux with a window system (for example, X Window System), install one of the following libraries:
EGL (Embedded-System Graphics Library)
sudo apt install libegl1
GLX (OpenGL extension to the X Window System)
sudo apt install libx11-dev