Mám ASP.NET Azure web aplikace napsaná v C#, který zahrnuje uživatele, nahrávání různých souborů pdf do Azure Blob storage. Rád bych uživateli později ke stažení kombinovaný PDF včetně dříve nahraných kuličky v určitém pořadí. Představu o nejlepší způsob, jak toho dosáhnout?
1
Zde jsou 2 řešení, která můžete vyzkoušet
- Použití Azure Funkce.
- Ke stažení pdf soubory z Azure Blob na místním počítači, a pak je sloučit.
Použití Funkce Azure
- Vytvoření azure funkce projektu a použití HTTP Spoušť.
- Ujistěte se, že nainstalovat níže balíčky, než jak začít s kódováním.
- Vytvořit kód Funkce.
- Vytvořte Azure funkce v portálu.
- Zveřejnit kód.
Jsme připraveni začít psát kód. Potřebujeme dva soubory:
- ResultClass.cs – vrací vzniklý soubor(y) jako seznam.
- Function1.cs – CCode, že má názvy souborů z URL, dostane z Úložiště účtu, spojí je do jednoho a vrátí URL pro stažení.
ResultClass.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; }
}
}
Function1.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;
}
}
}
Ke stažení pdf soubory z Azure Blob na místním počítači, a pak je sloučit
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);
}
ODKAZY:
SwethaKandikonda-MT, bylo to úžasné řešení a jeden, který jsem se úspěšně začlenit do své webové stránky. Mnoho mé upřímné díky vám za reakce! Nepracovala jsem s Azure Funkce před váš komentář, ale vím, že mnohem víc teď. Objednávání a sestavování nahraných azure blob Pdf souborů do jednoho PDF bylo něco, co jsem skoro vzdala, až na tuhle.
Wallstreetguy
Pokud moje odpověď vám pomohla, můžete ji přijmout jako odpověď (Klikněte na značku zaškrtnutí vedle odpověď, aby ji přepínat z šedě vyplnit). To může být prospěšné pro ostatní členy komunity. Děkuji
SwethaKandikonda-MT