Save a PDF to a remote server in MAUI

Saving a PDF document to a server in MAUI is achievable by programmatically exporting the document and then sending it to its remote destination.

Note that there’s a platform-specific setup required for FileSaver. It’s worth reading about the setup here if you’re not familiar with it.

Exporting a document to a remote server

The example below uses Microsoft’s HttpClient for demonstration purposes, though the general idea can be adapted to whichever solution you use:

HttpClient client = new HttpClient();

MultipartFormDataContent form = new MultipartFormDataContent();

var exportConfiguration = _document.CreateExportConfiguration();
// Update the configuration here.

// Read the file into a byte array.
byte[] fileBytes = await _document.ExportDocumentAsync(exportConfiguration);

// Create a `ByteArrayContent` from the byte array.
ByteArrayContent fileContent = new ByteArrayContent(fileBytes);

// Add the file content to the form.
form.Add(fileContent, "file", "download.pdf");
form.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
    FileName = "download.pdf"
};

// Send the `POST` request to the server.
HttpResponseMessage response = await client.PostAsync(remoteLocation, form);

// Check the response status.
if (response.IsSuccessStatusCode)
{
    // File uploaded successfully.
    Console.WriteLine("File uploaded successfully");
}
else
{
    // File upload failed.
    Console.WriteLine("File upload failed. Status: " + response.StatusCode);
}

For more control over exporting documents, use IExportConfiguration. If you pass null instead, the default configuration will be used:

var exportOptions = _document.CreateExportConfiguration();
{
    ExcludeAnnotations = true,
    ExportForPrinting = true,
    ExportIncrementally = false,
    Flatten = true,
};

var exportedDocumentContent = await _document.ExportDocumentAsync(exportConfiguration);
Information

If you experience issues saving a document into the PDF viewer from a remote URL, it may not be an issue with the PDF viewer itself. Ensure the location is accessible by checking the URL validity, network connectivity, and authentication.

To make it easier to try exporting a document to a remote server in Catalog, we added a Python script, exportServer.py, which can be used to start a local server. You can find it in the Resources/Server/ folder. To start the server:

  1. Install Python.

  2. Run the server using the python exportServer.py command.

Now you can save a document to this server using localhost:5000 as the server path.