Ejemplo n.º 1
0
        public static bool GetPdf(string templatePath, string newFilePath, Dictionary <string, string> parameters)
        {
            bool result = true;

            try
            {
                PdfReader  pdfReader  = new PdfReader(templatePath);
                PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFilePath, FileMode.Create));


                //加密
                pdfStamper.SetEncryption(PdfWriter.STRENGTH128BITS, "", null, PdfWriter.AllowPrinting);

                //通过iTextAsian调用中文字体
                //iTextSharp.text.io.StreamUtil.AddToResourceSearch(Assembly.LoadFile(Utils.GetMapPath(Utils.GetAppSettingValue("appName")+"lib/iTextAsian.dll")));
                //iTextSharp.text.io.StreamUtil.AddToResourceSearch(Assembly.LoadFile(Utils.GetMapPath(Utils.GetAppSettingValue("appName") + "lib/iTextAsianCmaps.dll")));
                //BaseFont baseFT = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
                // BaseFont baseFT1 = BaseFont.CreateFont("MHei-Medium", "UniCNS-UCS2-H", BaseFont.EMBEDDED);


                //调用系统字体
                BaseFont baseFT = BaseFont.CreateFont(@"C:\Windows\Fonts\MSYH.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //BaseFont baseFT1 = BaseFont.CreateFont(@"C:\Windows\Fonts\msyhbd.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                BaseFont baseFT1 = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);


                //获取域的集合;
                AcroFields pdfFormFields = pdfStamper.AcroFields;

                //设置域的字体;生成文件几十K

                pdfFormFields.AddSubstitutionFont(baseFT);

                //为需要赋值的域设置值;
                foreach (KeyValuePair <string, string> parameter in parameters)
                {
                    if (parameter.Key == "titile")
                    {
                        pdfFormFields.SetFieldProperty(parameter.Key, "textfont", baseFT1, null);
                    }

                    //pdfFormFields.SetFieldProperty(parameter.Key, "textfont", baseFT, null );//生成文件过大(十几MB左右) 摒弃掉了
                    pdfFormFields.SetField(parameter.Key, parameter.Value);
                }
                //这句很重要,如果为false那么生成的PDF文件还能编辑,一定要设为true;
                pdfStamper.FormFlattening = true;
                pdfStamper.Close();
                pdfReader.Close();
            }
            catch
            {
                result = false;
                throw;
            }

            return(result);
        }
Ejemplo n.º 2
0
        public void EncryptPdfOnlyPrint(string src, string dest)
        {
            PdfReader  reader  = new PdfReader(src);
            PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));

            stamper.SetEncryption(null, null,
                                  PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_256);
            stamper.Close();
        }
Ejemplo n.º 3
0
        public void Encrypt(PdfStamper stamper)
        {
            int permission = 0;

            foreach (int i in this.Permissions)
            {
                permission |= (int)i;
            }
            stamper.SetEncryption(this.Encryption, this.UserPwd, this.OwnerPwd, permission);
        }
