Tuesday, March 4, 2014

Securing PDF with not to Print and not to Copy content

Software application is aiding business in accelerating the day to day activities as well as makes so many things easy which eliminates delay in time, costs in $ etc... 
Most of business need data which can be shared over to other in universal or portal format, PDF document is the most common way to share the data across. These data is necessary to each participating roles in business, those roles can be customer or business owner or other business organization and many ....

Now the Data is very critical in all business applications, sharing them on PDF is very easy now a day you get your bank statement by email  and that is in PDF format which is password protected, until you don't enter correct password you cannot view or print that document.
But what if you want to make that PDF just read only i.e. disable print and content copy paste?

Well this can be a business need to, that can be done with itextsharp and here is the sample code/method [in C #] which will secure pdf.

//fileBytes :  can be from service over soap or tcp, it can be stored in DB as file stream or in var binary 
public static byte[] SecurePrintAndExport(byte[] fileBytes)
{
       byte[] securedFilebytes;
       string securedKey = Guid.NewGuid().ToString();
       using (MemoryStream report = new MemoryStream(fileBytes))
       {
              PdfReader reader = new PdfReader(report);
              int numberOfPages = reader.NumberOfPages;
              using (MemoryStream newStream = new MemoryStream())
              {
                     UTF8Encoding encoding = new UTF8Encoding();
                     PdfStamper stamper = new PdfStamper(reader, newStream);

                     stamper.SetEncryption(null, encoding.GetBytes(securedKey),PdfWriter.AllowCopy, PdfWriter.STRENGTH40BITS);
                     stamper.SetEncryption(null, encoding.GetBytes(securedKey),PdfWriter.ALLOW_ASSEMBLY | PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STRENGTH40BITS);
                     stamper.Writer.CloseStream = false;
                     stamper.Close();
                     newStream.Flush();
                     newStream.Position = 0;
                     securedFilebytes = new byte[newStream.Capacity];
                     securedFilebytes = newStream.ToArray();
              }
              reader.Close();
       }
       return securedFilebytes;
}

//How to make call of it...............
byte[] fileBytes = System.IO.File.ReadAllBytes(@"D:\Temp\TestPDF.pdf");
byte[] securedPdf = SecurePrintAndExport(fileBytes);

1 comment: