Protect Base64 PDF with a password using iText 7
Using iText 7, we can define two passwords: a user password and an owner password. A pdf that is encrypted with an owner password can be opened by every one who receives the document. The owner password is there to define permissions (for instance: the document can be viewed, but not printed). If a pdf is encrypted using a user password, everybody who knows the user password can open the file. There is no username, only a user password.
Nuget Package:
Install-Package itext7 -Version 7.1.7
Import Following packages:
using iText.Kernel.Pdf;
using System;
using System.Text;
using System.IO;
Source Code
public static string EncryptPDFwithPassword(string pdfBase64, string passwordUser, string passwordOwner)
{
var encryptedBase64 = string.Empty;
var srcBytes = Convert.FromBase64String(pdfBase64);
var userPassword = Encoding.ASCII.GetBytes(passwordUser);
var ownerPassword = Encoding.ASCII.GetBytes(passwordOwner);
PdfReader reader = new PdfReader(new MemoryStream(srcBytes));
WriterProperties props = new WriterProperties()
.SetStandardEncryption(userPassword, ownerPassword, EncryptionConstants.ALLOW_PRINTING,
EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
using (var memoryStream = new MemoryStream())
{
PdfWriter writer = new PdfWriter(memoryStream, props);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
pdfDoc.Close();
encryptedBase64 = Convert.ToBase64String(memoryStream.ToArray());
}
return encryptedBase64;
}
Use it as:
EncryptPDFwithPassword("base64pdf-without-any-prefixes", "niceuser", "niceowner");
References:
https://www.nuget.org/packages/itext7/
https://itextpdf.com/en/resources/faq/technical-support/itext-7/how-protect-pdf-username-and-password
https://itextpdf.com/en/resources/faq/technical-support/itext-7/how-protect-already-existing-pdf-password
0 Comments