Ejemplo n.º 4
0
 private static void EncryptPdf(Stream input, Stream output)
 {
     using (PdfReader reader = new PdfReader(input))
         using (PdfStamper stamper = new PdfStamper(reader, output))
         {
             stamper.SetEncryption(null, Encoding.UTF8.GetBytes("vsdffvgfsdvwvw"),
                                   PdfWriter.ALLOW_PRINTING,
                                   PdfWriter.ENCRYPTION_AES_256 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
         }
 }
        //public List<Param> CreateRowParamForLink(EbDataField field, int slno)
        //{
        //    List<Param> RowParams = new List<Param>();
        //    foreach (EbControl control in LinkCollection[field.LinkRefId])
        //    {
        //        Param x = DataSet.Tables[field.TableIndex].Rows[slno].GetCellParam(control.Name);
        //        ArrayList IndexToRemove = new ArrayList();
        //        for (int i = 0; i < RowParams.Count; i++)
        //        {
        //            if (RowParams[i].Name == control.Name)
        //            {
        //                IndexToRemove.Add(i); //the parameter will be in the report alredy
        //            }
        //        }
        //        for (int i = 0; i < IndexToRemove.Count; i++)
        //        {
        //            RowParams.RemoveAt(Convert.ToInt32(IndexToRemove[i]));
        //        }
        //        RowParams.Add(x);
        //    }
        //    if (!Parameters.IsEmpty())//the parameters which are alredy present in the rendering of current report
        //    {
        //        foreach (Param p in Parameters)
        //        {
        //            RowParams.Add(p);
        //        }
        //    }
        //    return RowParams;
        //}

        //public void GetWatermarkImages()
        //{
        //    if (this.ReportObjects != null)
        //    {
        //        foreach (EbReportField field in ReportObjects)
        //        {
        //            if (field is EbWaterMark)
        //            {
        //                int id = (field as EbWaterMark).ImageRefId;
        //                if (id != 0)
        //                {
        //                    byte[] fileByte = GetImage(id);
        //                    if (!fileByte.IsEmpty())
        //                        WatermarkImages.Add(id, fileByte);
        //                }
        //            }
        //        }
        //    }
        //}

        public void SetPassword()
        {
            Ms1.Position = 0;
            PdfReader    = new PdfReader(Ms1);
            Stamp        = new PdfStamper(PdfReader, Ms1);
            byte[] USER  = Encoding.ASCII.GetBytes(UserPassword);
            byte[] OWNER = Encoding.ASCII.GetBytes(OwnerPassword);
            Stamp.SetEncryption(USER, OWNER, 0, PdfWriter.ENCRYPTION_AES_128);
            Stamp.FormFlattening = true;
            Stamp.Close();
        }
        private MemoryStream pdfDocEncrypt(string ruta, string contraseña, string encryptDocument)
        {
            MemoryStream ms = new MemoryStream();

            using (var pdfReader = new PdfReader(System.Web.Hosting.HostingEnvironment.MapPath(ruta))) {
                using (var pdfStamper = new PdfStamper(pdfReader, ms)) {
                    if (encryptDocument == "S")
                    {
                        pdfStamper.SetEncryption(Encoding.ASCII.GetBytes(contraseña), Encoding.ASCII.GetBytes("PERMICONTRATOS"), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
                    }
                    return(ms);
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Encrypt a PDF file. The destination must be different from the source
        /// </summary>
        /// <param name="sourceFilename">full path of the source file</param>
        /// <param name="destinationFilename">full path of the destination file</param>
        /// <returns>true upon success</returns>
        private bool EncryptPDFFile(string sourceFilename, string destinationFilename, IJob job)
        {
            if (Profile.PdfSettings.Security.Enable)
            {
                int encryption = callculatePermissionValue(Profile);
                logger.Trace("Callculated Permission Value: " + encryption);

                string userPassword  = null;
                string ownerPassword = null;

                ownerPassword = job.PdfPasswords.OwnerPassword;
                if (Profile.PdfSettings.Security.RequireUserPassword)
                {
                    userPassword = job.PdfPasswords.UserPassword;
                }

                PdfReader  reader     = new PdfReader(sourceFilename);
                FileStream fileStream = new FileStream(destinationFilename, FileMode.Create, FileAccess.Write);
                PdfStamper stamper    = null;

                switch (Profile.PdfSettings.Security.EncryptionLevel)
                {
                case EncryptionLevel.Low40Bit:
                    stamper = new PdfStamper(reader, fileStream, PdfWriter.VERSION_1_4);
                    stamper.SetEncryption(PdfWriter.STRENGTH40BITS, userPassword, ownerPassword, encryption);
                    break;

                case EncryptionLevel.Medium128Bit:
                    stamper = new PdfStamper(reader, fileStream, PdfWriter.VERSION_1_4);
                    stamper.SetEncryption(PdfWriter.STRENGTH128BITS, userPassword, ownerPassword, encryption);
                    break;

                case EncryptionLevel.High128BitAES:
                    stamper = new PdfStamper(reader, fileStream, PdfWriter.VERSION_1_6);
                    stamper.SetEncryption(PdfWriter.ENCRYPTION_AES_128, userPassword, ownerPassword, encryption);
                    break;

                default:
                    break;
                }
                if (stamper != null)
                {
                    stamper.Close();
                }
                reader.Close();

                return(true);
            }
            return(false);
        }
Ejemplo n.º 8
0
 public void EncryptFile(string password)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         PdfReader  reader  = new PdfReader(myPdfImage);
         PdfStamper stamper = new PdfStamper(reader, ms);
         byte[]     USER    = System.Text.Encoding.ASCII.GetBytes(password);
         byte[]     OWNER   = System.Text.Encoding.ASCII.GetBytes(password);
         stamper.SetEncryption(USER, OWNER, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
         stamper.Close();
         reader.Close();
         ms.Flush();
         protectedDocument = ms.GetBuffer();
     }
 }
Ejemplo n.º 9
0
// ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] EncryptPdf(byte[] src)
        {
            PdfReader reader = new PdfReader(src);

            using (MemoryStream ms = new MemoryStream()) {
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                    stamper.SetEncryption(
                        USER, OWNER,
                        PdfWriter.ALLOW_PRINTING,
                        PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA
                        );
                }
                return(ms.ToArray());
            }
        }
Ejemplo n.º 10
0
        public static string removePassword(string path, string password)
        {
            PdfReader.unethicalreading = true;
            var reader  = new PdfReader(path, Encoding.ASCII.GetBytes(password));
            var mem     = new MemoryStream();
            var stamper = new PdfStamper(reader, mem);

            stamper.SetEncryption(Encoding.ASCII.GetBytes(""), Encoding.ASCII.GetBytes(""), PdfWriter.AllowPrinting, PdfWriter.AllowScreenReaders | PdfWriter.AllowModifyContents);
            stamper.Close();
            reader.Close();
            var fileName = Path.GetFileName(path);

            fileName = $"{fileName}_Unlocked.pdf";
            File.WriteAllBytes(Path.Combine(Environment.CurrentDirectory, fileName), mem.ToArray());
            return(fileName);
        }
Ejemplo n.º 11
0
        public List <PayStub> GenerateIndividualStubs(string filename)
        {
            List <PayStub> stubs = new List <PayStub>();

            using (var reader = new PdfReader(filename))
            {
                for (var page = 1; page <= reader.NumberOfPages; page++)
                {
                    //extract page text
                    var strategy    = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                    var currentText = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, page, strategy);


                    var paystub = FindPayStubMatch(currentText);
                    if (paystub == null)
                    {
                        continue;
                    }

                    //write this individual page into a temp file
                    var outFileName = System.IO.Path.GetTempPath() + Guid.NewGuid() + ".pdf";

                    var pdfDoc = new Document(reader.GetPageSizeWithRotation(page));
                    var stream = new MemoryStream();
                    var pdf    = new PdfCopy(pdfDoc, stream);
                    pdf.CloseStream = false;
                    pdfDoc.Open();
                    pdf.AddPage(pdf.GetImportedPage(reader, page));
                    pdf.Close();
                    pdfDoc.Close();
                    stream.Position = 0;

                    var stamper = new PdfStamper(new PdfReader(stream), new FileStream(outFileName, FileMode.Create));
                    if ((paystub.Password + "").Length > 0)
                    {
                        stamper.SetEncryption(Encoding.ASCII.GetBytes(paystub.Password), Encoding.ASCII.GetBytes(paystub.Password), PdfWriter.ALLOW_PRINTING,
                                              PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
                    }
                    stamper.Close();
                    stream.Close();

                    paystub.Filename = outFileName;
                    stubs.Add(paystub);
                }
            }
            return(stubs);
        }
Ejemplo n.º 12
0
        public static void EncryptPdfWithCertificate(string sourceDocument, string targetDocument, string certPath)
        {
            X509Certificate chain = new X509Certificate();

            chain.Import(certPath);
            Org.BouncyCastle.X509.X509Certificate   cert  = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(chain);
            Org.BouncyCastle.X509.X509Certificate[] certs = new Org.BouncyCastle.X509.X509Certificate[1] {
                cert
            };
            PdfReader  reader = new PdfReader(sourceDocument);
            PdfStamper st     = new PdfStamper(reader, new FileStream(targetDocument, FileMode.Create, FileAccess.Write), '\0', false);

            int[] x = new int[1];
            x[0] = PdfWriter.ALLOW_SCREENREADERS;
            st.SetEncryption(certs, x, PdfWriter.STANDARD_ENCRYPTION_40);
            st.Close();
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            //MergePdf();

            //Get All Files ina  directory
            List <FileInfo> _Files = new List <FileInfo>();

            foreach (var file in new DirectoryInfo(@"D:\PDF\Input").GetFiles("*.pdf", SearchOption.AllDirectories).OrderBy(x => x.Name))
            {
                _Files.Add(file);
            }

            Parallel.ForEach(_Files, file =>
            {
                PdfReader reader = new PdfReader(file.FullName);

                //Compress images, Specify quality as second paramter - 1 to 100
                ReduceResolution(reader, 7);

                if (!Directory.Exists($@"D:\PDF\Output\{file.Directory.Name}"))
                {
                    Directory.CreateDirectory($@"D:\PDF\Output\{file.Directory.Name}");
                }

                using (PdfStamper stamper = new PdfStamper(reader, new FileStream($@"D:\PDF\Output\{file.Directory.Name}\{file.Name}", FileMode.Create), PdfWriter.VERSION_1_7))
                {
                    // flatten form fields and close document
                    stamper.FormFlattening = true;

                    stamper.SetFullCompression();

                    //IText document - http://itextsupport.com/apidocs/itext5/latest/com/itextpdf/text/pdf/PdfStamper.html
                    //strength - true for 128 bit key length, false for 40 bit key length
                    stamper.SetEncryption(true, "tk", "tk", PdfWriter.AllowPrinting);
                    stamper.Close();
                }


                reader.Close();
            });

            //MergePdf();
            _Files.Clear();
            _Files = null;
        }
Ejemplo n.º 14
0
        //加密pdf,使其不能打印,不能复制
        public void pdfreadonly(string pdfname)
        {
            string pdfFile = pdfname;// "d:\\sample.pdf";

            //把文件读入内存可立即释放文件句柄,方便信息覆盖原文件
            PdfReader reader = new PdfReader(File.ReadAllBytes(pdfFile));

            //获取到本文件的 MetaData 信息
            // Dictionary<string, string> info =reader.Info;
            //  reader.Close();

            //覆盖掉原 PDF 文件中
            PdfStamper stamper = new PdfStamper(reader, new FileStream(pdfFile, FileMode.Create, FileAccess.Write));

            stamper.MoreInfo = reader.Info;
            stamper.SetEncryption(PdfWriter.STRENGTH40BITS, null, null, PdfWriter.AllowScreenReaders);
            stamper.Close();
        }
        private byte[] encryptPdf(byte[] src)
        {
            using (var ms = new MemoryStream())
            {
                var reader = new PdfReader(src);

                var stamper = new PdfStamper(reader, ms);

                stamper.SetEncryption(
                    _userPassword, _ownerPassword,
                    PdfWriter.ALLOW_PRINTING,
                    PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA
                    );

                stamper.Close();
                reader.Close();

                return(ms.ToArray());
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// CustomizePdf - Disable Print button and add metadata
        /// </summary>
        /// <param name="pdfIn"></param>
        private void CustomizePdf(string pdfIn)
        {
            try
            {
                var fileName = new FileInfo(pdfIn).Name.MakeUnique();
                var pdfOut   = Path.Combine(Path.Combine(Path.GetTempPath(), "PdfStorage"), fileName);
                var reader   = new PdfReader(pdfIn, null);
                var xmlPath  = Path.Combine(Path.GetDirectoryName(pdfIn), Path.GetFileNameWithoutExtension(pdfIn) + ".xml");

                using (FileStream fileStream = new FileStream(pdfOut, FileMode.Create))
                {
                    var stamper = new PdfStamper(reader, fileStream);
                    stamper.SetEncryption(null, null, PdfWriter.HideWindowUI, PdfWriter.STRENGTH40BITS);

                    stamper.MoreInfo = new XmlUtils(xmlPath).XmlProps;
                    stamper.Close();
                }
                reader.Close();

                //Replace input file with output one
                File.Delete(pdfIn);
                File.Move(pdfOut, pdfIn);

                ProcessedCounter++;
                _log.Info("Disabled print button for pdf file located at: " + pdfIn);
            }
            catch (Exception exp)
            {
                if (exp.HResult == -2146232800)
                {
                    _log.Warn("Pdf file: " + pdfIn + " already processed!" + Environment.NewLine);
                }
                else
                {
                    _log.Error(exp.Message + Environment.NewLine);
                }

                ErrCounter++;
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// set PDF information and 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 SetPDFInfoAndEncrypt(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, byteOWNER))
            {
                using (var streamPDF = new FileStream(dstFile, FileMode.Create))
                {
                    using (var stamper = new PdfStamper(reader, streamPDF))
                    {
                        Dictionary <String, String> info = reader.Info;
                        info["Title"]    = "title";
                        info["Subject"]  = "subject";
                        info["Keywords"] = "keyword";
                        info["Creator"]  = "creator";
                        info["Author"]   = "author";
                        stamper.SetEncryption(byteUSER, byteOWNER, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                        stamper.MoreInfo = info;
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public static void RunPasswordProtectTest()
        {
            Console.WriteLine("Enter a password to use for the test (password strength not important so it can be anything");
            Console.WriteLine();

            var password = Console.ReadLine();

            Console.WriteLine();

            if (!IsPasswordValid(password))
            {
                Console.WriteLine("You must enter SOMETHING for the password...");
                Console.WriteLine();

                password = Console.ReadLine();
                Console.WriteLine();

                if (!IsPasswordValid(password))
                {
                    Console.WriteLine("Ok, one more try... this time I'll quit if you don't enter a password!");
                    Console.WriteLine();

                    password = Console.ReadLine();
                    Console.WriteLine();

                    if (!IsPasswordValid(password))
                    {
                        Console.WriteLine("forget it!");
                        return;
                    }
                }
            }

            Console.WriteLine("Now enter the location of a PDF file to encrypt (don't worry, this will create a copy and not overwrite the original)");
            Console.WriteLine();

            var filePath = Console.ReadLine();

            Console.WriteLine();

            if (!IsFilePathValid(filePath))
            {
                Console.WriteLine("The file path entered is not valid or the file doesn't exist, please try again...");
                Console.WriteLine();

                filePath = Console.ReadLine();
                Console.WriteLine();

                if (!IsFilePathValid(filePath))
                {
                    Console.WriteLine("The file path is STILL not valid, one more go or I'm taking my ball home...");
                    Console.WriteLine();

                    filePath = Console.ReadLine();
                    Console.WriteLine();

                    if (!IsFilePathValid(filePath))
                    {
                        Console.WriteLine("forget it, I'm off!");
                        return;
                    }
                }
            }

            Console.WriteLine(string.Format("You chose: {0}; {1}", password, filePath));
            Console.ReadKey();

            Console.WriteLine("Creating a password protected copy...");
            Console.WriteLine();

            var protectedFileName = filePath.Replace(".pdf", "-protected.pdf");

            byte[] userPwd  = Encoding.ASCII.GetBytes(password);
            byte[] ownerPwd = Encoding.ASCII.GetBytes(password);

            PdfReader reader = new PdfReader(filePath);

            PdfStamper stamper = new PdfStamper(reader, new FileStream(protectedFileName, FileMode.Create));

            stamper.SetEncryption(userPwd, ownerPwd, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
            stamper.Close();

            Console.WriteLine(string.Format("All done, you should now have a protected file called {0}", protectedFileName));
            Console.WriteLine();

            Console.WriteLine("Press 1 to open the folder, or press any other key to exit");

            var pressedKey = Console.ReadKey();

            switch (pressedKey.KeyChar.ToString())
            {
            case ("1"):
                OpenDirectory(protectedFileName);
                break;

            default:
                break;
            }
        }
        public string GenerateEndorsement(EndorsementDto endorsement)
        {
            if (endorsement == null)
            {
                return(null);
            }

            _logger.LogTrace("GenerateEndorsement invoked. ");

            var templatePath = GetResource(endorsement.TemplatePdfUrl, EndorsementConstant.S_TEMPLATE_PDF_PATH);

            _logger.LogTrace("GetResource done. TemplatePath: " + templatePath);

            if (!File.Exists(templatePath))
            {
                _logger.LogTrace("Endorsement file does not exist at path: " + templatePath);
                throw new Exception("Template pdf file not exists! :: Path: " + templatePath + " :: templatePdfUrl: " + endorsement.TemplatePdfUrl);
            }

            if (_fileService.IsValidPdf(templatePath) == false)
            {
                _logger.LogTrace("IsValidPdf is false :: TemplatePath: " + templatePath);
                throw new Exception("Template pdf file is invalid! :: Path: " + templatePath + " :: templatePdfUrl: " + endorsement.TemplatePdfUrl);
            }

            var filename          = string.Empty;
            var folderEndorsement = string.Empty;
            var endorsementPath   = string.Empty;

            _logger.LogTrace("Endorsement is set to parseemptytext: " + endorsement.ParseEmptyText);

            if (endorsement.ParseEmptyText)
            {
                filename = string.Format(CertificateConstant.S_DOCUMENT_FILENAME_EMPTY_FORMAT, EndorsementConstant.S_DOCUMENT_FILENAME_EMPTY, endorsement.EndorsementCode);

                _logger.LogTrace("Empty Endorsement filename: " + filename);

                folderEndorsement = HttpContext.Current.Server.MapPath(EndorsementConstant.S_OUTPUT_PATH_EMPTY);

                _logger.LogTrace("Empty Endorsement folder: " + folderEndorsement);

                endorsementPath = folderEndorsement + filename;

                _logger.LogTrace("Empty Endorsement path: " + endorsementPath);

                //Cleanup once a week.
                CleanUpFile(folderEndorsement, TimeSpan.FromDays(7));

                if (File.Exists(endorsementPath))
                {
                    _logger.LogTrace("Empty Endorsement exists already. Return path. " + endorsementPath);
                    return(endorsementPath);
                }
            }
            else
            {
                filename = _fileService.GetFileName("endorsement", endorsement.ApplicationId, endorsement.ProductId);

                _logger.LogTrace("Endorsement file: " + filename);

                folderEndorsement = HttpContext.Current.Server.MapPath(EndorsementConstant.S_OUTPUT_PATH);

                _logger.LogTrace("Endorsement folder: " + folderEndorsement);

                CleanUpFile(folderEndorsement, TimeSpan.FromDays(1));
                endorsementPath = folderEndorsement + filename;

                _logger.LogTrace("Endorsement path: " + endorsementPath);
            }

            if (File.Exists(endorsementPath))
            {
                File.Delete(endorsementPath);
                _logger.LogTrace("Endorsement exists already. Delete file. " + endorsementPath);
            }

            var reader  = new PdfReader(templatePath);
            var stamper = new PdfStamper(reader, new FileStream(endorsementPath, FileMode.Create));

            try
            {
                _logger.LogTrace("Parse actual pdf document start. ");
                stamper.SetEncryption(PdfWriter.STRENGTH128BITS, string.Empty, endorsement.PdfPassword, PdfWriter.AllowPrinting | PdfWriter.AllowCopy | PdfWriter.AllowScreenReaders);
                var pdfFormFields   = stamper.AcroFields;
                var imageExtensions = new string[] { EndorsementConstant.S_IMAGE_FILE_EXTENSION_PNG, EndorsementConstant.S_IMAGE_FILE_EXTENSION_JPG };

                if (endorsement.VariableValues != null)
                {
                    foreach (var variableValue in endorsement.VariableValues)
                    {
                        if (imageExtensions.Contains(Path.GetExtension(variableValue.Value)))
                        {
                            var signatureFile = GetResource(variableValue.Value, EndorsementConstant.S_SIGNATURE_IMAGE_PATH);

                            if (!string.IsNullOrWhiteSpace(signatureFile))
                            {
                                stamper.SetImage(variableValue.Key, signatureFile);
                            }
                        }
                        else
                        {
                            pdfFormFields.SetField(variableValue.Key, variableValue.Value);
                        }
                    }
                }

                _logger.LogTrace("Parse actual pdf document done.");

                return(endorsementPath);
            }
            catch (Exception exception)
            {
                _logger.LogException(exception);
                throw;
            }
            finally
            {
                // flatten form fields and close document
                stamper.FormFlattening = true;
                stamper.Close();
                stamper.Dispose();
                reader.Close();
                reader.Dispose();
            }
        }
Ejemplo n.º 20
0
        public static void FillInPdfTemplateFields(string templatPath, Stream pdfOut, Dictionary <string, string> hashTable, byte[] qrCode, bool isEncrypt)
        {
            PdfReader  pdfReader  = new PdfReader(templatPath);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, pdfOut);

            try
            {
                if (isEncrypt)
                {
                    pdfStamper.SetEncryption(PdfWriter.STRENGTH40BITS, null, null, PdfWriter.AllowPrinting);
                }

                StreamUtil.AddToResourceSearch(Assembly.Load("iTextAsian"));
                BaseFont font = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

                AcroFields pdfFormFields = pdfStamper.AcroFields;
                foreach (KeyValuePair <string, AcroFields.Item> de in pdfFormFields.Fields)
                {
                    string fieldKey = de.Key.ToString();
                    if (string.IsNullOrWhiteSpace(fieldKey))
                    {
                        continue;
                    }

                    if (fieldKey.Contains("img_"))
                    {
                        int    page   = Convert.ToInt32(fieldKey.Split('_')[1]);
                        string hasKey = fieldKey.Split('_')[2];
                        //if (hashTable.ContainsKey(hasKey))
                        //{
                        IList <AcroFields.FieldPosition> fieldPositions = pdfFormFields.GetFieldPositions(fieldKey);
                        AcroFields.FieldPosition         fieldPosition  = fieldPositions[0];
                        iTextSharp.text.Image            image          = iTextSharp.text.Image.GetInstance(qrCode);
                        image.ScaleToFit(fieldPosition.position.Width, fieldPosition.position.Height);
                        float x = fieldPosition.position.Left;
                        float y = fieldPosition.position.Top - image.ScaledHeight;
                        image.SetAbsolutePosition(x, y);
                        var pdfContentByte = pdfStamper.GetOverContent(page);
                        pdfContentByte.AddImage(image);
                        //}
                    }
                    else if (hashTable.ContainsKey(fieldKey))
                    {
                        pdfFormFields.SetFieldProperty(fieldKey, "textfont", font, null);
                        string fieldValue = hashTable[fieldKey];
                        if (string.IsNullOrWhiteSpace(fieldValue))
                        {
                            fieldValue = string.Empty;
                        }
                        pdfFormFields.SetField(fieldKey, fieldValue);
                    }
                }

                pdfStamper.FormFlattening = true;
            }
            catch (Exception)
            {
            }
            finally
            {
                pdfStamper.Close();
                pdfReader.Close();
            }
        }
Ejemplo n.º 21
0
        public void SetWatermarkByWord(string inputfilepath, string outputfilepath, string waterMarkName, string userPassWord, string ownerPassWord, int permission, bool HasCover = false)
        {
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

            try
            {
                pdfReader  = new PdfReader(inputfilepath);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                // 设置密码
                pdfStamper.SetEncryption(false, userPassWord, ownerPassWord, permission);

                int total = pdfReader.NumberOfPages + 1;
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
                float          width            = psize.Width;
                float          height           = psize.Height;
                PdfContentByte content;
                BaseFont       font = BaseFont;
                PdfGState      gs   = new PdfGState();

                for (int i = 1; i < total; i++)
                {
                    if (HasCover && i == 1)
                    {
                        continue;
                    }

                    content = pdfStamper.GetOverContent(i);
                    var len = Encoding.UTF8.GetByteCount(waterMarkName);
                    gs.FillOpacity = 0.3f;
                    content.SetGState(gs);
                    //content.SetGrayFill(0.3f);

                    content.BeginText();
                    content.SetColorFill(BaseColor.LIGHT_GRAY);
                    var fontSize = 50;
                    if (len > 40 && len <= 60)
                    {
                        fontSize = 35;
                    }
                    else
                    {
                        fontSize = 30;
                    }
                    content.SetFontAndSize(font, fontSize);
                    content.SetTextMatrix(0, 0);
                    content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2, height / 2 + (len), 55);
                    //content.SetColorFill(BaseColor.BLACK);
                    //content.SetFontAndSize(font, 8);
                    //content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, 0, 0, 0);
                    content.EndText();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
        }
        public ActionResult getFileData(string Token)
        {
            using (var db = new Db_Entities()) {
                FileCode FileCode = new FileCode()
                {
                    Token = Token
                };
                FileCode.Decode();
                int    id_doc = Int32.Parse(FileCode.values["id_doc"]);
                string type   = FileCode.values["type"];
                string fecha  = FileCode.values["fecha"];
                int    id_usu = 0;// SesionLogin().id;
                Int32.TryParse(FileCode.values["id_usu"], out id_usu);
                string encryptDocument = "S";
                FileCode.values.TryGetValue("encryptDocument", out encryptDocument);
                MemoryStream ms = new MemoryStream();
                PdfReader    pdfReader;
                PdfStamper   pdfStamper;
                AcroFields   pdfFormFields;
                Usuario      usuario = id_usu == 0 ? SesionLogin() : db.Usuario.FirstOrDefault(p => p.id == id_usu);
                Cliente      cliente = id_usu == 0 ? SesionCliente() : db.Cliente.FirstOrDefault(p => p.id_cliente == usuario.id_cliente);

                try
                {
                    if (type == TIPO_LIQUIDACION)
                    {
                        var fecha_set = new string((from c in fecha where char.IsLetterOrDigit(c) select c).ToArray());
                        var fec_sp    = DateTime.ParseExact(fecha_set, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
                        pdfReader     = new PdfReader(System.Web.Hosting.HostingEnvironment.MapPath(db.Documento.FirstOrDefault(p => p.categoria == "DOCUMLIQUI" && p.estado == 1 && p.id_cliente == usuario.id_cliente).ruta));
                        pdfStamper    = new PdfStamper(pdfReader, ms);
                        pdfFormFields = pdfStamper.AcroFields;
                        var periodo = PeriodoVigente(new List <SqlParameter>()
                        {
                            new SqlParameter("@Fecha", SqlDbType.Date)
                            {
                                Value = fecha
                            },
                            new SqlParameter("@NOM_CLIENTE_DB", SqlDbType.VarChar)
                            {
                                Value = cliente.Nom_cor_emp
                            },
                            new SqlParameter("@VALOR_RET", SqlDbType.Int)
                            {
                                Value = 0
                            }
                        });
                        var datos_liquidacion = MultiLoadDataToDictionary(new List <SqlParameter>()
                        {
                            new SqlParameter("@USU_ID", SqlDbType.VarChar)
                            {
                                Value = usuario.id_usu
                            },
                            new SqlParameter("@NOM_CLIENTE_DB", SqlDbType.VarChar)
                            {
                                Value = cliente.Nom_cor_emp
                            },
                            new SqlParameter("@Mes_consul", SqlDbType.VarChar)
                            {
                                Value = periodo
                            },
                            new SqlParameter("@Fecha", SqlDbType.VarChar)
                            {
                                Value = fec_sp
                            },
                        }, "pa_selDatosLiquidacion");
                        var ficha = usuario.id_usu;
                        if (encryptDocument == "S")
                        {
                            pdfStamper.SetEncryption(Encoding.ASCII.GetBytes(ficha), Encoding.ASCII.GetBytes("PERMICONTRATOS"), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
                        }
                        var campo = LoadData("select tag, campo,label,id_cliente, orden  from configPDF where (id_cliente = -1 or id_cliente =" + cliente.id_cliente + ") order by tag, orden asc").ToList();
                        Fill_pdf(datos_liquidacion, campo, pdfFormFields, fecha); // funcion para llenado de pdf

                        //Estampar imagen de cliente dinamicamente
                        if (SesionLogin().id_cliente != 1)
                        {
                            var estampoImg = pdfStamper.GetOverContent(1);
                            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(System.Web.Hosting.HostingEnvironment.MapPath(db.Documento.FirstOrDefault(p => p.categoria == "DOCUMLOGOCLI" && p.estado == 1 && p.id_cliente == usuario.id_cliente).ruta));
                            image.SetAbsolutePosition(25, 730);
                            float percentage = 0.0f;
                            percentage = 100 / image.Width;
                            image.ScalePercent(percentage * 120);
                            estampoImg.AddImage(image);
                        }


                        pdfStamper.FormFlattening = false;
                        pdfStamper.MoreInfo       = new Dictionary <string, string>()
                        {
                            { "Title", "Liquidación_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf" }
                        };
                        pdfStamper.Close();
                        pdfReader.Close();
                        Response.AppendHeader("Content-Disposition", "inline; filename=Liquidación_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf");
                        return(File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf));
                    }
                    else if (type == TIPO_CERTIFICADO_ANTIGUEDAD)
                    {
                        pdfReader     = new PdfReader(System.Web.Hosting.HostingEnvironment.MapPath(db.Documento.FirstOrDefault(p => p.categoria == "DOCUMCERTANT" && p.estado == 1 && p.id_cliente == usuario.id_cliente).ruta));
                        pdfStamper    = new PdfStamper(pdfReader, ms);
                        pdfFormFields = pdfStamper.AcroFields;
                        var datosCertAntiguedad = LoadData("EXEC  [dbo].[pa_selDatosCertAntiguedad] @USU_ID = N'" + usuario.id_usu + "',@NOM_CLIENTE_DB = N'" + cliente.Nom_cor_emp + "' ");
                        var Texto_Super         = helper.Get_TextCertificado("C_ANTIGUEDAD", datosCertAntiguedad, usuario);
                        var fec_actu            = DateTime.Now.ToString("dd MMMM yyyy");
                        var pie_qr = "CERTIFICADO EMITIDO POR PAYROLL MANAGEMENT SYSTEM\nLa institución o persona ante quien se presente este certificado\npodrá validar su autenticidad mediante el escaneo del codigo QR.";
                        fec_actu = "En Santiago, " + fec_actu;
                        pdfFormFields.SetField("Texto_Super", Texto_Super);
                        pdfFormFields.SetField("fec_actu", fec_actu);
                        pdfFormFields.SetField("pie_qr", pie_qr);
                        var pdfContentByte2         = pdfStamper.GetOverContent(1);
                        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(System.Web.Hosting.HostingEnvironment.MapPath(db.Documento.FirstOrDefault(p => p.categoria == "DOCUMLOGOCLI" && p.estado == 1 && p.id_cliente == usuario.id_cliente).ruta));
                        image.SetAbsolutePosition(20, 730);
                        float percentage = 0.0f;
                        percentage = 100 / image.Width;
                        image.ScalePercent(percentage * 150);
                        pdfContentByte2.AddImage(image);
                        if (id_usu == 0)
                        {
                            var       fechaQR    = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                            var       mod11      = Helper.digitoVerificador(Int64.Parse(fechaQR));
                            var       cadena     = fechaQR + "_" + "o" + "_" + mod11 + "_" + usuario.id_usu + "_" + cliente.Nom_cor_emp;
                            var       encriptado = SeguridadUtilidades.Encriptar(cadena);
                            string    url        = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port);
                            var       QRfinal    = url + "/" + "ValidaDocumento" + "/" + "validaQR" + "?" + "token=" + HttpUtility.UrlEncode(encriptado);
                            QrEncoder qrEncoder  = new QrEncoder(ErrorCorrectionLevel.M);
                            QrCode    qrcode     = new QrCode();
                            qrEncoder.TryEncode(QRfinal, out qrcode);
                            GraphicsRenderer Renderder = new GraphicsRenderer(new FixedCodeSize(50, QuietZoneModules.Zero), Brushes.Black, Brushes.White);
                            MemoryStream     MS        = new MemoryStream();
                            Renderder.WriteToStream(qrcode.Matrix, ImageFormat.Jpeg, MS);
                            var imagentemporal       = new Bitmap(MS);
                            var pdfContentByte       = pdfStamper.GetOverContent(1);
                            iTextSharp.text.Image QR = iTextSharp.text.Image.GetInstance(imagentemporal, ImageFormat.Jpeg);
                            QR.SetAbsolutePosition(500, 40);
                            pdfContentByte.AddImage(QR);
                        }
                        pdfStamper.FormFlattening = false;
                        pdfStamper.MoreInfo       = new Dictionary <string, string>()
                        {
                            { "Title", "Certificado_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf" }
                        };
                        pdfStamper.Close();
                        pdfReader.Close();
                        Response.AppendHeader("Content-Disposition", "inline; filename=" + "Certificado_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf");
                        return(File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf));
                    }
                    if (type == TIPO_OTROS)
                    {
                        var documento = db.Documento.FirstOrDefault(p => p.id_doc == id_doc);
                        Response.AppendHeader("Content-Disposition", "inline; filename=" + documento.nombre_original);
                        using (FileStream file = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(documento.ruta), FileMode.Open, FileAccess.Read))
                        {
                            byte[] bytes = new byte[file.Length];
                            file.Read(bytes, 0, (int)file.Length);
                            ms.Write(bytes, 0, (int)file.Length);
                        }
                        return(File(ms.ToArray(), MimeMapping.GetMimeMapping(System.Web.Hosting.HostingEnvironment.MapPath(documento.ruta))));
                    }
                    if (type == TIPO_CONTRATO_ANEXO || type == TIPO_CONTRATO || type == TIPO_CONTRATO_OFERTA)
                    {
                        var doc        = db.Documento.FirstOrDefault(p => p.id_doc == id_doc && p.categoria == type);
                        var contraseña = db.Usuario.FirstOrDefault(p => p.id == doc.id_usu).id_usu;
                        Response.AppendHeader("Content-Disposition", "inline; filename=" + doc.nombre_original);
                        return(File(pdfDocEncrypt(doc.ruta, contraseña, encryptDocument).ToArray(), MimeMapping.GetMimeMapping(System.Web.Hosting.HostingEnvironment.MapPath(doc.ruta))));
                    }
                    else
                    {
                        return(null);
                    }
                }
                catch (Exception e)
                {
                    return(JsonError("Ocurrió un problema con su solicitud, por favor contacte a IT", e));
                }
            }
        }
        public string GenerateCertificate(Certificate certificate)
        {
            if (certificate == null)
            {
                return(null);
            }

            var templatePath = GetResource(certificate.TemplatePdfUrl, CertificateConstant.S_TEMPLATE_PDF_PATH);

            if (!File.Exists(templatePath))
            {
                throw new Exception("Template pdf file not exists! :: Path: " + templatePath + " :: templatePdfUrl: " + certificate.TemplatePdfUrl);
            }

            var filename          = _fileService.GetFileName("certificate", certificate.ApplicationId, certificate.ProductId);
            var folderCertificate = HttpContext.Current.Server.MapPath(CertificateConstant.S_OUTPUT_PATH);
            var certificatePath   = folderCertificate + filename;

            CleanUpFile(folderCertificate, TimeSpan.FromDays(1));

            var reader  = new PdfReader(templatePath);
            var stamper = new PdfStamper(reader, new FileStream(certificatePath, FileMode.Create));

            stamper.SetEncryption(PdfWriter.STRENGTH128BITS, string.Empty, certificate.PdfPassword, PdfWriter.AllowPrinting | PdfWriter.AllowCopy | PdfWriter.AllowScreenReaders);
            var pdfFormFields = stamper.AcroFields;

            pdfFormFields.SetField(CertificateFieldsConstant.S_DATE, certificate.Date);

            //producer
            pdfFormFields.SetField(CertificateFieldsConstant.S_PRODUCER, certificate.Producer.FullFormat);
            pdfFormFields.SetField(CertificateFieldsConstant.S_CONTACT_NAME, certificate.Contact.Name);
            pdfFormFields.SetField(CertificateFieldsConstant.S_CONTACT_PHONE, certificate.Contact.Phone);
            pdfFormFields.SetField(CertificateFieldsConstant.S_CONTACT_FAX, certificate.Contact.Fax);
            pdfFormFields.SetField(CertificateFieldsConstant.S_CONTACT_EMAIL, certificate.Contact.Email);

            //insured
            pdfFormFields.SetField(CertificateFieldsConstant.S_INSURED_NAME, certificate.Insured.Name);
            pdfFormFields.SetField(CertificateFieldsConstant.S_INSURED_ADDRESS, certificate.Insured.AddressFormat);

            //insurer
            var insurerNumber = 1;

            foreach (var insurer in certificate.Insurers.OrderBy(o => o.Letter))
            {
                pdfFormFields.SetField(CertificateFieldsConstant.S_INSURER_NAME + insurerNumber, insurer.Name);
                pdfFormFields.SetField(CertificateFieldsConstant.S_INSURER_NAIC + insurerNumber, insurer.Naic);
                insurerNumber += 1;
            }

            var policyGL = certificate.PolicySectionGl;

            if (policyGL != null)
            {
                //General Liability
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_INSURER_LETTER, policyGL.InsurerLetter);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_COMMERCIAL, policyGL.TakeCommercial);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_CLAIMS_MADE, policyGL.TakeClaimsMade);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_OCCURRENCE, policyGL.TakeOccur);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_OTHER_LIABILITY1, string.IsNullOrEmpty(policyGL.OtherLiability1) == false);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_OTHER_LIABILITY1_TEXT, policyGL.OtherLiability1);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_OTHER_LIABILITY2, string.IsNullOrEmpty(policyGL.OtherLiability2) == false);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_OTHER_LIABILITY2_TEXT, policyGL.OtherLiability2);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_AGGREGATE_POLICY, policyGL.TakeAggregatePolicy);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_AGGREGATE_PROJECT, policyGL.TakeAggregateProject);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_AGGREGATE_LOCATION, policyGL.TakeAggregateLoc);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_POLICY_NUMBER, policyGL.Number);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_EFFECTIVE_DATE, policyGL.EffectiveDate);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_EXPIRY_DATE, policyGL.ExpiryDate);

                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_OCCURRENCE, policyGL.LimitOccurance);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_DAMAGE, policyGL.LimitDamage);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_MEDICAL_EXPENSE, policyGL.LimitMedical);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_PERSONAL_INJURY, policyGL.LimitPersonal);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_AGGREGATE, policyGL.LimitAggregate);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_PRODUCTS, policyGL.LimitProducts);

                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_OTHER_TEXT, policyGL.LimitOtherText);
                if (string.IsNullOrEmpty(policyGL.LimitOtherText) == false)
                {
                    pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_LIMIT_OTHER_VALUE, policyGL.LimitOtherValue);
                }

                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_ADDITIONAL_INSURED, policyGL.IsAdditionalInsured);
                pdfFormFields.SetField(CertificateFieldsConstant.S_GENERAL_LIABILITY_SUBROGATION_WAIVER, policyGL.IsAdditionalInsured);
            }


            var policyAutomobile = certificate.PolicyAutomobile;

            if (policyAutomobile != null)
            {
                //Automobile
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_INSURER_LETTER, policyAutomobile.InsurerLetter);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_ANY_AUTO, policyAutomobile.TakeAnyAuto);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_ALL_OWNED_AUTOS, policyAutomobile.TakeAllOwnedAutos);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_SCHEDULED_OWNED_AUTOS, policyAutomobile.TakeScheduledOwnedAutos);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_HIRED_OWNED_AUTOS, policyAutomobile.TakeHiredOwnedAutos);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_NON_OWNED_AUTOS, policyAutomobile.TakeNonOwnedAutos);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_OTHER1, string.IsNullOrEmpty(policyAutomobile.Other1) == false);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_OTHER1_TEXT, policyAutomobile.Other1);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_OTHER2, string.IsNullOrEmpty(policyAutomobile.Other2) == false);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_OTHER2_TEXT, policyAutomobile.Other2);

                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_POLICY_NUMBER, policyAutomobile.Number);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_EFFECTIVE_DATE, policyAutomobile.EffectiveDate);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_EXPIRY_DATE, policyAutomobile.ExpiryDate);

                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_COMBINED, policyAutomobile.LimitCombined);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_INJURY_PERSON, policyAutomobile.LimitInjuryPerson);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_INJURY_ACCIDENT, policyAutomobile.LimitInjuryAccident);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_PROPERTY_DAMAGE, policyAutomobile.LimitPropertyDamage);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_OTHER_TEXT, policyAutomobile.LimitOtherText);
                if (string.IsNullOrEmpty(policyAutomobile.LimitOtherText) == false)
                {
                    pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_LIMIT_OTHER, policyAutomobile.LimitOtherValue);
                }

                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_ADDITIONAL_INSURED, policyAutomobile.IsAdditionalInsured);
                pdfFormFields.SetField(CertificateFieldsConstant.S_AUTOMOBILE_SUBROGATION_WAIVER, policyAutomobile.IsAdditionalInsured);
            }


            var policyUmbrella = certificate.PolicyUmbrella;

            if (policyUmbrella != null)
            {
                //Umbrella
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_INSURER_LETTER, policyUmbrella.InsurerLetter);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIABILITY, policyUmbrella.TakeLiability);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_OCCURRENCE, policyUmbrella.TakeOccur);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_EXCESS, policyUmbrella.TakeExcess);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_CLAIMS_MADE, policyUmbrella.TakeClaimsMade);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_DED, policyUmbrella.TakeDed);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_RETENTION, policyUmbrella.TakeRetention);
                if (policyUmbrella.TakeRetention)
                {
                    pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIMIT_RETENTION, policyUmbrella.LimitiRetention);
                }

                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_POLICY_NUMBER, policyUmbrella.Number);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_EFFECTIVE_DATE, policyUmbrella.EffectiveDate);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_EXPIRY_DATE, policyUmbrella.ExpiryDate);

                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIMIT_OCCURRENCE, policyUmbrella.LimitOccurrence);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIMIT_AGGREGATE, policyUmbrella.LimitAggregate);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIMIT_OTHER_TEXT, policyUmbrella.LimitOtherText);
                if (string.IsNullOrEmpty(policyUmbrella.LimitOtherText) == false)
                {
                    pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_LIMIT_OTHER, policyUmbrella.LimitOtherValue);
                }

                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_ADDITIONAL_INSURED, policyUmbrella.IsAdditionalInsured);
                pdfFormFields.SetField(CertificateFieldsConstant.S_UMBRELLA_SUBROGATION_WAIVER, policyUmbrella.IsAdditionalInsured);
            }


            var policyWorker = certificate.PolicyWorker;

            if (policyWorker != null)
            {
                //Workers Compensation and Employers's Liability
                pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_INSURER_LETTER, policyWorker.InsurerLetter);
                pdfFormFields.SetFieldYesNo(CertificateFieldsConstant.S_WORKER_EXCLUDED_PARTNER, policyWorker.TakeAnyExcludedPartner);

                pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_POLICY_NUMBER, policyWorker.Number);
                pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_EFEECTIVATE_DATE, policyWorker.EffectiveDate);
                pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_EXPIRY_DATE, policyWorker.ExpiryDate);

                pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_STATUTORY, policyWorker.TakeLimitStatutory);
                pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_OTHER, policyWorker.TakeLimitOther);

                pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_LIMIT_ACCIDENT, policyWorker.LimitAccident);
                pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_LIMIT_EMPLOYEE, policyWorker.LimitEmployee);
                pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_LIMIT_POLICY, policyWorker.LimitPolicy);
                pdfFormFields.SetField(CertificateFieldsConstant.S_WORKER_SUBROGATION_WAIVER, policyWorker.IsAdditionalInsured);
            }


            var policyOther = certificate.PolicyOther;

            if (policyOther != null)
            {
                //Other
                pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_INSURER_LETTER, policyOther.InsurerLetter);
                pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_TYPE, policyOther.InsuranceName);
                pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_POLICY_NUMBER, policyOther.Number);

                pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_EFFECITVE_DATE, policyOther.EffectiveDate);
                pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_EXPIRY_DATE, policyOther.ExpiryDate);

                pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_LIMITS, policyOther.LimitFormat);

                pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_ADDITIONAL_INSURED, policyOther.IsAdditionalInsured);
                pdfFormFields.SetField(CertificateFieldsConstant.S_OTHER_SUBROGATION_WAIVER, policyOther.IsAdditionalInsured);
            }


            pdfFormFields.SetField(CertificateFieldsConstant.S_DESCRIPTION, certificate.Description);

            for (var i = 0; i < certificate.DescriptionColumn.Count(); i++)
            {
                CustomCoverage customCoverage = certificate.DescriptionColumn.ElementAt(i);
                pdfFormFields.SetField(CertificateFieldsConstant.S_DESCRIPTIONCOLUMN + (i + 1), customCoverage.FullFormat);
            }

            pdfFormFields.SetField(CertificateFieldsConstant.S_HOLDER, certificate.Holder.FullFormat);

            //add signature image

            var signatureFile = GetResource(certificate.SignatureImageUrl, CertificateConstant.S_SIGNATURE_IMAGE_PATH);

            stamper.SetImage(CertificateFieldsConstant.S_SIGNATURE, signatureFile);

            // flatten form fields and close document
            stamper.FormFlattening = true;
            stamper.Close();
            stamper.Dispose();
            reader.Close();
            reader.Dispose();

            return(certificatePath);
        }