Friday, July 25, 2014

iTextSharp - Make the PDF file secure

When you use iTextSharp, which is a tool used to generate PDF, using C#, you can make the PDF secure. I mean by secure, you can modify the security properities of the PDF like printing, allow modification, allow copying...etc










You have just to write the following fragment: 

            // define the document
            Document document = new Document(PageSize.A4);
            document.SetMargins(0, 0, 20, 10);

            // create memory stream to save the file
            MemoryStream ms = new MemoryStream();
            PdfWriter p = PdfWriter.GetInstance(document, ms);

            // set security properties
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            p.SetEncryption(null, encoding.GetBytes("12"), PdfWriter.AllowPrinting, 
            PdfWriter.STRENGTH40BITS);

            // open the document
            document.Open();

            // generate the document content
            document.Add(PDF_FinanceCertificate(item, p, document));

            // close the final PDF document
            document.Close();

            byte[] pdfFile = ms.ToArray();

            return pdfFile;


Note that, because we implement security issue in the PDF, the generation operation will take more time more than usual.