My requirement was to create a PDF document on the fly within a ASP.net application. The document to be created was a certificate and it had a fixed format. Only some of the text (like name, date) within the certificate had to fetched from the database and the document had to be created on user request (on demand, on the fly).
Instead of creating the whole document from scratch each time the document is to be created, I thought the best approach would be to create a PDF template and add form fields for all the fields that would change. Then use Aspose control to open the template, fill the fields. I thought this would be an efficient way to create these documents and response time would be reduced drastically. It would also be easier to code because most of the content of the document is in place and I do not have to code to place the content with the document.
As this was a ASP.net application and the document was to be created only the user requested for it (using a link within a web page), I did not want to save the document on the web server because I did not want to go through the hassle of having to delete these documents later or having piles of documents using my web server space. So the solution was to use streams and manage everything in memory.
The document also had to be secure and the user must not be able to edit the fields or make any changes to the document. The only permission that was to be available to the users was to open the document and print it. So here is the code I finally came up with
public static MemoryStream CreateCertificate(string pName, string pDate)
{
//open template
string lpdfTemplate = "";
MemoryStream certificateFormStream = new MemoryStream();
//Get the form fields
Aspose.Pdf.Kit.Form certificateForm = new Form(lpdfTemplate, certificateFormStream);
//fill the form fields
certificateForm.FillField("Name", pName);
certificateForm.FillField("Date", "Date: " + Convert.ToDateTime(pDate).ToString("MMMM dd, yyyy"));
//Flatten form fields so that they are no longer editable
certificateForm.FlattenAllFields();
certificateForm.Save();
//secure the file
MemoryStream secureCertificateStream = new MemoryStream();
DocumentPrivilege documentPrivilege = DocumentPrivilege.ForbidAll;
documentPrivilege.AllowPrint = true;
documentPrivilege.PrintAllowLevel = 2;
PdfFileSecurity pdfFileSecurity = new PdfFileSecurity(certificateFormStream, secureCertificateStream);
pdfFileSecurity.SetPrivilege(documentPrivilege);
pdfFileSecurity.EncryptFile("",, documentPrivilege, KeySize.x128);
certificateFormStream.Flush();
certificateFormStream.Close();
secureCertificateStream.Flush();
secureCertificateStream.Close();
//return stream
return secureCertificateStream;
}