Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
تقدم هذه المقالة تعليمات مفصلة خطوة بخطوة لتحويل مستندات PDF في Microsoft Azure باستخدام Aspose.PDF for .NET ووظيفة Azure.
code --install-extension ms-dotnettools.csharp
code --install-extension ms-azuretools.vscode-azurefunctions
code --install-extension ms-vscode.azure-account
npm install -g azure-functions-core-tools@4 --unsafe-perm true
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>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.1" />
<PackageReference Include="Aspose.PDF" Version="24.10.0" />
<PackageReference Include="Azure.Storage.Blobs" Version="12.14.1" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="5.0.1" />
</ItemGroup>
</Project>
في Visual Studio، افتح وحدة تحكم إدارة الحزم وقم بتشغيل:
Install-Package Aspose.PDF
Install-Package Azure.Storage.Blobs
Install-Package Microsoft.Azure.WebJobs.Extensions.Storage
في Visual Studio Code، قم بتشغيل:
dotnet restore
احصل على مفاتيح الوصول لحساب التخزين تحت مفاتيح الوصول في بوابة Azure. ستستخدم هذه المفاتيح لمصادقة تطبيقك.
local.settings.json
:{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "YOUR_STORAGE_CONNECTION_STRING",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"ContainerName": "pdfdocs"
}
}
YOUR_STORAGE_CONNECTION_STRING
بسلسلة اتصال التخزين الفعلية الخاصة بك من بوابة Azure.في Visual Studio:
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.PDF.lic");
أنشئ ملفًا جديدًا PdfConverter.cs
:
using Azure.Storage.Blobs;
using System;
using System.IO;
using System.Threading.Tasks;
public class PdfConverter
{
private readonly BlobContainerClient _containerClient;
public PdfConverter(string connectionString, string containerName)
{
_containerClient = new BlobContainerClient(connectionString, containerName);
}
public async Task<string> ConvertToFormat(string sourceBlobName, string targetFormat)
{
// Download source PDF
var sourceBlob = _containerClient.GetBlobClient(sourceBlobName);
using var sourceStream = new MemoryStream();
await sourceBlob.DownloadToAsync(sourceStream);
sourceStream.Position = 0;
// Open PDF document
var document = new Aspose.Pdf.Document(sourceStream);
// Create output stream
using var outputStream = new MemoryStream();
string targetBlobName = Path.GetFileNameWithoutExtension(sourceBlobName);
// Convert based on format
switch (targetFormat.ToLower())
{
case "docx":
targetBlobName += ".docx";
document.Save(outputStream, Aspose.Pdf.SaveFormat.DocX);
break;
case "html":
targetBlobName += ".html";
document.Save(outputStream, Aspose.Pdf.SaveFormat.Html);
break;
case "xlsx":
targetBlobName += ".xlsx";
document.Save(outputStream, Aspose.Pdf.SaveFormat.Excel);
break;
case "pptx":
targetBlobName += ".pptx";
document.Save(outputStream, Aspose.Pdf.SaveFormat.Pptx);
break;
case "jpeg":
case "jpg":
targetBlobName += ".jpg";
foreach (var page in document.Pages)
{
var jpegDevice = new Aspose.Pdf.Devices.JpegDevice(new Aspose.Pdf.Devices.Resolution(300));
jpegDevice.Process(page, outputStream);
}
break;
default:
throw new ArgumentException($"Unsupported format: {targetFormat}");
}
// Upload converted file
outputStream.Position = 0;
var targetBlob = _containerClient.GetBlobClient(targetBlobName);
await targetBlob.UploadAsync(outputStream, true);
return targetBlob.Uri.ToString();
}
}
أنشئ ملفًا جديدًا ConvertPdfFunction.cs
:
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using System;
using System.IO;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
public static class ConvertPdfFunction
{
[FunctionName("ConvertPdf")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post"), Route = "convert"] HttpRequest req,
ILogger log)
{
try
{
// Read request body
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
string sourceBlob = data?.sourceBlob;
string targetFormat = data?.targetFormat;
if (string.IsNullOrEmpty(sourceBlob) || string.IsNullOrEmpty(targetFormat))
{
return new BadRequestObjectResult("Please provide sourceBlob and targetFormat");
}
// Get configuration
string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
string containerName = Environment.GetEnvironmentVariable("ContainerName");
// Convert PDF
var converter = new PdfConverter(connectionString, containerName);
string resultUrl = await converter.ConvertToFormat(sourceBlob, targetFormat);
return new OkObjectResult(new { url = resultUrl });
}
catch (Exception ex)
{
log.LogError(ex, "Error converting PDF");
return new StatusCodeResult(500);
}
}
}
// Startup.cs
[assembly: FunctionsStartup(typeof(PdfConverterAzure.Functions.Startup))]
namespace PdfConverterAzure.Functions
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
// Read configuration
var config = builder.GetContext().Configuration;
// Register services
builder.Services.AddLogging();
// Register Azure Storage
builder.Services.AddSingleton(x =>
new BlobServiceClient(config["AzureWebJobsStorage"]));
// Configure Aspose License
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.PDF.lic");
}
}
}
في Visual Studio:
curl -X POST http://localhost:7071/api/convert \
-H "Content-Type: application/json" \
-d '{"sourceBlob": "sample.pdf", "targetFormat": "docx"}'
في Visual Studio Code:
func start
az storage blob upload \
--account-name $AccountName \
--container-name pdfdocs \
--name sample.pdf \
--file /path/to/your/sample.pdf
curl -X POST http://localhost:7071/api/convert \
-H "Content-Type: application/json" \
-d '{"sourceBlob": "sample.pdf", "targetFormat": "docx"}'
في Visual Studio:
في Visual Studio Code:
استخدم Postman أو curl للاختبار:
curl -X POST "https://your-function.azurewebsites.net/api/convert" \
-H "x-functions-key: your-function-key" \
-H "Content-Type: application/json" \
-d '{"sourceBlob": "sample.pdf", "targetFormat": "docx"}'
يمكن العثور على قائمة التنسيقات المدعومة هنا.
[FunctionName("ConvertPdf")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "convert")] HttpRequest req,
ClaimsPrincipal principal,
ILogger log)
{
// Check authentication
if (!principal.Identity.IsAuthenticated)
{
return new UnauthorizedResult();
}
// ...
}
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.