병합 Azure Blob(Pdf 파일)를 하나의 Blob 및 다운로드를 통해 사용자의 C#ASP.NET

0

질문

가 ASP.NET Azure 웹 응용 프로그램에서 포함되는 사용자에 업로드하는 다른 pdf Azure Blob 저장합니다. 나는 사용자를 나중에 다운로드 결합된 PDF 파일 인클루시브의 이전에 업로드 blob 특정 순서입니다. 어떤 아이디어에서 최상의 방식으로 이러한 작업을 수행하는?

asp.net azure blob c#
2021-11-21 19:18:14
1

최고의 응답

1

여기에는 2 개의 해결 방법을 시도할 수 있습니다

  1. 사용 Azure 능합니다.
  2. 다운로드에서 pdf 파일 Azure Blob 로컬 컴퓨터를 병합니다.

사용 Azure 기능

  1. Create an azure 수 프로젝트를 사용하여 HTTP 니다.
  2. 이 설치되어 있는지 확인 아래 패키지를 시작하기 전에 코딩을 가진.
  3. 함수 코드입니다.
  4. 을 만들 기능에 포털입니다.
  5. 게시 코드입니다.

우리가 준비되어 있을 쓰기 시작하는 코드입니다. 우리가 필요한 두개의 파일

  1. ResultClass.cs –반환합 병합된 파일(s)으로 목록입니다.
  2. Function1.cs –CCode 는 파일 이름에서 URL 을 잡고 그들을 저장소 계정에서 병합으로 그들을 하나의 반환합니 다운로드 URL.

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;
        }
    }
}

다운로드에서 pdf 파일 Azure Blob 로컬 컴퓨터,그 다음 그들을 병합

 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);
        }

참고:

  1. Azure 기능을 결합하 PDF Blob Azure 계정에 저장(Blob 컨테이너)
  2. C#을 병합 PDF SDK:병합,결합에서 PDF 파일 C#.net,ASP.NET MVC,Ajax,WinForms,WPF
2021-11-22 05:18:46

SwethaKandikonda-MT,이 놀라운 솔루션 중 하나는 성공적으로 통합됩니다. 나의 많은 당신에게 진심으로 감사에 대한 응답! 지와 함께 일 Azure 기능을 사전에 귀하의 코멘트,하지만 난 그래서 더 많은 지금이다. 주문 컴파일로 업로드 azure blob Pdf 으로 한 PDF 었다가 거의 포기에 있을 때까지이다.
Wallstreetguy

는 경우에 저의 대답입니다 당신을 도움이할 수 있습으로 그것을 받아들이 대답(클릭 옆에 체크 표시에 대답하면서 회색을 채우). 이 도움이 될 수 있는 다른 커뮤니티 구성원. 감사
SwethaKandikonda-MT

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................