Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
AWS에서 클라우드 네이티브 애플리케이션을 구축하고 강력한 PDF 생성, 조작 또는 변환 기능이 필요한 경우, Aspose.PDF for .NET를 AWS Lambda 함수에 통합하는 것은 강력하고 확장 가능한 솔루션을 제공합니다. 이 접근 방식은 AWS의 서버리스 환경 내에서 Aspose.PDF의 광범위한 기능을 활용할 수 있게 하며, S3와 같은 다른 서비스와 통합할 수 있는 가능성을 제공합니다.
이 문서는 AWS Lambda에서 Aspose.PDF for .NET를 설정하고 실행하는 방법을 안내하며, 기본 PDF 생성 및 클라우드에서의 글꼴 관리와 같은 일반적인 문제를 다룹니다.
Aspose.PDF를 사용하여 PDF 문서를 생성하고 Amazon S3에 저장하는 간단한 Lambda 함수를 생성하려면 다음 단계를 따르세요:
Aspose.PDF
. PDF 조작을 위한 핵심 라이브러리입니다.AWSSDK.S3
. S3 저장소와 상호 작용하기 위한 AWS SDK for .NET 라이브러리입니다.Function.cs
)의 내용을 다음 코드로 교체합니다. 이 예제는 텍스트가 포함된 기본 PDF 문서를 생성하고 S3 버킷에 저장합니다.using System;
using System.IO;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using Aspose.Pdf;
using Aspose.Pdf.Text;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace TestAsposePdfLambda
{
public class Function
{
private IAmazonS3 S3Client { get; set; }
private const string BucketName = "your-s3-bucket-name";
/// <summary>
/// Default constructor. Initializes the S3 client.
/// </summary>
public Function()
{
S3Client = new AmazonS3Client();
// Consider setting the License here if needed, e.g., in a static constructor
Aspose.Pdf.License lic = new Aspose.Pdf.License();
// Assumes license file is an embedded resource
lic.SetLicense("Aspose.PDF.lic");
}
/// <summary>
/// Lambda function handler: Creates a PDF document and saves it to S3.
/// </summary>
public async Task<string> FunctionHandler(string input, ILambdaContext context)
{
context.Logger.LogLine($"Function processing input: {input}");
// Create PDF document
Document pdfDocument = new Document();
// Add a page
Page page = pdfDocument.Pages.Add();
// Add text elements
page.Paragraphs.Add(new TextFragment($"Hello {input} from Aspose.PDF!"));
page.Paragraphs.Add(new TextFragment($"You are running on: {System.Environment.OSVersion.VersionString}"));
// Save the PDF to a MemoryStream
using (MemoryStream ms = new MemoryStream())
{
// Aspose.PDF saves directly to PDF format
pdfDocument.Save(ms);
// Reset stream position for reading
ms.Position = 0;
// Upload the stream to S3
string outputKey = $"AP_out_{DateTime.UtcNow:yyyyMMddHHmmss}.pdf";
context.Logger.LogLine($"Attempting to upload {outputKey} to bucket {BucketName}");
bool putResult = await PutS3Object(BucketName, outputKey, ms, context);
return putResult ? $"OK - PDF saved as s3://{BucketName}/{outputKey}" : "FAILED to upload PDF to S3";
}
}
/// <summary>
/// Helper method to upload a stream to an S3 bucket.
/// </summary>
private async Task<bool> PutS3Object(string bucket, string key, Stream content, ILambdaContext context)
{
try
{
PutObjectRequest request = new PutObjectRequest
{
BucketName = bucket,
Key = key,
InputStream = content,
// Set appropriate content type
ContentType = "application/pdf"
};
var response = await S3Client.PutObjectAsync(request);
context.Logger.LogLine($"S3 PutObject Response: {response.HttpStatusCode}");
return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
}
catch (AmazonS3Exception s3ex)
{
context.Logger.LogLine($"Error uploading to S3: {s3ex.Message} (AWS Request ID: {s3ex.RequestId}, Error Code: {s3ex.ErrorCode})");
return false;
}
catch (Exception ex)
{
context.Logger.LogLine($"General error during S3 upload: {ex.Message}");
return false;
}
}
}
}
"your-s3-bucket-name"
을 쓰기 권한이 있는 S3 버킷의 이름으로 교체합니다.AP_out_... .pdf
)을 S3 버킷에서 확인합니다.생성된 PDF를 확인할 때 텍스트가 예상하는 표준 글꼴(예: Arial 또는 Times New Roman)을 사용하지 않는 것을 발견할 수 있습니다. 대신 Aspose.PDF는 대체 글꼴을 사용할 수 있습니다. AWS Lambda 실행 환경은 최소한의 Linux 컨테이너입니다. 일반적으로 Windows 또는 데스크탑 Linux 배포판에서 발견되는 일반적인 TrueType 글꼴이 부족합니다. Aspose.PDF가 지정된 글꼴이나 기본 글꼴을 찾을 수 없을 때, 사용 가능한 대체 글꼴로 대체하여 텍스트가 여전히 렌더링되도록 합니다. 이는 문서의 시각적 충실도에 영향을 줄 수 있습니다.
PDF가 올바른 글꼴로 렌더링되도록 하려면 Lambda 환경 내에서 Aspose.PDF에 제공해야 합니다. S3 버킷에 글꼴을 저장하는 것은 클라우드 애플리케이션을 위한 유연하고 일반적인 접근 방식입니다:
Fonts
)를 생성하고 필요한 TrueType(.ttf
) 또는 OpenType(.otf
) 글꼴 파일을 업로드합니다. 시연을 위해 “Noto Sans"와 같은 무료로 제공되는 세트를 사용할 수 있습니다.FontRepository
에 등록합니다.이전 Lambda 함수 코드를 조정하는 방법은 다음과 같습니다:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using Aspose.Pdf;
using Aspose.Pdf.Text;
// Assembly attribute
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace TestAsposePdfLambda
{
public class Function
{
private IAmazonS3 S3Client { get; set; }
private const string BucketName = "your-s3-bucket-name"; // Replace with your bucket name
private const string FontsS3Folder = "Fonts/"; // Folder in your bucket containing .ttf/.otf files
private static bool _fontsLoaded = false; // Flag to load fonts only once per container instance
private static readonly object _fontLoadLock = new object(); // Lock for thread safety
/// <summary>
/// Static constructor: Ensures fonts are loaded when the class is first accessed
/// within a Lambda execution environment instance.
/// </summary>
static Function()
{
// Consider setting the License here if needed
Aspose.Pdf.License lic = new Aspose.Pdf.License();
lic.SetLicense("Aspose.PDF.lic");
}
/// <summary>
/// Default constructor. Initializes S3 client.
/// </summary>
public Function()
{
S3Client = new AmazonS3Client();
// Ensure fonts are loaded
EnsureFontsLoaded(S3Client, BucketName, FontsS3Folder);
}
/// <summary>
/// Lambda function handler: Creates a PDF with custom fonts loaded from S3.
/// </summary>
public async Task<string> FunctionHandler(string input, ILambdaContext context)
{
context.Logger.LogLine($"Function processing input: {input}");
// Ensure fonts loaded (important for warm starts)
EnsureFontsLoaded(S3Client, BucketName, FontsS3Folder, context);
// Create PDF document
Document pdfDocument = new Document();
// Add a page
Page page = pdfDocument.Pages.Add();
// Create TextFragment and specify the font
TextFragment titleFragment = new TextFragment($"Hello {input} from Aspose.PDF!");
// Attempt to find the font loaded from S3. Use the actual font name
titleFragment.TextState.Font = FontRepository.FindFont("Noto Sans");
// If the font wasn't found/loaded, FindFont might return a default/fallback font
titleFragment.TextState.FontSize = 14;
page.Paragraphs.Add(titleFragment);
TextFragment infoFragment = new TextFragment($"Running on: {System.Environment.OSVersion.VersionString}");
// Example using a specific style
infoFragment.TextState.Font = FontRepository.FindFont("Noto Sans Regular");
infoFragment.TextState.FontSize = 10;
page.Paragraphs.Add(infoFragment);
// Save PDF to stream
using (MemoryStream ms = new MemoryStream())
{
pdfDocument.Save(ms);
ms.Position = 0;
// Upload to S3
string outputKey = $"AP_Font_out_{DateTime.UtcNow:yyyyMMddHHmmss}.pdf";
context.Logger.LogLine($"Attempting to upload {outputKey} to bucket {BucketName}");
bool putResult = await PutS3Object(BucketName, outputKey, ms, context);
return putResult ? $"OK - PDF saved as s3://{BucketName}/{outputKey}" : "FAILED to upload PDF to S3";
}
}
/// <summary>
/// Loads fonts from S3 into Aspose.PDF's FontRepository if not already loaded.
/// </summary>
private void EnsureFontsLoaded(IAmazonS3 s3Client, string bucketName, string fontsFolderKey, ILambdaContext context = null)
{
// Prevent multiple threads/invocations trying to load simultaneously
lock (_fontLoadLock)
{
if (_fontsLoaded)
{
return;
}
context?.Logger.LogLine("Attempting to load fonts from S3...");
try
{
// Get font sources from S3
var fontSources = Task.Run(async () => await GetS3FontSources(s3Client, bucketName, fontsFolderKey, context)).Result;
if (fontSources.Any())
{
// Clear existing default sources (optional, ensures only S3 fonts are primary)
// FontRepository.Sources.Clear();
// Add the sources loaded from S3
FontRepository.Sources.AddRange(fontSources);
context?.Logger.LogLine($"Successfully loaded {fontSources.Count()} font sources from S3.");
_fontsLoaded = true;
}
else
{
context?.Logger.LogLine("No font sources found in S3 folder.");
// Set _fontsLoaded to true anyway to avoid retrying every invocation if folder is empty/missing
_fontsLoaded = true;
}
}
catch (AggregateException aggEx) when (aggEx.InnerException is AmazonS3Exception s3Ex)
{
context?.Logger.LogLine($"S3 Error loading fonts: {s3Ex.Message} (Request ID: {s3Ex.RequestId}, Error Code: {s3Ex.ErrorCode}) - Check bucket/folder name and permissions.");
// Avoid retrying constantly on permission errors
_fontsLoaded = true;
}
catch (Exception ex)
{
context?.Logger.LogLine($"Error loading fonts from S3: {ex.ToString()}");
// Decide if you want to retry or not. Setting _fontsLoaded = true prevents retries.
_fontsLoaded = true;
}
}
}
/// <summary>
/// Lists font files in an S3 folder and creates MemoryFontSource for each.
/// </summary>
private static async Task<List<MemoryFontSource>> GetS3FontSources(IAmazonS3 client, string bucketName, string fontsFolderKey, ILambdaContext context)
{
List<MemoryFontSource> fontSources = new List<MemoryFontSource>();
ListObjectsV2Request request = new ListObjectsV2Request()
{
BucketName = bucketName,
// e.g., "Fonts/"
Prefix = fontsFolderKey,
};
context?.Logger.LogLine($"Listing objects in {bucketName}/{fontsFolderKey}");
ListObjectsV2Response response;
do
{
// Requires s3:ListBucket permission on the bucket
response = await client.ListObjectsV2Async(request);
foreach (S3Object entry in response.S3Objects)
{
// Skip the folder itself and non-font files (simple check)
if (entry.Key.EndsWith("/") || !(entry.Key.EndsWith(".ttf", StringComparison.OrdinalIgnoreCase) || entry.Key.EndsWith(".otf", StringComparison.OrdinalIgnoreCase)))
{
continue;
}
context?.Logger.LogLine($"Found font file: {entry.Key}");
try
{
// Requires s3:GetObject permission on the font files
GetObjectRequest fontRequest = new GetObjectRequest
{
BucketName = bucketName,
Key = entry.Key
};
using (GetObjectResponse fontResponse = await client.GetObjectAsync(fontRequest))
{
using (MemoryStream ms = new MemoryStream())
{
await fontResponse.ResponseStream.CopyToAsync(ms);
// IMPORTANT: Aspose.PDF needs the raw byte array for MemoryFontSource.
// It manages the stream internally after this.
fontSources.Add(new MemoryFontSource(ms.ToArray()));
context?.Logger.LogLine($" -- Added MemoryFontSource for {entry.Key}");
}
}
}
catch (Exception ex)
{
context?.Logger.LogLine($" -- Failed to load font {entry.Key}: {ex.Message}");
// Decide how to handle failures - continue or stop?
}
}
request.ContinuationToken = response.NextContinuationToken;
} while (response.IsTruncated);
return fontSources;
}
/// <summary>
/// Helper method to upload a stream to an S3 bucket.
/// </summary>
private async Task<bool> PutS3Object(string bucket, string key, Stream content, ILambdaContext context)
{
try
{
PutObjectRequest request = new PutObjectRequest
{
BucketName = bucket,
Key = key,
InputStream = content,
// Set appropriate content type
ContentType = "application/pdf"
};
var response = await S3Client.PutObjectAsync(request);
context.Logger.LogLine($"S3 PutObject Response: {response.HttpStatusCode}");
return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
}
catch (AmazonS3Exception s3ex)
{
context.Logger.LogLine($"Error uploading to S3: {s3ex.Message} (AWS Request ID: {s3ex.RequestId}, Error Code: {s3ex.ErrorCode})");
return false;
}
catch (Exception ex)
{
context.Logger.LogLine($"General error during S3 upload: {ex.Message}");
return false;
}
}
}
}
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.