簡體   English   中英

iText7 pdf 到 blob c#

[英]iText7 pdf to blob c#

使用 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 並將新的發送到 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

下面的代碼展示了如何從文件中讀取 PDF 到 byte[] 以及如何修改存儲為 byte[] 的 PDF。

下載並安裝 NuGet package: iText7

  • 在解決方案資源管理器中,右鍵單擊 <project name> 和 select Manage NuGet Packages...
  • 點擊瀏覽
  • 在搜索框中輸入: iText7
  • Select iText7
  • Select 所需版本
  • 點擊安裝

添加以下使用語句:

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

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

用法

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

}

修改存儲在 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);
}

用法

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 package: Azure.Storage.Blobs

添加以下使用語句:

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 文件用於測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM