Create password protected PDF through PdfSharp
public FileContentResult DownloadPDF()
{
//Create PDF Document
PdfDocument document = new PdfDocument();
//You will have to add Page in PDF Document
PdfPage page = document.AddPage();
//For drawing in PDF Page you will nedd XGraphics Object
XGraphics gfx = XGraphics.FromPdfPage(page);
//For Test you will have to define font to be used
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
//Finally use XGraphics & font object to draw text in PDF Page
gfx.DrawString("FileContent", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
//Specify file name of the PDF file
string filename = "FileName.pdf";
PdfSecuritySettings securitySettings = document.SecuritySettings;
// Setting one of the passwords automatically sets the security level to
// PdfDocumentSecurityLevel.Encrypted128Bit.
securitySettings.UserPassword = "UserPassword";
securitySettings.OwnerPassword = "OwnerPassword";
// Don't use 40 bit encryption unless needed for compatibility reasons
//securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;
// Restrict some rights.
securitySettings.PermitAccessibilityExtractContent = false;
securitySettings.PermitAnnotations = false;
securitySettings.PermitAssembleDocument = false;
securitySettings.PermitExtractContent = false;
securitySettings.PermitFormsFill = true;
securitySettings.PermitFullQualityPrint = false;
securitySettings.PermitModifyDocument = true;
securitySettings.PermitPrint = false;
//Creates a new Memory stream
MemoryStream stream = new MemoryStream();
// Saves the document as stream
document.Save(stream);
document.Close();
// Converts the PdfDocument object to byte form.
byte[] fileBytes = stream.ToArray();
//System.IO.File.Delete(filename);
return File(fileBytes, "application/pdf", filename);
}