Exemplo n.º 1
0
        public static void MakeReadOnly(string inputFilePath, string outputFilePath, string password)
        {
            try
            {
                using (Stream inputPdfStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))

                    using (Stream outputPdfStream2 = new FileStream(outputFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        //Opens our outputted file for reading
                        var reader2 = new PdfReader(inputPdfStream);

                        //Encrypts the outputted PDF to make it not allow Copy or Pasting
                        PdfEncryptor.Encrypt(
                            reader2,
                            outputPdfStream2,
                            true,
                            null,
                            password,
                            PdfWriter.ALLOW_SCREENREADERS
                            );
                        //Creates the outputted final file
                        reader2.Close();
                    }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 2
0
        //public void EmbadedFileToPDF(string strPDFPath, List<string> fileToEmbad)
        //{
        //    PdfReader reader = new PdfReader(strPDFPath);
        //    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));

        //}


        //Additional Function
        private static void PasswordProtectPDF(string strPDFPath, string strPassword)
        {
            try
            {
                Stream input        = new FileStream(strPDFPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] btSourceFile = StreamToByteArray(input);
                input.Close();

                using (Stream output = new FileStream(strPDFPath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    PdfReader reader = new PdfReader(btSourceFile);
                    PdfReader.unethicalreading = true;

                    PdfEncryptor.Encrypt(reader, output, true, strPassword, strPassword, PdfWriter.ALLOW_PRINTING | PdfWriter.AllowFillIn | PdfWriter.AllowScreenReaders | PdfWriter.ENCRYPTION_AES_128);

                    reader.Close();
                    //PdfEncryptor.IsPrintingAllowed(PdfWriter.ALLOW_PRINTING);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message == "Bad user password")
                {
                    throw new Exception("Document is password protected");
                }
                else
                {
                    throw ex;
                }
            }
        }
Exemplo n.º 3
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            TargetFile objTarget = new TargetFile(this.FilePathTextBox.Text);
            string     sPW       = "TOHU";

            byte[] objPW = Encoding.ASCII.GetBytes(sPW);

            using (PdfReader objReader = new PdfReader(objTarget.SourcePath, objPW))
            {
                using (var objOutputFileStream = new FileStream(objTarget.OutputPath, FileMode.Create))
                {
                    string sPassword   = this.IsNeedPassWordForOpenFileCheckBox.IsChecked == true ? this.PasswordTextBox.Text : null;
                    int    nPermission = 0;

                    if (this.AllowCopyCheckBox.IsChecked == true)
                    {
                        nPermission = nPermission | PdfWriter.AllowCopy;
                    }

                    if (this.AllowPrintingCheckBox.IsChecked == true)
                    {
                        nPermission = nPermission | PdfWriter.AllowPrinting;
                    }
                    PdfEncryptor.Encrypt(objReader, objOutputFileStream, true, sPassword, sPW, nPermission);
                }
            }
            objTarget.CleanTempFile();

            MessageBox.Show("完成指定設定。");
        }
Exemplo n.º 4
0
        protected string EncriptarPDF(string Archivo)
        {
            string ArchivoE = "";

            try
            {
                Random rnd = new Random();
                string Key = DateTime.Now.AddMinutes(rnd.NextDouble()).ToString("yyyyMMMMddddHHmmssfffff");
                //string Key = "Pruebas";
                string CarpetaArchivo = Path.GetDirectoryName(Archivo);

                ArchivoE = Path.Combine(CarpetaArchivo, Path.GetFileNameWithoutExtension(Archivo) + rnd.Next().ToString() + ".pdf");

                using (Stream input = new FileStream(Archivo, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (Stream output = new FileStream(ArchivoE, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        PdfReader reader = new PdfReader(input);
                        PdfEncryptor.Encrypt(reader, output, true, null, Key, PdfWriter.ALLOW_PRINTING);
                    }
                }

                if (File.Exists(ArchivoE))
                {
                    File.Delete(Archivo);
                }
            }
            catch (Exception ex)
            {
                ArchivoE = "Error: " + ex.Message;
            }

            return(ArchivoE);
        }
Exemplo n.º 5
0
        public static void AssertProtection(string filePath, FileAuthentication fileAuth, AuthenticationManager authenticationManager,
                                            bool expectedIsEncrypted,
                                            bool expectedDontEncryptMetadata,
                                            bool expectedAllowAssembly          = false,
                                            bool expectedAllowCopy              = false,
                                            bool expectedAllowDegradedPrinting  = false,
                                            bool expectedAllowFillIn            = false,
                                            bool expectedAllowModifyAnnotations = false,
                                            bool expectedAllowModifyContents    = false,
                                            bool expectedAllowPrinting          = false,
                                            bool expectedAllowScreenReaders     = false)
        {
            using (var comparer = new PdfComparer(filePath, fileAuth, authenticationManager))
            {
                Assert.AreEqual(expectedIsEncrypted, comparer.pdfReader.IsEncrypted());
                Assert.AreEqual(expectedDontEncryptMetadata, !comparer.pdfReader.IsMetadataEncrypted());

                if (expectedAllowAssembly && expectedAllowCopy && expectedAllowDegradedPrinting && expectedAllowFillIn &&
                    expectedAllowModifyAnnotations && expectedAllowModifyContents && expectedAllowPrinting && expectedAllowScreenReaders)
                {
                    Assert.IsTrue(comparer.pdfReader.IsOpenedWithFullPermissions);
                }
                else
                {
                    Assert.AreEqual(expectedAllowAssembly, PdfEncryptor.IsAssemblyAllowed((int)comparer.pdfReader.Permissions));
                    Assert.AreEqual(expectedAllowCopy, PdfEncryptor.IsCopyAllowed((int)comparer.pdfReader.Permissions));
                    Assert.AreEqual(expectedAllowDegradedPrinting, PdfEncryptor.IsDegradedPrintingAllowed((int)comparer.pdfReader.Permissions));
                    Assert.AreEqual(expectedAllowFillIn, PdfEncryptor.IsFillInAllowed((int)comparer.pdfReader.Permissions));
                    Assert.AreEqual(expectedAllowModifyAnnotations, PdfEncryptor.IsModifyAnnotationsAllowed((int)comparer.pdfReader.Permissions));
                    Assert.AreEqual(expectedAllowModifyContents, PdfEncryptor.IsModifyContentsAllowed((int)comparer.pdfReader.Permissions));
                    Assert.AreEqual(expectedAllowPrinting, PdfEncryptor.IsPrintingAllowed((int)comparer.pdfReader.Permissions));
                    Assert.AreEqual(expectedAllowScreenReaders, PdfEncryptor.IsScreenReadersAllowed((int)comparer.pdfReader.Permissions));
                }
            }
        }
Exemplo n.º 6
0
        public void EncryptPdf(string inputFile, string outputFile, string password)
        {
            try
            {
                using (Stream input = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (Stream output = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        PdfReader reader = new PdfReader(input);
                        PdfEncryptor.Encrypt(reader, output, PdfWriter.ENCRYPTION_AES_256, password, password, PdfWriter.ENCRYPTION_AES_256);
                    }
                }
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show("Error Message: " + ex.Message + Environment.NewLine + "Inner Exception: "
                                + ex.InnerException + Environment.NewLine + "Stack Trace: " + ex.StackTrace);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Message: " + ex.Message + Environment.NewLine + "Inner Exception: "
                                + ex.InnerException + Environment.NewLine + "Stack Trace: " + ex.StackTrace);

                File.Delete(outputFile);
            }
        }
Exemplo n.º 7
0
        public void Replace(Object sender,
                            EventArgs e)
        {
            //Path to where you want the file to output
            string outputFilePath = "C:/Users/eu725cj/Documents/test123.pdf";
            //Path to where the pdf you want to modify is
            string inputFilePath = "C:/Users/eu725cj/Documents/input1.pdf";

            try
            {
                using (Stream inputPdfStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    //using (Stream outputPdfStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                    using (Stream outputPdfStream2 = new FileStream(outputFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        string password = "******";
                        //Opens our outputted file for reading
                        var reader2 = new PdfReader(inputPdfStream);

                        //Encrypts the outputted PDF to make it not allow Copy or Pasting
                        PdfEncryptor.Encrypt(
                            reader2,
                            outputPdfStream2,
                            true,
                            null,
                            password,
                            PdfWriter.ALLOW_SCREENREADERS
                            );
                        //Creates the outputted final file
                        reader2.Close();
                    }
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 8
0
        public void SendPDFEmail(string dt, string Email)
        {
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                {
                    StringReader sr = new StringReader(dt.ToString());

                    Document   pdfDoc     = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);

                        pdfDoc.Open();
                        htmlparser.Parse(sr);
                        pdfDoc.Close();
                        byte[] bytes = memoryStream.ToArray();
                        memoryStream.Close();

                        using (MemoryStream inputData = new MemoryStream(bytes))
                        {
                            using (MemoryStream outputData = new MemoryStream())
                            {
                                string    PDFFileword = "adt";//you can also generate Dynamic word
                                PdfReader reader      = new PdfReader(inputData);
                                PdfEncryptor.Encrypt(reader, outputData, true, PDFPassword, PDFPassword, PdfWriter.ALLOW_SCREENREADERS);
                                bytes = outputData.ToArray();
                                try
                                {
                                    var         MsgBody = "         Please find the attached pay slip for the month of " + PayslipMonth + " " + PayslipYear + ". Any queries, feel free to contact me." + Environment.NewLine + Environment.NewLine + "Thanks," + Environment.NewLine + "Sravani Tamma" + Environment.NewLine + "Executive-HR";
                                    var         Note    = Environment.NewLine + "NOTE : Your PDF Passcode is your Date of Birth." + Environment.NewLine + "Ex: If your Birthday date like  March 5th, 2010 Then PassCode :05/03/2010 ";
                                    MailMessage message = new MailMessage();
                                    SmtpClient  smtp    = new SmtpClient();

                                    message.From = new MailAddress("*****@*****.**");
                                    message.To.Add(new MailAddress(Email));
                                    message.Subject = "Payslip for " + PayslipMonth;
                                    message.Body    = "Hi " + EmpName + "," + Environment.NewLine + Environment.NewLine + MsgBody + Environment.NewLine + Note;
                                    message.Attachments.Add(new Attachment(new MemoryStream(bytes), NameOfPDF));
                                    smtp.Port                  = 80;
                                    smtp.Host                  = "smtpout.secureserver.net";
                                    smtp.EnableSsl             = false;
                                    smtp.UseDefaultCredentials = false;
                                    smtp.Credentials           = new NetworkCredential("*****@*****.**", "123456aA");
                                    smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                                    smtp.Send(message);
                                    lblMsg.Text = "Mail sent successfully";
                                }
                                catch (Exception ex)
                                {
                                    lblMsg.Text = "err: " + ex.Message;
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 9
0
 protected void btnTestPDF_Click(object sender, EventArgs e)
 {
     using (Stream input = new FileStream(Server.MapPath("~/mockup/test.pdf"), FileMode.Open, FileAccess.Read, FileShare.Read))
         using (Stream output = new FileStream(Server.MapPath("~/mockup/test_encrypted.pdf"), FileMode.Create, FileAccess.Write, FileShare.None))
         {
             PdfReader reader = new PdfReader(input);
             PdfEncryptor.Encrypt(reader, output, true, "test", "test", PdfWriter.AllowPrinting);
         }
 }
Exemplo n.º 10
0
 static void EncryptPDF(string SrcPath, string OutPath, string passwd)
 {
     using (PdfReader reader = new PdfReader(SrcPath))
     {
         using (var os = new FileStream(OutPath, FileMode.Create))
         {
             PdfEncryptor.Encrypt(reader, os, true, passwd, passwd, PdfWriter.ALLOW_SCREENREADERS);
         }
     }
 }
 public void EncryptPdf(string sourcePdf, string outputPdfFile, string password)
 {
     using (Stream input = new FileStream(sourcePdf, FileMode.Open, FileAccess.Read, FileShare.Read))
     {
         using (Stream output = new FileStream(outputPdfFile, FileMode.Create, FileAccess.Write, FileShare.None))
         {
             PdfReader reader = new PdfReader(input);
             PdfEncryptor.Encrypt(reader, output, Encoding.ASCII.GetBytes(password), Encoding.ASCII.GetBytes(password), PdfWriter.AllowPrinting, true);
         }
     }
 }
        public ActionResult FileUpload(IFormFile files)
        {
            String FileExt = Path.GetExtension(files.FileName).ToUpper();

            if (FileExt == ".PDF")
            {
                Stream fileStream = files.OpenReadStream();
                var    mStreamer  = new MemoryStream(1000 * 1024);
                mStreamer.SetLength(fileStream.Length);
                fileStream.Read(mStreamer.GetBuffer(), 0, (int)fileStream.Length);
                mStreamer.Seek(0, SeekOrigin.Begin);
                byte[] bytes = mStreamer.GetBuffer();

                FileStream fs = new FileStream(files.FileName, FileMode.Append, FileAccess.Write);
                using (MemoryStream inputData = new MemoryStream(bytes))
                {
                    using (MemoryStream outputData = new MemoryStream())
                    {
                        //ReaderProperties rp = new ReaderProperties();

                        iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(bytes, password);
                        var    font            = BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
                        byte[] watemarkedbytes = AddWatermark(bytes, font);

                        iTextSharp.text.pdf.PdfReader awatemarkreader = new iTextSharp.text.pdf.PdfReader(watemarkedbytes, password);

                        PdfEncryptor.Encrypt(awatemarkreader, outputData, true, "123456", "123456", PdfWriter.ALLOW_MODIFY_CONTENTS);

                        bytes = outputData.ToArray();

                        FileDetailsModel Fd = new Models.FileDetailsModel();
                        Fd.FileName    = files.FileName;
                        Fd.FileContent = bytes;
                        SaveFileDetails(Fd);
                        return(File(bytes, "application/pdf"));
                    }
                }
                // ReaderProperties rp = new ReaderProperties(); rp.SetOwnerPassword(new System.Text.UTF8Encoding().GetBytes("123456"));

                //iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(rp,str);
                //PdfEncryptor.Encrypt(reader, Filebytes, true, "secret", "secret", PdfWriter.ALLOW_PRINTING);
                //MemoryStream ObjememoryStream = new MemoryStream();
                //byte[] output = Filebytes.ToArray();

                //BinaryReader Br = new BinaryReader(Filebytes);
                //Byte[] FileDet = Br.ReadBytes((Int32)str.Length);
            }
            else
            {
                ViewBag.FileStatus = "Invalid file format.";
                return(View());
            }
        }
Exemplo n.º 13
0
        // Sending Mail to User with pdf Attachment
        public static bool Sendmail(int orderid)
        {
            User      user      = UserHelper.GetUserByOrderId(orderid);
            Candidate candidate = UserHelper.GetCandidateByOrderId(orderid);
            string    toAddress = user.Email;
            bool      isSent    = false;

            try
            {
                StringBuilder emailBody = new StringBuilder(ConstructMail.GetMailBody(Constant.STATUS_COMPLETE));
                emailBody = emailBody.Replace(Constant.CONST_FIRSTNAME, user.FirstName);
                emailBody = emailBody.Replace(Constant.CONST_LASTNAME, user.LastName);

                string subject = Constant.CONST_ORDERCOMPLETE_SUBJECT;
                subject = subject.Replace(Constant.CONST_ORDERID, orderid.ToString());
                MailMessage mail = new MailMessage(ConfigurationManager.AppSettings["Email"].ToString(), toAddress, subject, emailBody.ToString());
                mail.IsBodyHtml = true;
                string PDF_File_Path = GetFilePath() + "\\" + orderid.ToString() + ".pdf";

                FileStream stream = File.OpenRead(PDF_File_Path);


                int    length = Convert.ToInt32(stream.Length);
                byte[] data   = new byte[length];
                stream.Read(data, 0, length);
                stream.Close();
                using (MemoryStream input = new MemoryStream(data)) {
                    using (MemoryStream output = new MemoryStream()) {
                        string    password = candidate.Email;
                        PdfReader reader   = new PdfReader(input);
                        PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS);
                        data = output.ToArray();
                    }
                }

                mail.Attachments.Add(new Attachment(new MemoryStream(data), orderid + ".pdf"));
                SmtpClient smtp = new SmtpClient();
                smtp.Send(mail);

                EmailSendLog emailSendLog = new EmailSendLog();
                emailSendLog.OrderId    = orderid;
                emailSendLog.UserMailId = toAddress;
                emailSendLog.InsertTime = DateTime.Now;

                OrderHelper.SaveMailSendLog(emailSendLog);

                isSent = true;
            }
            catch (Exception ex) { }

            return(isSent);
        }
Exemplo n.º 14
0
        public static void SetPassword(string pdfPath, string password, string outputPath)
        {
            pdfPath    = pdfPath?.GetFullPath();
            outputPath = outputPath?.GetFullPath();

            using (Stream input = new FileStream(pdfPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (Stream output = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    PdfReader reader = new PdfReader(input);
                    PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS);
                }
            }
        }
Exemplo n.º 15
0
        public EncryptStatements(string accNumber, string statementPath, string encryptedPath)
        {
            var str = accNumber.Substring(5, 4);

            HashedAccountNumber = accNumber.Replace(str, "####");
            var path1 = statementPath;
            var path2 = encryptedPath;

            using (var isp = (Stream) new FileStream(path1, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (var os = (Stream) new FileStream(path2, FileMode.Create, FileAccess.Write, FileShare.None))
                    PdfEncryptor.Encrypt(new PdfReader(isp), os, true, str, str, 512);
            }
        }
Exemplo n.º 16
0
        public static void AddPWtoPDFFile(string inputFile, string outputFile, string folder, string reviewerPassword, string ownerPassword)
        {
            string WorkingFolder = folder;                                 // Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string InputFile     = Path.Combine(WorkingFolder, inputFile); // Path.Combine(WorkingFolder, "Test.pdf");
            string OutputFile    = Path.Combine(WorkingFolder, outputFile);

            using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    PdfReader reader = new PdfReader(input);
                    PdfEncryptor.Encrypt(reader, output, true, reviewerPassword, ownerPassword, PdfWriter.ALLOW_SCREENREADERS);
                }
            }
        }
Exemplo n.º 17
0
 public static byte[] set_password(byte[] pdfContent, string password)
 {
     if (string.IsNullOrEmpty(password))
     {
         return(pdfContent);
     }
     else
     {
         using (PdfReader reader = new PdfReader(pdfContent))
             using (MemoryStream m = new MemoryStream())
             {
                 PdfEncryptor.Encrypt(reader, m, true, password, password, PdfAWriter.ALLOW_SCREENREADERS);
                 return(m.ToArray());
             }
     }
 }
Exemplo n.º 18
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public async Task EncryptAsync(string pdfSource, string newPdfSavePath, string passWord)
 {
     await Task.Run(() =>
     {
         var reader = new PdfReader(pdfSource);
         using (var os = new FileStream(newPdfSavePath, FileMode.Create))
         {
             var userPassword  = Encoding.Default.GetBytes(passWord);
             var ownerPassword = Encoding.Default.GetBytes(passWord);
             var permissions   = EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_ASSEMBLY;
             PdfEncryptor.Encrypt(reader, os,
                                  new EncryptionProperties().SetStandardEncryption(userPassword, ownerPassword, permissions,
                                                                                   EncryptionConstants.ENCRYPTION_AES_256));
         }
     });
 }
Exemplo n.º 19
0
        public static Byte[] AddPWtoPDFMemory(Byte[] pdfDocument, string reviewerPassword, string ownerPassword)
        {
            try
            {
                MemoryStream stream1 = new MemoryStream(pdfDocument);
                MemoryStream output  = new MemoryStream();

                PdfReader input = new PdfReader(stream1.ToArray());
                PdfEncryptor.Encrypt(input, output, true, reviewerPassword, ownerPassword, PdfWriter.ALLOW_SCREENREADERS);

                return(output.ToArray());
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Exemplo n.º 20
0
        public byte[] PasswordProtect(byte[] bytes, string password)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                return(new byte[0]);
            }

            using (var input = new MemoryStream(bytes))
            {
                using (var output = new MemoryStream())
                {
                    var reader = new PdfReader(input);
                    PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS);
                    return(output.ToArray());
                }
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Set Password to a PDF file
        /// </summary>
        /// <param name="srcFile">source PDF file path</param>
        /// <param name="dstFile">destination PDF file path</param>
        /// <param name="ownerPassword">owner password</param>
        /// <param name="userPassword">user password</param>
        public static void SetPassword(string srcFile, string dstFile, string ownerPassword, string userPassword)
        {
            byte[] byteUSER  = Encoding.ASCII.GetBytes(userPassword);  // user password
            byte[] byteOWNER = Encoding.ASCII.GetBytes(ownerPassword); // owner password

            using (var reader = new PdfReader(srcFile))
            {
                using (var streamPDF = new FileStream(dstFile, FileMode.Create))
                {
                    PdfEncryptor.Encrypt(reader,
                                         streamPDF,
                                         byteUSER,
                                         byteOWNER,
                                         PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING,
                                         PdfWriter.STRENGTH128BITS);
                }
            }
        }
Exemplo n.º 22
0
        public static Boolean SetPwd(String inputFile, String outputFile, String pwd)
        {
            Boolean r             = false;
            string  WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string  InputFile     = inputFile.ToString();
            string  OutputFile    = outputFile.ToString();

            using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    PdfReader reader = new PdfReader(input);
                    PdfEncryptor.Encrypt(reader, output, true, pwd.ToString(), pwd.ToString(), PdfWriter.ALLOW_SCREENREADERS);
                }
            }

            return(r);
        }
Exemplo n.º 23
0
        public void Setup()
        {
            //System.IO.File.Copy(_fileNameSorgente, _fileNameDestinazione);
            _reader = new PdfReader(_fileNameSorgente);

            _stamper = new PdfStamper(_reader, new FileOutputStream(_fileNameDestinazione, true));
            if (_reader.isEncrypted())
            {
                System.Diagnostics.Debug.Print(PdfEncryptor.getPermissionsVerbose(_reader.getPermissions()));
            }
            _stamper.setEncryption(new byte[] { }, new byte[] { },
                                   PdfWriter.AllowPrinting | PdfWriter.AllowCopy | PdfWriter.AllowModifyContents | PdfWriter.AllowAssembly | PdfWriter.AllowDegradedPrinting | PdfWriter.AllowModifyAnnotations | PdfWriter.AllowFillIn | PdfWriter.AllowScreenReaders,
                                   PdfWriter.STRENGTH128BITS);


            _form   = _stamper.getAcroFields();
            _hTable = new Hashtable();
        }
Exemplo n.º 24
0
        private string[] CreateEncryptedPDF(string sourceFile, string strFileName, string password)
        {
            string outputFile = "C:\\Data\\PDFTemp\\";

            if (Directory.Exists(outputFile) == false)
            {
                Directory.CreateDirectory(outputFile);
            }

            outputFile += strFileName;

            PdfReader pReader = new PdfReader(sourceFile);
            int       pages   = pReader.NumberOfPages;

            PdfEncryptor.Encrypt(pReader, new FileStream(outputFile, FileMode.Append), PdfWriter.ENCRYPTION_AES_128, password, null, PdfWriter.AllowPrinting);
            string[] ret = new string[] { outputFile, pages.ToString() };
            return(ret);
        }
Exemplo n.º 25
0
        public string ProtectPdfStandard(string passwordUser, string passwordOwner, string namepathPDFIn, string namepathPDFOUT)
        {
            string error = string.Empty;

            if (string.IsNullOrWhiteSpace(passwordUser))
            {
                return("Error: User Password not set");
            }
            if (string.IsNullOrWhiteSpace(passwordOwner))
            {
                return("Error: Owner Password not set");
            }
            if (string.IsNullOrWhiteSpace(namepathPDFIn))
            {
                return("Error: User Password not set");
            }
            if (string.IsNullOrWhiteSpace(namepathPDFOUT))
            {
                return("Error: Owner Password not set");
            }


            try
            {
                using (Stream inputStream = new FileStream(namepathPDFIn, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (Stream outputStream = new FileStream(namepathPDFOUT, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        PdfReader reader = new PdfReader(inputStream);

                        // use bitwise AND to set / combine PDF permissioning

                        PdfEncryptor.Encrypt(reader, outputStream, true, passwordUser, passwordOwner,
                                             PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS);
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }

            return(error);
        }
Exemplo n.º 26
0
 // The bulk of the clean-up code is implemented in Dispose(bool)
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         // Free managed resources.
         // Add producer as Little's PDF Merge using TextSharp
         PdfString l = new PdfString("SuicSoft Little's PDF Merge 2.2.1 (http://www.suicsoft.com) using " + iTextSharp.text.Version.GetInstance().GetVersion);
         c.Info.Put(PdfName.PRODUCER, l);
         c.Info.Put(PdfName.CREATOR, l);
         l = null;
         // Dispose all resources that implement IDisposable
         if (c != null)
         {
             c.Close();
             c = null;
         }
         if (b != null)
         {
             b.Close();
             b = null;
         }
         if (a != null)
         {
             a.Close();
             if (Password != null)
             {
                 using (Stream output = new FileStream(d, FileMode.Create, FileAccess.Write, FileShare.None))
                 {
                     using (PdfReader reader = new PdfReader(a.GetBuffer()))
                     {
                         PdfEncryptor.Encrypt(reader, output, true, Password.ToUnsecureString(), Password.ToUnsecureString(), PdfWriter.ALLOW_SCREENREADERS);
                     }
                 }
             }
             else
             {
                 File.WriteAllBytes(d, a.GetBuffer());
             }
             a = null;
         }
     }
     // Free native resources if there are any. But Doga isn't using them
 }
Exemplo n.º 27
0
        static public string Create(string output_pdf, Dictionary <string, string> fields2value, System.Drawing.Image employee_signature, System.Drawing.Image preparer_signature, System.Drawing.Image employer_signature, string user_password, string owner_password)
        {
            PdfReader.unethicalreading = true;

            PdfReader pr;

            pr = new PdfReader(OriginPdf);
            MemoryStream ms = new MemoryStream();

            pr.RemoveUsageRights();
            pr.SelectPages("7,8");
            PdfStamper ps = new PdfStamper(pr, ms);

            //String[] values = ps.AcroFields.GetAppearanceStates("form1[0].#subform[6].Checkbox1a[0]");
            //string fs = "";
            //foreach (KeyValuePair<string, AcroFields.Item> kvp in ps.AcroFields.Fields)
            //    //fs += "\n{\"" + kvp.Key + "\", \"\"},";
            //    fs += "\n{\"\", \"" + kvp.Key + "\"},";

            foreach (KeyValuePair <string, string> kvp in fields2value)
            {
                set_field(ps.AcroFields, kvp.Key, kvp.Value);
            }
            ps.FormFlattening = true;

            var pcb = ps.GetOverContent(1);

            add_image(pcb, employee_signature, new System.Drawing.Point(140, 213));
            add_image(pcb, preparer_signature, new System.Drawing.Point(180, 120));
            pcb = ps.GetOverContent(2);
            add_image(pcb, employer_signature, new System.Drawing.Point(60, 256));
            add_image(pcb, employer_signature, new System.Drawing.Point(65, 30));
            ps.Close();
            pr.Close();

            pr = new PdfReader(new MemoryStream(ms.GetBuffer()));
            using (Stream output = new FileStream(output_pdf, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                PdfEncryptor.Encrypt(pr, output, true, user_password, owner_password, PdfWriter.ALLOW_SCREENREADERS);
            }
            pr.Close();
            return(output_pdf);
        }
Exemplo n.º 28
0
        public bool EncryptPDF(string filepath, string password)
        {
            //string filepath = path;
            string fileName = Path.GetFileNameWithoutExtension(filepath);
            string ext      = Path.GetExtension(filepath);
            string path     = Path.GetDirectoryName(filepath);
            //Console.WriteLine("Press any key to stop..." + args[0].ToString());
            // Console.ReadKey();
            string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string InputFile     = Path.Combine(filepath);
            string OutputFile    = Path.Combine(path, fileName + "_enc" + ext);

            using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    PdfReader.unethicalreading = true;
                    PdfReader reader = new PdfReader(input);



                    PdfEncryptor.Encrypt(reader, output, true, password, null, PdfWriter.ALLOW_SCREENREADERS);
                }
            }
            // byte[] USER = Encoding.ASCII.GetBytes(password);
            // byte[] OWNER = Encoding.ASCII.GetBytes("ownerpwd");
            // PdfReader reader = new PdfReader(filepath);
            // string newfile = path + fileName + "_encrpt" + ext;
            //// reader.se = true;
            // PdfStamper stamper = new PdfStamper(reader, new FileStream(newfile, FileMode.Create));
            // stamper.SetEncryption(USER, OWNER, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
            // stamper.Close();
            // reader.Close();
            // reader = null;
            if (File.Exists(filepath))
            {
                File.SetAttributes(filepath, FileAttributes.Normal);
                File.Delete(filepath);
            }

            File.Move(OutputFile, filepath);
            return(true);
        }
Exemplo n.º 29
0
        public void Set(string arquivo, string senha)
        {
            var item = arquivo;


            if (!File.Exists(item))
            {
                return;
            }

            try
            {
                EncryptionProperties encryptionProperties = new EncryptionProperties();

                var senhabyte = Encoding.ASCII.GetBytes(senha);

                encryptionProperties.SetStandardEncryption(senhabyte, senhabyte, EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_128);

                using (Stream input = new FileStream(item, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var info = new FileInfo(item);

                    var nameFile = Path.GetFileName(arquivo);

                    var pdfencrypted = info.Directory + "\\encrypted.pdf";

                    using (Stream output = new FileStream(pdfencrypted, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        iText.Kernel.Pdf.PdfReader reader = new PdfReader(input);
                        PdfEncryptor.Encrypt(reader, output, encryptionProperties);
                    }

                    //  File.Delete(item);
                    // File.Move(pdfencrypted, item);
                }
            }
            catch (iText.Kernel.PdfException e)
            {
                throw new Exception(e.Message);
            }
        }
Exemplo n.º 30
0
        private static byte[] EncryptPdf(byte[] pdfDoc)
        {
            PdfReader reader = null;

            try
            {
                reader = new PdfReader(pdfDoc);
                using (var output = new MemoryStream())
                {
                    PdfEncryptor.Encrypt(reader, output, true, userPassword, ownerPassword, permision);
                    return(output.ToArray());
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }