Пример #1
0
// ---------------------------------------------------------------------------
        public byte[] FillTemplate(byte[] pdf, Movie movie)
        {
            using (MemoryStream ms = new MemoryStream()) {
                PdfReader reader = new PdfReader(pdf);
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                    AcroFields form  = stamper.AcroFields;
                    BaseColor  color = WebColors.GetRGBColor(
                        "#" + movie.entry.category.color
                        );
                    PushbuttonField bt = form.GetNewPushbuttonFromField(POSTER);
                    bt.Layout           = PushbuttonField.LAYOUT_ICON_ONLY;
                    bt.ProportionalIcon = true;
                    bt.Image            = Image.GetInstance(Path.Combine(IMAGE, movie.Imdb + ".jpg"));
                    bt.BackgroundColor  = color;
                    form.ReplacePushbuttonField(POSTER, bt.Field);

                    PdfContentByte           canvas = stamper.GetOverContent(1);
                    float                    size   = 12;
                    AcroFields.FieldPosition f      = form.GetFieldPositions(TEXT)[0];
                    while (AddParagraph(CreateMovieParagraph(movie, size),
                                        canvas, f, true) && size > 6)
                    {
                        size -= 0.2f;
                    }
                    AddParagraph(CreateMovieParagraph(movie, size), canvas, f, false);

                    form.SetField(YEAR, movie.Year.ToString());
                    form.SetFieldProperty(YEAR, "bgcolor", color, null);
                    form.SetField(YEAR, movie.Year.ToString());
                    stamper.FormFlattening = true;
                }
                return(ms.ToArray());
            }
        }
Пример #2
0
        public SignaturePermissions InspectSignature(AcroFields fields, String name, SignaturePermissions perms)
        {
            IList <AcroFields.FieldPosition> fps = fields.GetFieldPositions(name);

            if (fps != null && fps.Count > 0)
            {
                AcroFields.FieldPosition fp = fps[0];
                Rectangle pos = fp.position;
                if (pos.Width == 0 || pos.Height == 0)
                {
                    Console.WriteLine("Invisible signature");
                }
                else
                {
                    Console.WriteLine("Field on page {0}; llx: {1}, lly: {2}, urx: {3}; ury: {4}",
                                      fp.page, pos.Left, pos.Bottom, pos.Right, pos.Top);
                }
            }

            PdfPKCS7 pkcs7 = VerifySignature(fields, name);

            Console.WriteLine("Digest algorithm: " + pkcs7.GetHashAlgorithm());
            Console.WriteLine("Encryption algorithm: " + pkcs7.GetEncryptionAlgorithm());
            Console.WriteLine("Filter subtype: " + pkcs7.GetFilterSubtype());
            X509Certificate cert = pkcs7.SigningCertificate;

            Console.WriteLine("Name of the signer: " + CertificateInfo.GetSubjectFields(cert).GetField("CN"));
            if (pkcs7.SignName != null)
            {
                Console.WriteLine("Alternative name of the signer: " + pkcs7.SignName);
            }

            Console.WriteLine("Signed on: " + pkcs7.SignDate.ToString("yyyy-MM-dd HH:mm:ss.ff"));
            if (!pkcs7.TimeStampDate.Equals(DateTime.MaxValue))
            {
                Console.WriteLine("TimeStamp: " + pkcs7.TimeStampDate.ToString("yyyy-MM-dd HH:mm:ss.ff"));
                TimeStampToken ts = pkcs7.TimeStampToken;
                Console.WriteLine("TimeStamp service: " + ts.TimeStampInfo.Tsa);
                Console.WriteLine("Timestamp verified? " + pkcs7.VerifyTimestampImprint());
            }
            Console.WriteLine("Location: " + pkcs7.Location);
            Console.WriteLine("Reason: " + pkcs7.Reason);
            PdfDictionary sigDict = fields.GetSignatureDictionary(name);
            PdfString     contact = sigDict.GetAsString(PdfName.CONTACTINFO);

            if (contact != null)
            {
                Console.WriteLine("Contact info: " + contact);
            }
            perms = new SignaturePermissions(sigDict, perms);
            Console.WriteLine("Signature type: " + (perms.Certification ? "certification" : "approval"));
            Console.WriteLine("Filling out fields allowed: " + perms.FillInAllowed);
            Console.WriteLine("Adding annotations allowed: " + perms.AnnotationsAllowed);
            foreach (SignaturePermissions.FieldLock Lock in perms.FieldLocks)
            {
                Console.WriteLine("Lock: " + Lock);
            }
            return(perms);
        }
        /// <summary>
        ///   Checks if the pdf stamper has any field positions.
        ///   If the stamper has any field positions it'll set the out parameter with the first field position.
        /// </summary>
        /// <param name="pdfStamper">The pdf stamper to use.</param>
        /// <param name="name">The field name to use.</param>
        /// <param name="fieldPosition">The field position, which is set to the first field position or to null.</param>
        /// <returns>True or false, whether the field has any field positions or not.</returns>
        public static bool GetFieldPosition(this PdfStamper pdfStamper, string name, out AcroFields.FieldPosition fieldPosition)
        {
            var fieldPositions = pdfStamper.AcroFields.GetFieldPositions(name);

            fieldPosition = fieldPositions.Any() ? fieldPositions[0] : null;

            return(fieldPositions.Any());
        }
