【问题标题】:iText7 pdf to blob c#iText7 pdf to blob c#
【发布时间】:2021-09-27 22:13:24
【问题描述】:

使用 c# 和 iText7 我需要修改现有 PDF 并将其保存到 blob 存储。 我有一个控制台应用程序,它使用文件系统完全满足我的需要:

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

这很好用。但是我不知道如何从 blob 存储中提取 PDF 并将新的 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");

我想我需要将 pdfDoc 作为字节数组。 Outstream 不正确,长度只有 15

【问题讨论】:

  • 那 15 个字节是什么?

标签: c# azure itext


【解决方案1】:

下面的代码展示了如何将 PDF 从文件读取到字节 [] 以及如何修改存储为字节 [] 的 PDF。

下载并安装 NuGet 包:iText7

  • 在解决方案资源管理器中,右键单击 并选择 Manage NuGet Packages...
  • 点击浏览
  • 在搜索框中输入:iText7
  • 选择iText7
  • 选择所需版本
  • 点击安装

添加以下 using 语句:

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

以字节形式获取 PDF[] (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);
}

用法

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 + "'");

}

修改存储在字节中的 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);
}

用法

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 + "'");
}

以下代码改编自Sample01b_HelloWorldAsync.cs,未经测试。

下载并安装 NuGet 包:Azure.Storage.Blobs

添加以下 using 语句:

using Azure.Storage.Blobs;

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

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

这是PDF file for testing

【讨论】:

    猜你喜欢
    • 2021-01-21
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 2016-10-15
    • 2020-12-09
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多