Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Cet article fournit des instructions détaillées étape par étape pour convertir des documents PDF dans Microsoft Azure en utilisant Aspose.PDF for .NET et Azure App service.
code --install-extension ms-dotnettools.csharp
code --install-extension ms-azuretools.vscode-azureappservice
brew install azure-cli
.curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
.code .
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>
// .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"
}
}
]
}
mkdir Controllers
touch Controllers/PdfController.cs
Dans Visual Studio, ouvrez la console du gestionnaire de packages et exécutez :
Install-Package Aspose.PDF
Install-Package Microsoft.ApplicationInsights.AspNetCore
Install-Package Microsoft.Extensions.Logging.AzureAppServices
Dans Visual Studio Code, exécutez :
dotnet restore
Dans Visual Studio :
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.PDF.lic");
Dans Visual Studio :
// 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();
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ApplicationInsights": {
"ConnectionString": "Your-Connection-String"
}
}
Remplacez Your-Connection-StringG
par votre véritable chaîne de connexion depuis le portail Azure.
Dans Visual Studio :
Dans Visual Studio Code :
dotnet run
curl -X POST "https://localhost:5001/api/pdf/convert?outputFormat=docx" \
-F "file=@sample.pdf" \
-o converted.docx
Dans Visual Studio :
Dans 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"
App Settings:
- WEBSITE_RUN_FROM_PACKAGE=1
- ASPNETCORE_ENVIRONMENT=Production
Utilisez Postman ou curl pour tester :
curl -X POST "https://your-app.azurewebsites.net/api/pdf/convert?outputFormat=docx" \
-F "file=@sample.pdf" \
-o converted.docx
La liste des formats pris en charge peut être trouvée ici.
<configuration>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="104857600" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder
.WithOrigins("https://your-frontend-domain.com")
.AllowAnyMethod()
.AllowAnyHeader());
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
// Configure JWT options
});
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.