简体   繁体   English

iText7 pdf 到 blob c#

[英]iText7 pdf to blob c#

Using c# and iText7 I need to modify an existing PDF and save it to blob storage.使用 c# 和 iText7 我需要修改现有的 PDF 并将其保存到 blob 存储。 I have a console app that does exactly what I need using the file system:我有一个控制台应用程序,它使用文件系统完全满足我的需要:

        PdfReader reader = new PdfReader(source);
        PdfWriter writer = new PdfWriter(destination2);
        PdfDocument pdfDoc = new PdfDocument(reader, writer);
        PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
        fields = form.GetFormFields();

        fields.TryGetValue("header", out PdfFormField cl);
        var type = cl.GetType();
        cl.SetValue("This is a header");
        pdfDoc.Close();

This works just fine.这很好用。 However I can not figure out how to do the same thing pulling the PDF from blob storage and sending the new one to blob storage但是我不知道如何做同样的事情,从 blob 存储中拉出 PDF 并将新的发送到 blob 存储

            IDictionary<string, PdfFormField> fields;
            MemoryStream outStream = new MemoryStream();
            var pdfTemplate = _blobStorageService.GetBlob("mycontainer", "TestPDF.pdf");
            PdfReader reader = new PdfReader(pdfTemplate);
            PdfWriter writer = new PdfWriter(outStream);
            PdfDocument pdfDoc = new PdfDocument(reader, writer);
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
            fields = form.GetFormFields();

            fields.TryGetValue("header", out PdfFormField cl);

            cl.SetValue("This is a header");
            pdfDoc.Close();
            outStream.Position = 0;
            _blobStorageService.UploadBlobAsync("mycontainer", **THIS IS THE ISSUE**, "newpdf.pdf");

I think I need to get pdfDoc as a byte array.我想我需要将 pdfDoc 作为字节数组获取。 Outstream is incorrect, it is only has a length of 15 Outstream 不正确,它的长度只有 15

The code below shows how to read a PDF from a file into a byte[] and also how to modify a PDF that's stored as a byte[].下面的代码展示了如何从文件中读取 PDF 到 byte[] 以及如何修改存储为 byte[] 的 PDF。

Download and install NuGet package: iText7下载并安装 NuGet package: iText7

  • In Solution Explorer, right-click <project name> and select Manage NuGet Packages...在解决方案资源管理器中,右键单击 <project name> 和 select Manage NuGet Packages...
  • Click Browse点击浏览
  • In the search box type: iText7在搜索框中输入: iText7
  • Select iText7 Select iText7
  • Select desired version Select 所需版本
  • Click Install点击安装

Add the following using statements:添加以下使用语句:

using System.IO;
using iText.Kernel.Pdf;
using iText.Forms;
using iText.Forms.Fields;

Get PDF as byte[] (GetPdfBytes):获取 PDF 作为 byte[] (GetPdfBytes):

public static Task<byte[]> GetPdfBytes(string pdfFilename)
{
    byte[] pdfBytes = null;

    using (PdfReader reader = new PdfReader(pdfFilename))
    {
        using (MemoryStream msPdfWriter = new MemoryStream())
        {
            using (PdfWriter writer = new PdfWriter(msPdfWriter))
            {
                using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
                {
                    //don't close underlying streams when PdfDocument is closed
                    pdfDoc.SetCloseReader(false);
                    pdfDoc.SetCloseWriter(false);

                    //close
                    pdfDoc.Close();

                    //set value
                    msPdfWriter.Position = 0;

                    //convert to byte[]
                    pdfBytes = msPdfWriter.ToArray();
                }
            }
        }
    }

    return Task.FromResult(pdfBytes);
}

Usage :用法

byte[] pdfBytes = null;
string filename = string.Empty;

OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PDF File (*.pdf)|*.pdf";

if (ofd.ShowDialog() == DialogResult.OK)
{
    //get PDF as byte[]
    var tResult = GetPdfBytes(ofd.FileName);
    pdfBytes = tResult.Result;

    //For testing, write back to file so we can ensure that the PDF file opens properly
    //create a new filename
    filename = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName) + " - Test.pdf";
    filename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(ofd.FileName), filename);

    //save to file
    File.WriteAllBytes(filename, pdfBytes);
    System.Diagnostics.Debug.WriteLine("Saved as '" + filename + "'");

}

Modify PDF that's stored in a byte[] (ModifyPdf)修改存储在 byte[] 中的PDF (ModifyPdf)

