How To: Convert a DOCX Document to PDF format
- 2 minutes to read
This example demonstrates how to utilize the RichEditDocumentServer.ExportToPdf method to export a document to PDF format.
Use the PdfExportOptions instance as the method parameter to specify PDF export options.
RichEditDocumentServer wordProcessor = new RichEditDocumentServer();
wordProcessor.LoadDocument("Documents\\MovieRentals.docx", DocumentFormat.OpenXml);
//Specify export options:
PdfExportOptions options = new PdfExportOptions();
options.DocumentOptions.Author = "Mark Jones";
options.Compressed = false;
options.ImageQuality = PdfJpegImageQuality.Highest;
//Export the document to the stream:
using (FileStream pdfFileStream = new FileStream("Document_PDF.pdf", FileMode.Create))
{
wordProcessor.ExportToPdf(pdfFileStream, options);
}
System.Diagnostics.Process.Start("Document_PDF.pdf");
Asynchronous Export
Important
The RichEditDocumentServerExtensions class is defined in the DevExpress.Docs.v20.2.dll assembly. Add this assembly to your project to use the RichEditDocumentServerExtensions members. You need a license for the DevExpress Office File API Subscription or DevExpress Universal Subscription to use this library in production code.
Use the RichEditDocumentServerExtensions.ExportToPdfAsync method to asynchronously export a document to the PDF format.
Important
Take into account the following when you call this method:
The events fired by this method’s call may occur in a different thread than the target operation.
The operation is not thread safe (documents should not be accessed simultaneously by different threads). Wait until the operation is completed before working with the document, i.e., use the
await
operator.
The code sample below uses the CancellationToken object to asynchronously export a document to PDF format:
private async void ConvertDocx2PdfWithCancellation()
{
//10 second limit
using (CancellationTokenSource source = new CancellationTokenSource(10000))
{
using (RichEditDocumentServer wordProcessor = new RichEditDocumentServer())
{
try
{
await wordProcessor.LoadDocumentAsync("Document.docx", source.Token);
await wordProcessor.ExportToPdfAsync("result.pdf", source.Token);
}
catch (OperationCanceledException)
{
// Your code to handle cancellation
}
}
}
}