Converting Documents with Microsoft Azure App service
Contents
[
Hide
]
This article provides detailed step-by-step instructions for converting PDF documents in Microsoft Azure using Aspose.PDF for .NET and Azure App service.
Prerequisites
- Visual Studio 2022 Community Edition with installed Azure development or Visual Studio Code.
- Azure Account: You need an Azure subscription, create a free account before beginning.
- .NET 6 SDK.
- Aspose.PDF for .NET.
Create Azure Resources
Create App Service
- Go to Azure Portal (https://portal.azure.com).
- Create a new Resource Group.
- Create a new App Service:
- Choose .NET 6 (LTS) runtime.
- Select appropriate pricing tier.
- Create an Application Insights resource for logging.
Create Project
Create Visual Studio Project
- Open Visual Studio 2022.
- Click “Create a new project”.
- Select “ASP.NET Core Web API”.
- Name your project “PdfConversionService”.
- Select “.NET 6.0” or later.
- Click “Create”.
Create Visual Studio Code Project
Install Prerequisites
- Visual Code extensions:
code --install-extension ms-dotnettools.csharp
code --install-extension ms-azuretools.vscode-azureappservice
- Install Azure CLI:
- Windows: Download from Microsoft’s website.
- macOS:
brew install azure-cli
. - Linux:
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
.
Configure Project
- Open project in Visual Studio Code:
code .
- Add NuGet packages by creating/updating
PdfConverterApp.csproj
:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aspose.PDF" Version="24.10.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="8.0.10" />
</ItemGroup>
</Project>
- Add configuration:
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/bin/Debug/net6.0/PdfConversionService.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
]
}
- Create project structure:
mkdir Controllers
touch Controllers/PdfController.cs
Install Required NuGet Packages
In Visual Studio open Package Manager Console and run:
Install-Package Aspose.PDF
Install-Package Microsoft.ApplicationInsights.AspNetCore
Install-Package Microsoft.Extensions.Logging.AzureAppServices
In Visual Studio Code run:
dotnet restore
Configure Aspose License
In Visual Studio:
- Copy your Aspose.PDF license file to the project.
- Right-click on the license file, and select “Properties”.
- Set “Copy to Output Directory” to “Copy always”.
- Add license initialization code in the Program.cs:
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.PDF.lic");
Create code
In Visual Studio:
- Right-click on Controllers folder.
- Add → New Item → API Controller - Empty.
- Name your file “PdfController.cs”.
// PdfController.cs
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
private readonly ILogger<PdfController> _logger;
public PdfController(ILogger<PdfController> logger)
{
_logger = logger;
}
[HttpPost("convert")]
public async Task<IActionResult> ConvertPdf(
IFormFile file,
[FromQuery] string outputFormat = "docx")
{
try
{
if (file == null || file.Length == 0)
return BadRequest("No file uploaded");
// Validate input file is PDF
if (!file.ContentType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase))
return BadRequest("File must be a PDF");
using var inputStream = file.OpenReadStream();
using var document = new Aspose.Pdf.Document(inputStream);
using var outputStream = new MemoryStream();
switch (outputFormat.ToLower())
{
case "docx":
document.Save(outputStream, Aspose.Pdf.SaveFormat.DocX);
return File(outputStream.ToArray(),
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"converted.docx");
case "html":
document.Save(outputStream, Aspose.Pdf.SaveFormat.Html);
return File(outputStream.ToArray(),
"text/html",
"converted.html");
case "jpg":
case "jpeg":
var jpegDevice = new Aspose.Pdf.Devices.JpegDevice();
jpegDevice.Process(document.Pages[1], outputStream);
return File(outputStream.ToArray(),
"image/jpeg",
"converted.jpg");
case "png":
var pngDevice = new Aspose.Pdf.Devices.PngDevice();
pngDevice.Process(document.Pages[1], outputStream);
return File(outputStream.ToArray(),
"image/png",
"converted.png");
default:
return BadRequest("Unsupported output format");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error converting PDF");
return StatusCode(500, "Internal server error");
}
}
}
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Add logging
builder.Services.AddApplicationInsightsTelemetry();
builder.Services.AddLogging(logging =>
{
logging.AddConsole();
logging.AddDebug();
logging.AddAzureWebAppDiagnostics();
});
var app = builder.Build();
// Initialize license
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.PDF.lic");
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Configure application settings
- Open appsettings.json.
- Add configuration:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ApplicationInsights": {
"ConnectionString": "Your-Connection-String"
}
}
Replace Your-Connection-StringG
with your actual connection string from Azure Portal.
Test Locally
In Visual Studio:
- Press F5 to run the application.
- Swagger UI will open.
- Test the /api/pdf/convert endpoint:
- Click “Try it out”.
- Upload a PDF file.
- Select output format.
- Execute and verify the conversion.
In Visual Studio Code:
dotnet run
curl -X POST "https://localhost:5001/api/pdf/convert?outputFormat=docx" \
-F "file=@sample.pdf" \
-o converted.docx
Deploy to Azure
In Visual Studio:
- Right-click on the project.
- Select “Publish”.
- Choose “Azure” as target.
- Select “Azure App Service (Windows)”.
- Select your subscription and App Service.
- Click “Publish”.
In Visual Studio Code:
dotnet publish -c Release
az webapp deployment source config-zip \
--resource-group $resourceGroup \
--name $appName \
--src bin/Release/net6.0/publish.zip
az webapp deploy \
--resource-group $resourceGroup \
--name $appName \
--src-path "Aspose.PDF.lic" \
--target-path "site/wwwroot/Aspose.PDF.lic"
Configure Azure App Service
- Go to Azure Portal.
- Open your App Service.
- Configure settings:
App Settings: - WEBSITE_RUN_FROM_PACKAGE=1 - ASPNETCORE_ENVIRONMENT=Production
Test the Deployed Service
Use Postman or curl to test:
curl -X POST "https://your-app.azurewebsites.net/api/pdf/convert?outputFormat=docx" \
-F "file=@sample.pdf" \
-o converted.docx
Supported Formats
The list of supported formats can be found here.
Trobleshooting
Important Configuration Options
- File Size Limits Add to web.config:
<configuration>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="104857600" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
- CORS (if needed) In Program.cs:
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder
.WithOrigins("https://your-frontend-domain.com")
.AllowAnyMethod()
.AllowAnyHeader());
});
- Authentication (if needed)
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
// Configure JWT options
});