Пример #4
0
        /// <summary>
        ///   Scales and sets the absolute position for the image.
        /// </summary>
        /// <param name="image">The image to use.</param>
        /// <param name="fieldPosition">The field position to use.</param>
        /// <returns>The image which was used.</returns>
        public static Image SetImageMetrics(this Image image, AcroFields.FieldPosition fieldPosition)
        {
            Guard.AgainstNull(fieldPosition, "The field position cannot be empty.");

            image.ScaleAbsolute(fieldPosition.position.Width, fieldPosition.position.Height);
            image.SetAbsolutePosition(fieldPosition.position.Left, fieldPosition.position.Bottom);

            return(image);
        }
Пример #5
0
        public bool AddParagraph(Paragraph p, PdfContentByte canvas,
                                 AcroFields.FieldPosition f, bool simulate)
        {
            ColumnText ct = new ColumnText(canvas);

            ct.SetSimpleColumn(
                f.position.Left, f.position.GetBottom(2),
                f.position.GetRight(2), f.position.Top
                );
            ct.AddElement(p);
            return(ColumnText.HasMoreText(ct.Go(simulate)));
        }
Пример #6
0
    public List <string> AddSignature(string svgString, string[] fileString)
    {
        List <string> savePaths = new List <string>();

        svgString = svgString.Split(',')[1];
        Byte[] bytes = Convert.FromBase64String(svgString);
        iTextSharp.text.Image itextImage = iTextSharp.text.Image.GetInstance(bytes);
        foreach (var file in fileString)
        {
            try
            {
                string fullPath       = System.Web.HttpContext.Current.Server.MapPath("~" + file.Replace(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath, ""));
                int    idx            = fullPath.LastIndexOf('.');
                int    idx2           = file.LastIndexOf('.');
                string fileEnd        = "_signed" + Path.GetRandomFileName() + ".pdf";
                string saveFileString = fullPath.Substring(0, idx) + fileEnd;
                string relSaveString  = file.Substring(0, idx2) + fileEnd;;
                using (Stream inputPdfStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read))


                    using (Stream outputPdfStream = new FileStream(saveFileString, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        var reader         = new PdfReader(inputPdfStream);
                        var stamper        = new PdfStamper(reader, outputPdfStream);
                        var pdfContentByte = stamper.GetOverContent(1);

                        AcroFields formFields = stamper.AcroFields;
                        if (formFields.Fields.ContainsKey("signature"))
                        {
                            int i = 0;
                            foreach (var field in formFields.Fields)
                            {
                                if (field.Key == "signature")
                                {
                                    AcroFields.FieldPosition f = formFields.GetFieldPositions(field.Key)[i];
                                    int page = formFields.GetFieldPositions(field.Key)[i].page;//get(i).page;
                                    formFields.SetField("Start_date", DateTime.Now.ToString("yyyy/MM/dd"));
                                    iTextSharp.text.Rectangle rect = f.position;
                                    itextImage.ScaleToFit(rect.Width, rect.Height);
                                    int p = reader.NumberOfPages;

                                    itextImage.SetAbsolutePosition(rect.Left, rect.Bottom);
                                    i++;
                                    pdfContentByte = stamper.GetOverContent(page);
                                    pdfContentByte.AddImage(itextImage);
                                }
                            }
                        }
                        stamper.FormFlattening = true;
                        stamper.Close();
                    }
                System.IO.File.Delete(fullPath);
                savePaths.Add(relSaveString);
            }
            catch (Exception ex)
            {
                // write to log
                throw (ex);
            }
        }
        return(savePaths);
    }
Пример #7
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();
            }
        }
Пример #8
0
        private static MessageReport.Signature InspectSignature(AcroFields fields, String name, SignaturePermissions perms)
        {
            MessageReport.Signature sigInfo = new MessageReport.Signature();

            IList <AcroFields.FieldPosition> fps = fields.GetFieldPositions(name);

            if (fps != null && fps.Count > 0)
            {
                AcroFields.FieldPosition fp = fps[0];
                Rectangle pos = fp.position;
                if (pos.Width == 0 || pos.Height == 0)
                {
                    sigInfo.visible = false;
                }
                else
                {
                    sigInfo.visible = true;
                }
            }

            PdfPKCS7 pkcs7 = VerifySignature(fields, name, ref sigInfo);

            sigInfo.digestAlgorithm     = pkcs7.GetHashAlgorithm();
            sigInfo.encryptionAlgorithm = pkcs7.GetEncryptionAlgorithm();
            sigInfo.isRevocationValid   = pkcs7.IsRevocationValid();


            X509Certificate cert = pkcs7.SigningCertificate;

            sigInfo.signerName = CertificateInfo.GetSubjectFields(cert).GetField("CN");

            if (pkcs7.SignName != null)
            {
                sigInfo.signerName = pkcs7.SignName;
            }

            sigInfo.signDate = pkcs7.SignDate.ToString("yyyy-MM-dd HH:mm:ss.ff");

            if (!pkcs7.TimeStampDate.Equals(DateTime.MaxValue))
            {
                sigInfo.isTimestampped = true;
                sigInfo.timestampDate  = pkcs7.TimeStampDate.ToString("yyyy-MM-dd HH:mm:ss.ff");

                TimeStampToken ts = pkcs7.TimeStampToken;
                sigInfo.timestampName = ts.TimeStampInfo.Tsa.ToString();
            }

            sigInfo.signLocation = pkcs7.Location;
            sigInfo.signReason   = pkcs7.Reason;

            PdfDictionary sigDict = fields.GetSignatureDictionary(name);
            PdfString     contact = sigDict.GetAsString(PdfName.CONTACTINFO);

            if (contact != null)
            {
                Console.WriteLine("Contact info: " + contact);
            }
            perms = new SignaturePermissions(sigDict, perms);

            sigInfo.signatureType = (perms.Certification ? "certification" : "approval");


            return(sigInfo);
        }