Bende bir tane var. ASP.NET Kullanıcının Azure Blob depolama alanına farklı pdf'ler yüklemesini içeren C# ile yazılmış Azure web uygulaması. Kullanıcının daha sonra önceden yüklenmiş blobları içeren birleştirilmiş bir PDF'yi belirli bir sırayla indirmesini istiyorum. Bunu başarmanın en iyi yolu hakkında bir fikrin var mı?
1
İşte deneyebileceğiniz 2 geçici çözüm
- Azure İşlevlerinin Kullanımı.
- Pdf dosyalarınızı Azure Blob'dan yerel bilgisayarınıza indirin ve birleştirin.
Azure İşlevlerinin Kullanımı
- Bir azure işlev projesi oluşturun ve HTTP Tetikleyicisini kullanın.
- Kodlamaya başlamadan önce aşağıdaki paketleri yüklediğinizden emin olun.
- İşlev kodunu oluşturun.
- Portalda Azure işlevi oluşturun.
- Kodu yayınla.
Kod yazmaya başlamaya hazırız. İki dosya lazım :
- Sonuç sınıfı.cs-birleştirilmiş dosya(lar) ı liste olarak döndürür.
- İşlev1.dosya adlarını url'den alan, Depolama hesabından alan, bunları bir araya getiren ve bir indirme URL'si döndüren cs – CCode.
Sonuç sınıfı.cs
using System;
using System.Collections.Generic;
namespace FunctionApp1
{
public class Result
{
public Result(IList<string> newFiles)
{
this.files = newFiles;
}
public IList<string> files { get; private set; }
}
}
İşlev1.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
namespace FunctionApp1
{
public class Function1
{
static Function1()
{
// This is required to avoid the "No data is available for encoding 1252" exception when saving the PdfDocument
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
}
[FunctionName("Function1")]
public async Task<Result> SplitUploadAsync(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req,
//container where files will be stored and accessed for retrieval. in this case, it's called temp-pdf
[Blob("temp-pdf", Connection = "")] CloudBlobContainer outputContainer,
ILogger log)
{
//get query parameters
string uriq = req.RequestUri.ToString();
string keyw = uriq.Substring(uriq.IndexOf('=') + 1);
//get file name in query parameters
String fileNames = keyw.Split("mergepfd&filenam=")[1];
//split file name
string[] files = fileNames.Split(',');
//process merge
var newFiles = await this.MergeFileAsync(outputContainer, files);
return new Result(newFiles);
}
private async Task<IList<string>> MergeFileAsync(CloudBlobContainer container, string[] blobfiles)
{
//init instance
PdfDocument outputDocument = new PdfDocument();
//loop through files sent in query
foreach (string fileblob in blobfiles)
{
String intfile = $"" + fileblob;
// get file
CloudBlockBlob blob = container.GetBlockBlobReference(intfile);
using (var memoryStream = new MemoryStream())
{
await blob.DownloadToStreamAsync(memoryStream);
//get file content
string contents = blob.DownloadTextAsync().Result;
//open document
var inputDocument = PdfReader.Open(memoryStream, PdfDocumentOpenMode.Import);
//get pages
int count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
//append
outputDocument.AddPage(inputDocument.Pages[idx]);
}
}
}
var outputFiles = new List<string>();
var tempFile = String.Empty;
//call save function to store output in container
tempFile = await this.SaveToBlobStorageAsync(container, outputDocument);
outputFiles.Add(tempFile);
//return file(s) url
return outputFiles;
}
private async Task<string> SaveToBlobStorageAsync(CloudBlobContainer container, PdfDocument document)
{
//file name structure
var filename = $"merge-{DateTime.Now.ToString("yyyyMMddhhmmss")}-{Guid.NewGuid().ToString().Substring(0, 4)}.pdf";
// Creating an empty file pointer
var outputBlob = container.GetBlockBlobReference(filename);
using (var stream = new MemoryStream())
{
//save result of merge
document.Save(stream);
await outputBlob.UploadFromStreamAsync(stream);
}
//get sas token
var sasBlobToken = outputBlob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
{
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(5),
Permissions = SharedAccessBlobPermissions.Read
});
//return sas token
return outputBlob.Uri + sasBlobToken;
}
}
}
Pdf dosyalarınızı Azure Blob'dan yerel bilgisayarınıza indirin ve birleştirin
internal static void combineNormalPdfFiles()
{
String inputFilePath1 = @"C:\1.pdf";
String inputFilePath2 = @"C:\2.pdf";
String inputFilePath3 = @"C:\3.pdf";
String outputFilePath = @"C:\Output.pdf";
String[] inputFilePaths = new String[3] { inputFilePath1, inputFilePath2, inputFilePath3 };
// Combine three PDF files and output.
PDFDocument.CombineDocument(inputFilePaths, outputFilePath);
}
BAŞVURU:
SwethaKandikonda-MT, bu harika bir çözümdü ve web siteme başarıyla dahil ettiğim bir çözümdü. Cevap verdiğiniz için size çok içten teşekkürlerimi sunarım! Yorumunuzdan önce Azure İşlevleriyle çalışmamıştım, ancak şimdi çok daha fazlasını biliyorum. Yüklenen azure blob Pdf'lerini tek bir PDF'ye sipariş etmek ve derlemek, buna kadar neredeyse vazgeçtiğim bir şeydi.
Wallstreetguy
Eğer benim cevap yardım ettin, sen kabul et gibi bir cevap (Tıklayın onay yanındaki cevap için aç / kapat ondan silik boşluğu). Bu, diğer topluluk üyeleri için faydalı olabilir. Teşekkür ederim
SwethaKandikonda-MT