Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Este artigo fornece instruções detalhadas passo a passo para converter documentos PDF no Microsoft Azure usando Aspose.PDF for .NET e 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
No Visual Studio, abra o Console do Gerenciador de Pacotes e execute:
Install-Package Aspose.PDF
Install-Package Microsoft.ApplicationInsights.AspNetCore
Install-Package Microsoft.Extensions.Logging.AzureAppServices
No Visual Studio Code, execute:
dotnet restore
No Visual Studio:
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.PDF.lic");
No 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"
}
}
Substitua Your-Connection-StringG
pela sua string de conexão real do Portal Azure.
No Visual Studio:
No Visual Studio Code:
dotnet run
curl -X POST "https://localhost:5001/api/pdf/convert?outputFormat=docx" \
-F "file=@sample.pdf" \
-o converted.docx
No Visual Studio:
No 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
Use Postman ou curl para testar:
curl -X POST "https://your-app.azurewebsites.net/api/pdf/convert?outputFormat=docx" \
-F "file=@sample.pdf" \
-o converted.docx
A lista de formatos suportados pode ser encontrada aqui.
<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.