public static Task<byte[]> ModifyPdf(byte[] pdfBytes)
{
    byte[] modifiedPdfBytes = null;

    using (MemoryStream ms = new MemoryStream(pdfBytes))
    {
        using (PdfReader reader = new PdfReader(ms))
        {
            using (MemoryStream msPdfWriter = new MemoryStream())
            {
                using (PdfWriter writer = new PdfWriter(msPdfWriter))
                {
                    using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
                    {
                        //don't close underlying streams when PdfDocument is closed
                        pdfDoc.SetCloseReader(false);
                        pdfDoc.SetCloseWriter(false);

                        //get AcroForm from document
                        PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);

                        //get form fields
                        IDictionary<string, PdfFormField> fields = form.GetFormFields();

                        //for testing, show all fields
                        foreach (KeyValuePair<string, PdfFormField> kvp in fields)
                        {
                            System.Diagnostics.Debug.WriteLine("Key: '" + kvp.Key + "' Value: '" + kvp.Value + "'");
                        }

                        PdfFormField cl = null;

                        //get specified field
                        fields.TryGetValue("1 Employee name", out cl);

                        //set value for specified field
                        cl.SetValue("John Doe");

                        //close PdfDocument
                        pdfDoc.Close();

                        //set value
                        msPdfWriter.Position = 0;

                        //convert to byte[]
                        modifiedPdfBytes = msPdfWriter.ToArray();
                    }
                }
            }
        }
    }

    return Task.FromResult(modifiedPdfBytes);
}

Usage :用法

byte[] pdfBytes = null;
string filename = string.Empty;

OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PDF File (*.pdf)|*.pdf";

if (ofd.ShowDialog() == DialogResult.OK)
{
    //get PDF as byte[]
    var tResult = GetPdfBytes(ofd.FileName);
    pdfBytes = tResult.Result;

    //modify PDF
    pdfBytes = await ModifyPdf(pdfBytes);

    //create a new filename
    filename = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName) + " - TestModified.pdf";
    filename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(ofd.FileName), filename);

    //save to file
    File.WriteAllBytes(filename, pdfBytes);
    System.Diagnostics.Debug.WriteLine("Saved as '" + filename + "'");
}

The code below is adapted from Sample01b_HelloWorldAsync.cs and is untested.下面的代码改编自Sample01b_HelloWorldAsync.cs并且未经测试。

Download and install NuGet package: Azure.Storage.Blobs下载并安装 NuGet package: Azure.Storage.Blobs

Add the following using statement:添加以下使用语句:

using Azure.Storage.Blobs;

DownloadPdf :下载PDF :

public static async Task<byte[]> DownloadPdf(string connectionString, string blobContainerName, string blobName)
{
    byte[] pdfBytes = null;
 
    using (MemoryStream ms = new MemoryStream())
    {
        // Get a reference to the container and then create it
        BlobContainerClient container = new BlobContainerClient(connectionString, blobContainerName);
        Azure.Response<Azure.Storage.Blobs.Models.BlobContainerInfo> responseCA = await container.CreateAsync();

        // Get a reference to the blob
        BlobClient blob = container.GetBlobClient(blobName);

        // Download the blob's contents and save it to a file
        Azure.Response responseDTA = await blob.DownloadToAsync(ms);

        //set value
        ms.Position = 0;

        //convert to byte[]
        pdfBytes = ms.ToArray();
    }

    return pdfBytes;
}

UploadPdf :上传PDF

public static async Task<Azure.Response<Azure.Storage.Blobs.Models.BlobContentInfo>> UpdloadPdf(byte[] pdfBytes, string connectionString, string blobContainerName, string blobName)
{
    Azure.Response<Azure.Storage.Blobs.Models.BlobContentInfo> result = null;

    using (MemoryStream ms = new MemoryStream(pdfBytes))
    {
        //this statement may not be necessary
        ms.Position = 0; 

        // Get a reference to the container and then create it
        BlobContainerClient container = new BlobContainerClient(connectionString, blobContainerName);
        await container.CreateAsync();

        // Get a reference to the blob
        BlobClient blob = container.GetBlobClient(blobName);

        //upload
        result = await blob.UploadAsync(ms);
    }

    return result;
}

Here's a PDF file for testing .这里有一个PDF 文件用于测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# 删除 Azure Blob - 无效的 URI - C# Delete Azure Blob - Invalid Uri Azure 使用标签的 blob 存储搜索 c# - Azure blob storage search using tags c# 将文件写入 blob 存储并使用 C# 保存 SaS URL - Write file to blob storage and save the SaS URL using C# Azure function C#:写入 Azure 上的块 blob(csv 文件)存储帐户创建了两个版本的 blob - Azure function C#: Writing to Block blob (csv file) on Azure Storage Account creates two versions of the blob 将 blob 从一个容器复制到另一个容器时出错,最终内容在 C# 中为 0 字节 - Error when copying a blob from one container to another, the content final is 0 bytes in C# 创建并上传 PDF 到 azure blob 存储 - Create and upload PDF to azure blob storage 使用 UWP C# (mediaCapture) 捕获网络摄像头并保存到 azure blob 存储中 - Capture webcamera and save into azure blob storage using UWP C# (mediaCapture) C# - 如何将文件上传到 Azure 存储 Blob(未知物理路径) - C# - How to upload files to Azure Storage Blob (unknown phisic path) 如何使用 Blazor 将大文件上传到 WebAPI (C#) 并将其存储到 Azure Blob 存储中 - How to upload large file using Blazor to WebAPI (C#) and store it into Azure Blob storage 为什么json文件上传到azure blob存储c#时出现Rare characters? - Why does Rare characters appears when json file is uploaded to azure blob storage c#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM