Mengonversi Dokumen dengan Layanan Aplikasi Microsoft Azure

Artikel ini memberikan instruksi langkah demi langkah yang terperinci untuk mengonversi dokumen PDF di Microsoft Azure menggunakan Aspose.PDF for .NET dan Layanan Aplikasi Azure.

Prasyarat

  • Visual Studio 2022 Community Edition dengan pengembangan Azure yang terinstal atau Visual Studio Code.
  • Akun Azure: Anda memerlukan langganan Azure, buat akun gratis sebelum memulai.
  • .NET 6 SDK.
  • Aspose.PDF for .NET.

Buat Sumber Daya Azure

Buat Layanan Aplikasi

  1. Buka Portal Azure (https://portal.azure.com).
  2. Buat Grup Sumber Daya baru.
  3. Buat Layanan Aplikasi baru:
    • Pilih runtime .NET 6 (LTS).
    • Pilih tier harga yang sesuai.
  4. Buat sumber daya Application Insights untuk logging.

Buat Proyek

Buat Proyek Visual Studio

  1. Buka Visual Studio 2022.
  2. Klik “Buat proyek baru”.
  3. Pilih “ASP.NET Core Web API”.
  4. Beri nama proyek Anda “PdfConversionService”.
  5. Pilih “.NET 6.0” atau lebih baru.
  6. Klik “Buat”.

Buat Proyek Visual Studio Code

Instal Prasyarat

  1. Ekstensi Visual Code:
code --install-extension ms-dotnettools.csharp
code --install-extension ms-azuretools.vscode-azureappservice
  1. Instal Azure CLI:
  • Windows: Unduh dari situs web Microsoft.
  • macOS: brew install azure-cli.
  • Linux: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash.

Konfigurasi Proyek

  1. Buka proyek di Visual Studio Code:
code .
  1. Tambahkan paket NuGet dengan membuat/memperbarui 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>
  1. Tambahkan konfigurasi:
// .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"
            }
        }
    ]
}
  1. Buat struktur proyek:
mkdir Controllers
touch Controllers/PdfController.cs

Instal Paket NuGet yang Diperlukan

Di Visual Studio buka Package Manager Console dan jalankan:

Install-Package Aspose.PDF
Install-Package Microsoft.ApplicationInsights.AspNetCore
Install-Package Microsoft.Extensions.Logging.AzureAppServices

Di Visual Studio Code jalankan:

dotnet restore

Konfigurasi Lisensi Aspose

Di Visual Studio:

  1. Salin file lisensi Aspose.PDF Anda ke proyek.
  2. Klik kanan pada file lisensi, dan pilih “Properties”.
  3. Atur “Copy to Output Directory” ke “Copy always”.
  4. Tambahkan kode inisialisasi lisensi di Program.cs:
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.PDF.lic");

Buat kode

Di Visual Studio:

  1. Klik kanan pada folder Controllers.
  2. Tambah → Item Baru → API Controller - Kosong.
  3. Beri nama file Anda “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();

Konfigurasi pengaturan aplikasi

  1. Buka appsettings.json.
  2. Tambahkan konfigurasi:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    "ConnectionString": "Your-Connection-String"
  }
}

Ganti Your-Connection-StringG dengan string koneksi Anda yang sebenarnya dari Portal Azure.

Uji Secara Lokal

Di Visual Studio:

  1. Tekan F5 untuk menjalankan aplikasi.
  2. UI Swagger akan terbuka.
  3. Uji endpoint /api/pdf/convert:
    • Klik “Coba”.
    • Unggah file PDF.
    • Pilih format output.
    • Eksekusi dan verifikasi konversi.

Di Visual Studio Code:

dotnet run

curl -X POST "https://localhost:5001/api/pdf/convert?outputFormat=docx" \
     -F "file=@sample.pdf" \
     -o converted.docx

Deploy ke Azure

Di Visual Studio:

  1. Klik kanan pada proyek.
  2. Pilih “Publish”.
  3. Pilih “Azure” sebagai target.
  4. Pilih “Azure App Service (Windows)”.
  5. Pilih langganan dan Layanan Aplikasi Anda.
  6. Klik “Publish”.

Di 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"

Konfigurasi Layanan Aplikasi Azure

  1. Buka Portal Azure.
  2. Buka Layanan Aplikasi Anda.
  3. Konfigurasi pengaturan:
    App Settings:
    - WEBSITE_RUN_FROM_PACKAGE=1
    - ASPNETCORE_ENVIRONMENT=Production
    

Uji Layanan yang Dideploy

Gunakan Postman atau curl untuk menguji:

curl -X POST "https://your-app.azurewebsites.net/api/pdf/convert?outputFormat=docx" \
     -F "file=@sample.pdf" \
     -o converted.docx

Format yang Didukung

Daftar format yang didukung dapat ditemukan di sini.

Pemecahan Masalah

Opsi Konfigurasi Penting

  1. Batas Ukuran File Tambahkan ke web.config:
<configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="104857600" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>
  1. CORS (jika diperlukan) Di Program.cs:
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigin",
        builder => builder
            .WithOrigins("https://your-frontend-domain.com")
            .AllowAnyMethod()
            .AllowAnyHeader());
});
  1. Autentikasi (jika diperlukan)
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => {
        // Configure JWT options
    });