empira / PDFsharp-1.5

A .NET library for processing PDF
MIT License
1.28k stars 588 forks source link

NullReferenceException when saving with owner password #30

Closed RichardD2 closed 6 years ago

RichardD2 commented 6 years ago

Steps to reproduce:

Expected result:

The document should be saved and protected with a password.

Actual result:

System.NullReferenceException: Object reference not set to an instance of an object.
    at PdfSharp.Pdf.Security.PdfStandardSecurityHandler.PrepareRC4Key(Byte[] key, Int32 offset, Int32 length)
    at PdfSharp.Pdf.Internal.PdfEncoders.FormatStringLiteral(Byte[] bytes, Boolean unicode, Boolean prefix, Boolean hex, PdfStandardSecurityHandler securityHandler)
    at PdfSharp.Pdf.IO.PdfWriter.WriteDocString(String text)
    at PdfSharp.Pdf.PdfDate.WriteObject(PdfWriter writer)
    at PdfSharp.Pdf.PdfDictionary.WriteDictionaryElement(PdfWriter writer, PdfName key)
    at PdfSharp.Pdf.PdfDictionary.WriteObject(PdfWriter writer)
    at PdfSharp.Pdf.PdfDocument.DoSave(PdfWriter writer)
    at PdfSharp.Pdf.PdfDocument.Save(Stream stream, Boolean closeStream)
    at PdfSharp.Pdf.PdfDocument.Save(String path)

Code:

static void Main()
{
    // Create a new PDF document
    PdfDocument document = new PdfDocument();
    document.Info.Title = "Created with PDFsharp";

    // Create an empty page
    PdfPage page = document.AddPage();

    // Get an XGraphics object for drawing
    XGraphics gfx = XGraphics.FromPdfPage(page);

    // Create a font
    XFont font = new XFont("Times New Roman", 20, XFontStyle.BoldItalic);

    // Draw the text
    gfx.DrawString("Hello, World!", font, XBrushes.Black,
        new XRect(0, 0, page.Width, page.Height),
        XStringFormats.Center);

    // Set the password(s):
    document.SecuritySettings.OwnerPassword = "password";
    document.SecuritySettings.UserPassword = "password";

    // Save the document...
    const string filename = "HelloWorld_tempfile.pdf";
    document.Save(filename);

    // ...and start a viewer.
    Process.Start(filename);
}

Notes:

System details:

RichardD2 commented 6 years ago

Same issue as #31:

TH-Soft commented 6 years ago

Not replicable with RC1.