Hi tanws8,
You can secure the PDF by setting the password and have to share the password to paid user, so that they can open it.
Non paid user can download the PDF but without the password they can't view the content.
For password you may apply any logic to share the password to paid user by email of sms.
Refer below code to download password protected pdf. For this example i have set default password. You can change your logic.
Model
public class FileModel
{
public string FileName { get; set; }
}
Namespaces
using System.IO;
using iTextSharp.text.pdf;
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Files/"));
List<FileModel> files = new List<FileModel>();
foreach (string filePath in filePaths)
{
files.Add(new FileModel { FileName = Path.GetFileName(filePath) });
}
return View(files);
}
public FileResult DownloadFile(string fileName)
{
string path = Server.MapPath("~/Files/") + fileName;
byte[] bytes = System.IO.File.ReadAllBytes(path);
using (MemoryStream input = new MemoryStream(bytes))
{
using (MemoryStream output = new MemoryStream())
{
string password = "pass@123";
PdfReader reader = new PdfReader(input);
PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS);
bytes = output.ToArray();
return File(bytes, "application/pdf");
}
}
}
}
View
@using File_Folder_Download_MVC.Models
@model List<FileModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table>
<tr>
<th>File Name</th>
<th></th>
</tr>
@foreach (FileModel file in Model)
{
<tr>
<td>@file.FileName</td>
<td>@Html.ActionLink("Download", "DownloadFile", new { fileName = file.FileName }, new { target = "_blank" })</td>
</tr>
}
</table>
</body>
</html>
Screenshot