c# – Is it possible to determine if a byte array represents a pdf file that cannot be edited?

Question:

Context

I have two steps in my service, the file upload and download. When uploading to the service, I receive the data through an ASCII byte array .

This data is stored in a database. When downloading, the data referring to the file are fetched from the database and written in binary to a temporary file.

From there, I place a watermark, and download the final file back to the user. It is a PDF file .

The problem

The problem is that when the user uploads a file (PDF) it cannot be edited. It is not a read-only attribute, as the data is being fetched from the database, not the user's computer.

What characterizes the "editability" of the file is a permission assigned within the PDF format when the file is protected .

objective

What I am trying to understand is whether there is a way to identify if the file:

  1. It's a protected PDF
  2. If editing permission has been assigned by the creator of the file

So I can handle the application flow and prevent a non-editable file from being stored in the database (and eventually an error being thrown for not being able to add the watermark.).

Exemplo do byte[]:

    [0] 37  

    [1] 80  

    [2] 68  

    [...] ... 

    [84006] 10  

Remembering that, currently, my solution is to save the file in a temporary location on the server to do this verification. I want to avoid this step and perform any checks directly on the array of data I get from the database.

To reconstruct the file from the data stored in the database, I use the following resource:

BinaryWriter Writer = new BinaryWriter(System.IO.File.OpenWrite(fileName));
Writer.Write("variavel_byte[]");

Answer:

There is a solution without using the Byte Array using iTextSharp, with byte array I have not found anything, including in other searches all point to the components.

PM> Install-Package iTextSharp


    using iTextSharp.text.pdf;

    private void CheckPdfProtection()
    {
        var filePath = @"c:\temp\EmploymentHistory.pdf";
        using (var reader = new PdfReader(filePath))
        {
            if (!reader.IsEncrypted()) return;

            if (!PdfEncryptor.IsPrintingAllowed(Convert.ToInt32(reader.Permissions)))
                throw new InvalidOperationException("Arquivo protegido para impressão");
            if (!PdfEncryptor.IsModifyContentsAllowed(Convert.ToInt32(reader.Permissions)))
                throw new InvalidOperationException("Arquivo protegido para escrita");
        }
    }
Scroll to Top