Search code examples
c#.netitextmemorystreampdfstamper

iTextSharp PdfStamper consistently only writing out 15 bytes


I'm attempting to write a method for encrypting existing pdf's and writing out the encrypted pdf to a memory stream, using the following code:

    public byte[] ProtectPdfStreamWithPassword(
        string filePath,
        string password)
    {
        using (var outStream = new MemoryStream())
        {
            using (var reader = new PdfReader(filePath))
            {
                using (var stamper = new PdfStamper(reader, outStream))
                {
                    var passwordBytes =
                            Encoding.ASCII.GetBytes(password);

                    stamper.SetEncryption(
                        passwordBytes,
                        passwordBytes,
                        PdfWriter.AllowPrinting,
                        PdfWriter.ENCRYPTION_AES_256);

                    return outStream.ToArray();
                }
            }
        }
    }

I'm following the same pattern I've seen used elsewhere online but I'm running into an issue where the MemoryStream being written into only ever has 15 bytes written to it, when the file passed to the PdfReader has around 8Kb. I did not run into this issue when working with FileStreams instead but I'd prefer to use MemoryStreams here, if possible. Any help would be appreciated.


Solution

  • Okay, so the issue for me was returning the MemoryStream bytes from within the PdfStamper using block. There must be an implicit Flush going on that wasn't happening because I was returning the bytes too soon. I refactored my code to the following, which works:

    public byte[] ProtectPdfStreamWithPassword(
                string filePath,
                string password)
            {
                using (var outStream = new MemoryStream())
                {
                    using (var reader = new PdfReader(filePath))
                    {
                        using (var stamper = new PdfStamper(reader, outStream))
                        {
                            var passwordBytes =
                                    Encoding.ASCII.GetBytes(password);
    
                            stamper.SetEncryption(
                                passwordBytes,
                                passwordBytes,
                                PdfWriter.AllowPrinting,
                                PdfWriter.ENCRYPTION_AES_256);
                        }
                    }
    
                    return outStream.ToArray();
                }
            }