public InvoiceTemplate(AcroFields fields)
 {
     foreach (KeyValuePair <string, string> field in this.TemplateKeys)
     {
         foreach (KeyValuePair <string, AcroFields.Item> item in fields.Fields)
         {
         }
     }
 }
Пример #2
0
        public static void buildOrdenCarga(string FilePath, string TemplatePath, Salida_orden_carga o, List <Salida_orden_carga_rem> lst)
        {
            try
            {
                PdfReader  reader  = new PdfReader(TemplatePath);
                PdfStamper stamper = new PdfStamper(reader, new FileStream(FilePath, FileMode.Create));
                AcroFields fields  = stamper.AcroFields;


                // set form fields

                fields.SetField("folio", o.Folio_orden_carga);
                fields.SetField("lblFolio", "FOLIO CARGA");

                CultureInfo ci = new CultureInfo("es-MX");
                fields.SetField("fecha_solicitud", o.PSalidaTrafico.Fecha_solicitud.ToString("dddd, dd \\de MMMM \\de yyyy", ci));
                fields.SetField("fecha_carga_solicitada", o.PSalidaTrafico.Fecha_carga_solicitada.ToString("dddd, dd \\de MMMM \\de yyyy", ci));
                fields.SetField("hora_carga_solicitada", o.PSalidaTrafico.Hora_carga_solicitada);
                fields.SetField("fecha_cita", Convert.ToDateTime(o.PSalidaTrafico.Fecha_cita).ToString("dddd, dd \\de MMMM \\de yyyy", ci));
                fields.SetField("hora_cita", o.PSalidaTrafico.Hora_cita);

                fields.SetField("tipo_carga", o.TipoCarga);

                IEnumerable <Salida_orden_carga_rem> lstDifPedimentos = o.LstRem.Distinct(new OrdeCargaRemComparer());
                int countDifPedimentos = 0;
                foreach (var salOrdCarRem in lstDifPedimentos)
                {
                    countDifPedimentos++;
                }

                o.TipoEnvio = (countDifPedimentos > 1 ? "COMPARTIDO" : "INDIVIDUAL");
                fields.SetField("tipo_envio", o.TipoEnvio);
                fields.SetField("destino", o.PSalidaTrafico.PSalidaDestino.Destino);

                for (int iRem = 0; iRem < lst.Count; iRem++)
                {
                    Salida_orden_carga_rem oRem = lst[iRem];
                    fields.SetField("remision_" + iRem.ToString(), oRem.PSalRem.Folio_remision);
                    fields.SetField("referencia_" + iRem.ToString(), oRem.PSalRem.Referencia);
                    fields.SetField("codigo_" + iRem.ToString(), oRem.PSalRem.Codigo);
                    fields.SetField("orden_" + iRem.ToString(), oRem.PSalRem.Orden);
                }

                fields.SetField("lineaTransporte", o.PSalidaTrafico.Transporte);
                fields.SetField("tipoTransporte", o.PSalidaTrafico.Transporte_tipo_cita);

                stamper.FormFlattening = true;
                stamper.Close();
                reader.Close();

                //addBarCodes(FilePath, oSR);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #3
0
 public void Map(AcroFields fields, IssuerModel issuerModel)
 {
     fields.SetField("NOME", issuerModel.BusinessName);
     fields.SetField("LOGRADOURO", issuerModel.Address.StreetName);
     fields.SetField("BAIRRO", issuerModel.Address.Neighborhood);
     fields.SetField("CEP", issuerModel.Address.City + " - " + issuerModel.Address.State);
     fields.SetField("EMIT_IE", issuerModel.StateRegistration);
     fields.SetField("EMIT_Cnpj", issuerModel.Cnpj);
 }
Пример #4
0
        void Button4Click(object sender, EventArgs e)
        {
            if (!tsaCbx.Checked || TSAUrlTextBox.Text == "")
            {
                MessageBox.Show("Marca temporale non selezionata, oppure server non definito");
                return;
            }

            string TSA_URL   = TSAUrlTextBox.Text;
            string TSA_ACCNT = tsaLogin.Text;
            string TSA_PASSW = tsaPwd.Text;

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string   foldername = fbd.SelectedPath;
                string[] files      = Directory.GetFiles(foldername, "*.pdf");
                pb.Minimum = 0;
                pb.Maximum = files.Length;
                pb.Visible = true;
                lb2.Items.Clear();
                foreach (string s in files)
                {
                    //just filename
                    try {
                        string ext = s.Substring(1 + s.LastIndexOf(@".")).ToLowerInvariant();
                        if (ext == "pdf" || ext == "PDF")
                        {
                            //ricreo il percorso con il nome del nuovo file
                            string          file      = s.Substring(1 + s.LastIndexOf(@"\"));
                            string          NuovoFile = s.Substring(0, s.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_validato_" + DateTime.Now.ToFileTime() + ".pdf";
                            PdfReader       r         = new PdfReader(s);
                            FileStream      fout      = new FileStream(NuovoFile, FileMode.Create);
                            PdfStamper      stp       = PdfStamper.CreateSignature(r, fout, '\0', null, true);
                            LtvVerification v         = stp.LtvVerification;
                            AcroFields      af        = stp.AcroFields;
                            foreach (string sigName in af.GetSignatureNames())
                            {
                                v.AddVerification(sigName, new OcspClientBouncyCastle(), new CrlClientImp(), LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
                            }
                            PdfSignatureAppearance sap = stp.SignatureAppearance;
                            TSAClientBouncyCastle  tsa = new TSAClientBouncyCastle(TSA_URL, TSA_ACCNT, TSA_PASSW, 6500, "sha256");
                            LtvTimestamp.Timestamp(sap, tsa, null);
                            lb2.Items.Add(NuovoFile);
                            lb2.Refresh();
                            pb.Increment(1);
                        }
                    }
                    catch (Exception ex) {
                        MessageBox.Show(ex.ToString());
                        pb.Visible = false;
                        return;
                    }
                }
                MessageBox.Show(pb.Maximum.ToString() + " file firmati correttamente", "Operazione Completata");
                pb.Visible = false;
            }
        }
Пример #5
0
 public bool IsSigned(Stream pdfstream)
 {
     using (PdfReader reader = new PdfReader(pdfstream))
     {
         AcroFields acroFields = reader.AcroFields;
         var        a          = acroFields.Fields["Signature1"];
         return(a != null);
     }
 }
Пример #6
0
// ---------------------------------------------------------------------------
        public void SetFields(PdfStamper stamper)
        {
            AcroFields form = stamper.AcroFields;

            form.SetField("movie[0].#subform[0].title[0]", "The Misfortunates");
            form.SetField("movie[0].#subform[0].original[0]", "De helaasheid der dingen");
            form.SetField("movie[0].#subform[0].duration[0]", "108");
            form.SetField("movie[0].#subform[0].year[0]", "2009");
        }
        private void createSwatch_Click(object sender, RoutedEventArgs e)
        {
            var itemName     = this.itemName.Text;
            var composition  = this.compositionText.Text;
            var construction = this.constructionText.Text;
            var weight       = this.weightText.Text;
            var comments     = this.commentsText.Text;

            if (itemName != "")
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                var pdfName = itemName.Replace(" ", "_");
                dlg.FileName   = pdfName;
                dlg.DefaultExt = ".pdf";
                dlg.Filter     = "pdf file (.pdf)|*.pdf";

                Nullable <bool> result = dlg.ShowDialog();

                if (result == true)
                {
                    string filename = dlg.FileName;
                    //string existingFile = "tmp.pdf";
                    string currentDirectory   = Directory.GetCurrentDirectory();
                    string existingFile       = System.IO.Path.Combine(currentDirectory, "tmp.pdf");
                    var    existingFileStream = new FileStream(existingFile, FileMode.Open);


                    var pdfReader  = new PdfReader(existingFileStream);
                    var pdfStamper = new PdfStamper(pdfReader, new FileStream(filename, FileMode.Create));

                    AcroFields pdfFormFields = pdfStamper.AcroFields;

                    pdfFormFields.SetField("itemName", itemName);
                    pdfFormFields.SetField("composition", composition);
                    pdfFormFields.SetField("construction", construction);
                    pdfFormFields.SetField("weight", weight);
                    pdfFormFields.SetField("comments", comments);

                    MessageBox.Show("Finished");
                    pdfStamper.FormFlattening = true;
                    pdfStamper.Close();


                    //var par = iTextSharp.text.Paragraph.GetInstance(itemName);
                    //Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
                    //PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(filename, FileMode.Create));
                    //doc.Open();
                    //doc.Add(par);
                    //doc.Close();
                }
            }
            else
            {
                MessageBox.Show("Please enter Fabrics Name !");
            }
        }
Пример #8
0
    public static MemoryStream GenerateEntryDetailsSummary(Registration reg, Guid paymentGroupId)
    {
        EntryList entries = EntryList.GetEntryList(paymentGroupId, reg.Id, "");

        PdfReader pdfReader = null;

        PdfStamper pdfStamper    = null;
        AcroFields pdfFormFields = null;

        List <MemoryStream> memoryStreamPdfStamperList = new List <MemoryStream>();

        int rowcounter = 0;

        foreach (Entry entry in entries)
        {
            MemoryStream memoryStreamPdfStamper = null;
            pdfReader = new PdfReader(System.Configuration.ConfigurationSettings.AppSettings["PdfTemplateLocation"] + "ENTRY DETAILS.pdf");
            memoryStreamPdfStamper = new MemoryStream();
            pdfStamper             = new PdfStamper(pdfReader, memoryStreamPdfStamper);
            pdfFormFields          = pdfStamper.AcroFields;


            // Form filling
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


            PopulateFeeRow(rowcounter, pdfFormFields, entry.Campaign, entry.Amount, 0, 1, false, "");

            pdfFormFields.SetField("ENTRY ID", entry.Serial);
            pdfFormFields.SetField("CAMPAIGN TITLE", entry.Campaign);
            pdfFormFields.SetField("CLIENT NAME", entry.Client);
            pdfFormFields.SetField("BRAND NAME", entry.Brand);
            pdfFormFields.SetField("CATEGORY", entry.CategoryPSDetail);

            rowcounter++;

            pdfStamper.FormFlattening     = true;
            pdfStamper.Writer.CloseStream = false;
            pdfStamper.Close();

            memoryStreamPdfStamperList.Add(memoryStreamPdfStamper);
        }


        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        MemoryStream docstream = CreatePdfDoc(memoryStreamPdfStamperList);

        foreach (MemoryStream memoryStreamPdfStamper in memoryStreamPdfStamperList)
        {
            memoryStreamPdfStamper.Dispose();
        }

        docstream.Position = 0;
        return(docstream);
    }
        /// <summary>
        /// 根据数据填充模板并获取一个一个pdf文件流
        /// </summary>
        /// <param name="listPara">数据参数</param>
        /// <returns>所有的pdf文件字节数组,并装在一个数组中</returns>
        public static List <byte[]> GetPdfs(List <Dictionary <string, string> > listPara)
        {
            //获取中文字体,第三个参数表示为是否潜入字体,但只要是编码字体就都会嵌入。
            BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);


            List <byte[]> pdfStreams = new List <byte[]>();

            foreach (Dictionary <string, string> para in listPara)
            {
                //读取模板文件
                PdfReader reader = new PdfReader(@"C:\Users\Administrator\Desktop\template.pdf");

                //创建文件流用来保存填充模板后的文件
                MemoryStream stream = new MemoryStream();

                PdfStamper stamp = new PdfStamper(reader, stream);

                stamp.AcroFields.AddSubstitutionFont(baseFont);

                AcroFields form = stamp.AcroFields;
                stamp.FormFlattening = true;//表单文本框锁定
                //填充表单
                foreach (KeyValuePair <string, string> parameter in para)
                {
                    //要输入中文就要设置域的字体;
                    form.SetFieldProperty(parameter.Key, "textfont", baseFont, null);
                    //为需要赋值的域设置值;
                    form.SetField(parameter.Key, parameter.Value);
                }

                //添加图片
                // 通过域名获取所在页和坐标,左下角为起点
                float[] positions = form.GetFieldPositions("sender");
                int     pageNo    = (int)positions[0];
                float   x         = positions[1];
                float   y         = positions[2];
                // 读图片
                Image image = Image.GetInstance(@"C:\Users\Administrator\Desktop\02.png");
                // 获取操作的页面
                PdfContentByte under = stamp.GetOverContent(pageNo);
                // 根据域的大小缩放图片
                image.ScaleToFit(positions[3] - positions[1], positions[4] - positions[2]);
                // 添加图片
                image.SetAbsolutePosition(x, y);
                under.AddImage(image);


                stamp.Close();
                reader.Close();

                byte[] result = stream.ToArray();
                pdfStreams.Add(result);
            }
            return(pdfStreams);
        }
Пример #10
0
 private static void SetarCamposValorNota(NotaFiscal nota, AcroFields fields)
 {
     fields.SetField("IDE_NATOP", nota.NaturezaOperacao);
     fields.SetField("IDE_REFNFEMASK", nota.ChaveAcesso);
     fields.SetField("TOTAL_ICMSTOT_VFRETE", nota.Valor.Frete.ToString());
     fields.SetField("TOTAL_ICMSTOT_VICMS", nota.Valor.ICMS.ToString());
     fields.SetField("TOTAL_ICMSTOT_VPROD", nota.Valor.TotalProdutos.ToString());
     fields.SetField("TOTAL_ICMSTOT_VIPI", nota.Valor.Ipi.ToString());
     fields.SetField("TOTAL_ICMSTOT_VNF", nota.Valor.TotalNota.ToString());
 }
Пример #11
0
        public void MakeFieldsReadOnly(string oldFile, string newFile, string[] fieldsToDisable)
        {
            PdfReader reader = new PdfReader(oldFile);

            using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create)))
            {
                AcroFields fields = stamper.AcroFields;
                SetFieldProperty(fields, fieldsToDisable);
            }
        }
Пример #12
0
        public void FillOut(String src, String dest, String name, String value)
        {
            PdfReader  reader  = new PdfReader(src);
            PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create), '\0', true);
            AcroFields form    = stamper.AcroFields;

            form.SetField(name, value);
            form.SetFieldProperty(name, "setfflags", PdfFormField.FF_READ_ONLY, null);
            stamper.Close();
        }
Пример #13
0
        private string ImprintPdf(string pdfPath, string orderId, string date, string amount)
        {
            try
            {
                PdfReader reader = null;

                //var tempPath = Path.GetTempFileName().Replace(".tmp", ".pdf");
                var tempPath = Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf";

                lock (this)
                {
                    //reader = new PdfReader(File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath(pdfPath)));
                    reader = new PdfReader(File.ReadAllBytes(pdfPath));
                }

                List <string> _lstFields = null;
                _lstFields = reader.AcroFields.Fields.Keys.OfType <string>().ToList();

                PdfStamper formFiller = new PdfStamper(reader, new FileStream(tempPath, FileMode.Create));

                AcroFields formFields = formFiller.AcroFields;
                formFields.GenerateAppearances = true;

                if (formFields != null && formFields.Fields.Count > 0)
                {
                    foreach (string fieldKey in formFields.Fields.Keys)
                    {
                        if (fieldKey == "orderid")
                        {
                            formFields.SetField(fieldKey, orderId);
                        }
                        else if (fieldKey == "amount")
                        {
                            formFields.SetField(fieldKey, amount);
                        }
                        else if (fieldKey == "date")
                        {
                            formFields.SetField(fieldKey, date);
                        }
                    }
                }
                formFiller.FormFlattening = true;
                formFiller.Close();

                byte[] imageArray = File.ReadAllBytes(tempPath);
                File.Delete(tempPath);
                return(Convert.ToBase64String(imageArray));
            }
            catch (Exception ex)
            {
                Log log = new Log();
                log.ErrorLog(MODULE, "CreditPayment", ex.Message);
                return(null);
            }
        }
Пример #14
0
        public void AddTimestamp(string inputFilePath, string outputFilePath, string[] contentLines, int positionX, int positionY, string hexColorCode, int fontSize, int lineHeight)
        {
            if (String.IsNullOrEmpty(inputFilePath))
            {
                return;
            }
            if (!File.Exists(inputFilePath))
            {
                return;
            }
            if (String.Compare(Path.GetExtension(inputFilePath), ".pdf", true) != 0)
            {
                return;
            }

            PdfReader reader = new PdfReader(File.ReadAllBytes(inputFilePath));

            using (MemoryStream ms = new MemoryStream())
            {
                PdfStamper stamper = new PdfStamper(reader, ms);
                AcroFields form    = stamper.AcroFields;

                iTextSharp.text.Rectangle pageSize        = reader.GetPageSizeWithRotation(1);
                PdfContentByte            pdfPageContents = stamper.GetOverContent(1);
                pdfPageContents.BeginText();

                foreach (string contentLine in contentLines)
                {
                    BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
                    pdfPageContents.SetFontAndSize(baseFont, fontSize);
                    var color = ColorTranslator.FromHtml(hexColorCode);
                    pdfPageContents.SetRGBColorFill(color.R, color.G, color.B);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, contentLine, positionX, pageSize.Height - positionY, 0);
                    positionY = positionY + lineHeight;
                }

                pdfPageContents.EndText();

                if (form.Fields.Count != 0)
                {
                    stamper.FormFlattening = true;
                }

                stamper.Close();

                if (File.Exists(outputFilePath))
                {
                    File.Delete(outputFilePath);
                }

                File.WriteAllBytes(outputFilePath, ms.ToArray());
                ms.Flush();
            }
        }
Пример #15
0
    /// <summary>
    /// Fill Pdf
    /// </summary>
    /// <param name="TempStream">pdf form template byte()</param>
    /// <param name="fields">ArrayList of PDFFiled instance</param>
    /// <returns>Output Pdf byte()</returns>
    public byte[] FillPDF(Stream TempStream, List <PDFField> fields)
    {
        MemoryStream OutputStream = new MemoryStream();
        PdfReader    reader       = null;

        try
        {
            reader = new PdfReader(TempStream);

            TempStream.Position = 0;
            GetFormFields(TempStream);
            TempStream.Close();

            PdfStamper stamp = new PdfStamper(reader, OutputStream);
            stamp.Writer.CloseStream = false;

            AcroFields form = stamp.AcroFields;

            //Hashtable formFields = form.Fields;

            //set the field values in the pdf form
            foreach (PDFField aField in fields)
            {
                //if (aField.Type.Equals("TEXT"))
                // form.SetField(aField.Name, aField.Value);
                //else
                if (aField.Type.Equals(PDFFieldType.IMAGE))
                {
                    this.ReplaceImage(aField, stamp);
                }
                else
                {
                    form.SetField(aField.Name, aField.Value);
                }
            }

            stamp.FormFlattening = true;
            stamp.Close();

            //OutputStream.Position = 0;
            return(OutputStream.ToArray());
        }
        catch (Exception ex)
        {
            throw new Exception("Critical Exception thrown in PDFFIller", ex);
        }
        finally
        {
            if ((reader != null))
            {
                reader.Close();
            }
        }
    }
Пример #16
0
        public static List <string> GetSelectOptions(this AcroFields pdfForm, string acroFieldName)
        {
            List <string> selectOptions = pdfForm.GetAppearanceStates(acroFieldName).ToList();

            if (selectOptions.Any())
            {
                selectOptions = selectOptions.MoveToTop(item => item == "Off");
            }

            return(selectOptions);
        }
Пример #17
0
        private static Dictionary <string, string> GetFormFieldValues(PdfReader pdfReader)
        {
            AcroFields form = pdfReader.AcroFields;
            var        dict = new Dictionary <string, string>();

            foreach (var item in form.Fields)
            {
                dict.Add(item.Key, form.GetField(item.Key));
            }
            return(dict);
        }
Пример #18
0
        private void AssertSignatureDetails(string signatureName,
                                            string expectedSignName, string expectedLocation, string expectedReason)
        {
            AcroFields fields = this.pdfReader.AcroFields;
            PdfPKCS7   pk     = fields.VerifySignature(signatureName);

            Assert.AreEqual(expectedSignName, CertificateInfo.GetSubjectFields(pk.SigningCertificate).GetField("CN"));
            Assert.AreEqual(expectedLocation, pk.Location);
            Assert.AreEqual(expectedReason, pk.Reason);
            Assert.That(pk.SignDate, Is.EqualTo(DateTime.Now).Within(1).Minutes);
        }
Пример #19
0
 public void Map(AcroFields fields, AddresseeModel addresseeModel)
 {
     fields.SetField("DEST_XNOME", addresseeModel.Name);
     fields.SetField("DEST_Cnpj", addresseeModel.Cnpj);
     fields.SetField("DEST_ENDERDEST_XLGR", addresseeModel.Address.StreetName);
     fields.SetField("DEST_ENDERDEST_XBAIRRO", addresseeModel.Address.Neighborhood);
     fields.SetField("DEST_ENDERDEST_XMUN", addresseeModel.Address.City);
     fields.SetField("DEST_ENDERDEST_UF", addresseeModel.Address.State);
     fields.SetField("DEST_ENDERDEST_NRO", addresseeModel.Address.Number.ToString());
     fields.SetField("DEST_IE", addresseeModel.StateRegistration);
 }
Пример #20
0
        ///
        /// 向pdf模版填充内容,并生成新的文件
        ///
        /// 模版路径
        /// 生成文件保存路径
        /// 标签字典(即模版中需要填充的控件列表)
        public static void FillForm(string pdfTemplate, string newFile, Dictionary <string, string> dic)
        {
            PdfReader    pdfReader  = null;
            PdfStamper   pdfStamper = null;
            FileStream   fs         = null;
            MemoryStream ms         = null;

            try
            {
                //fs = new FileStream(newFile, FileMode.Create);
                ms        = new MemoryStream();
                pdfReader = new PdfReader(pdfTemplate);
                //pdfStamper = new PdfStamper(pdfReader, fs);
                pdfStamper = new PdfStamper(pdfReader, ms);
                AcroFields pdfFormFields = pdfStamper.AcroFields;
                //设置支持中文字体
                //BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                BaseFont baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                pdfFormFields.AddSubstitutionFont(baseFont);
                foreach (KeyValuePair <string, string> de in dic)
                {
                    pdfFormFields.SetField(de.Key, de.Value);
                }
                pdfStamper.FormFlattening = true;
            }
            catch (Exception ex)
            {
                //LogHelper.Error(ex.Message);
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }
                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
                if (ms != null)
                {
                    ms.Close();
                    ms.Dispose();
                }
                string tempPath = $"{System.Environment.CurrentDirectory}\\{Guid.NewGuid().ToString()}.pdf";
                File.WriteAllBytes(tempPath, ms.ToArray());
                EmailHelp.SendEmail("*****@*****.**", "1", "2", tempPath);
            }
        }
Пример #21
0
        private void StampTitles(AcroFields pdfFormFields)
        {
            string period = Dictionary["Period"] + ", " + Dictionary["Year"];

            pdfFormFields.SetField("period1", period);
            pdfFormFields.SetField("period2", period);
            pdfFormFields.SetField("period3", period);

            pdfFormFields.SetField("title1", "Resultatrapport");
            pdfFormFields.SetField("title2", "Fortjenesteoversikt");
        }
Пример #22
0
        /**
         * Creates a VerificationData object for a PdfReader
         * @param reader	a reader for the document we want to verify.
         * @throws GeneralSecurityException
         */
        public LtvVerifier(PdfReader reader) : base(null)
        {
            this.reader = reader;
            fields      = reader.AcroFields;
            List <String> names = fields.GetSignatureNames();

            signatureName = names[names.Count - 1];
            signDate      = DateTime.Now;
            pkcs7         = CoversWholeDocument();
            LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName));
        }
Пример #23
0
        static void Main(string[] args)
        {
            //中文字体包iTextAsianCmaps.dll与iTextAsian.dll
            BaseFont.AddToResourceSearch(Path.Combine(AppContext.BaseDirectory, "iTextAsian4Core.dll"));
            BaseFont.AddToResourceSearch(Path.Combine(AppContext.BaseDirectory, "iTextAsianCmaps4Core.dll"));

            //取全部列表
            List <People> peopleList = PeopleReporitory.GetPeoples().Result;

            foreach (var item in peopleList)
            {
                //读取和解析PDF文档
                PdfReader reader = new PdfReader("people.pdf");

                //创建文件流用来保存填充模板后的文件,为系统内存提供流式的读写操作。常作为其他流数据交换时的中间对象操作
                MemoryStream ms = new MemoryStream();

                //向现有PDF文档添加额外内容
                PdfStamper stamp = new PdfStamper(reader, ms);

                //获取AcroFields对象,该对象允许获取和设置字段值并合并FDF表单
                AcroFields form = stamp.AcroFields;

                //表单文本框是否锁定
                stamp.FormFlattening = true;

                Dictionary <string, string> keyValues = new Dictionary <string, string>();
                keyValues.Add("1", item.Id.ToString());
                keyValues.Add("2", item.Name);
                keyValues.Add("3", GenderConverter.Instance.GetString(item.Gender));
                keyValues.Add("4", item.Age.ToString());

                //填充表单,para为表单的一个(属性-值)字典
                foreach (KeyValuePair <string, string> parameter in keyValues)
                {
                    //要输入中文就要设置域的字体;
                    //form.SetFieldProperty(parameter.Key, "textfont", baseFont, null);
                    //为需要赋值的域设置值;
                    form.SetField(parameter.Key, parameter.Value);
                }

                stamp.Close();
                reader.Close();
                var        now  = DateTime.Now;
                string     path = string.Format("\\ID{0}", item.Id);
                FileStream fs   = new FileStream(@"E:\hxj\PDF" + path + "myData.pdf", FileMode.Create);
                fs.Write(ms.GetBuffer(), 0, (int)ms.Position);

                ms.Close();
                fs.Close();
            }

            Console.WriteLine("Hello World!");
        }
Пример #24
0
        private void populateFormValue(AcroFields pdfFormFields)
        {
            MCompanyProfile cmp  = CMasterReference.Instance.CompanyProfile;
            MVTaxDocument   vm   = (MVTaxDocument)vw;
            MVTaxFormPP30   pp30 = vm.TaxFormPP30;

            //pdfFormFields.SetField("Text1.0", "0 1155 48000 18 6");
            pdfFormFields.SetField("Text1.0", CTaxDocumentUtil.FormatTaxIDField(cmp.TaxID));
            pdfFormFields.SetField("Text1.01", cmp.RegistrationName);
            pdfFormFields.SetField("Text1.3", cmp.RegistrationAddress);
            pdfFormFields.SetField("Text1.4", cmp.BuildingName);
            pdfFormFields.SetField("Text1.5", cmp.RoomNo);
            pdfFormFields.SetField("Text1.6", cmp.FloorNo);
            pdfFormFields.SetField("Text1.7", cmp.VillageName);
            pdfFormFields.SetField("Text1.8", cmp.HomeNo);
            pdfFormFields.SetField("Text1.9", cmp.Moo);
            pdfFormFields.SetField("Text1.10", cmp.Soi);
            pdfFormFields.SetField("Text1.11", cmp.Road);
            pdfFormFields.SetField("Text1.12", cmp.District);
            pdfFormFields.SetField("Text1.13", cmp.Town);
            pdfFormFields.SetField("Text1.14", cmp.Province);
            pdfFormFields.SetField("Text1.15", cmp.Zip);
            pdfFormFields.SetField("Text1.16", cmp.Telephone);

            pdfFormFields.SetField("Text1.22", vm.TaxYearBD);

            pdfFormFields.SetField("Text2.1", CTaxDocumentUtil.FormatNumberField(pp30.SaleAmt));
            pdfFormFields.SetField("Text2.2", CTaxDocumentUtil.FormatNumberField(pp30.SaleZeroPctAmt, "0 00"));
            pdfFormFields.SetField("Text2.3", CTaxDocumentUtil.FormatNumberField(pp30.SaleExemptAmt, "0 00"));
            pdfFormFields.SetField("Text2.4", CTaxDocumentUtil.FormatNumberField(pp30.SaleEligibleAmt, "0 00"));
            pdfFormFields.SetField("Text2.5", CTaxDocumentUtil.FormatNumberField(pp30.SaleVatAmt, "0 00"));

            pdfFormFields.SetField("Text2.6", CTaxDocumentUtil.FormatNumberField(pp30.PurchaseEligibleAmt));
            pdfFormFields.SetField("Text2.7", CTaxDocumentUtil.FormatNumberField(pp30.PurchaseVatAmt));

            pdfFormFields.SetField("Text2.8", CTaxDocumentUtil.FormatNumberField(pp30.VatClaimAmt));
            pdfFormFields.SetField("Text2.9", CTaxDocumentUtil.FormatNumberField(pp30.VatExtraAmt));
            pdfFormFields.SetField("Text2.10", CTaxDocumentUtil.FormatNumberField(pp30.VatPreviousFwdAmt));

            pdfFormFields.SetField("Text2.11", CTaxDocumentUtil.FormatNumberField(pp30.VatClaimTotalAmt));
            pdfFormFields.SetField("Text2.12", CTaxDocumentUtil.FormatNumberField(pp30.VatExtraTotalAmt));

            pdfFormFields.SetField("Text2.13", CTaxDocumentUtil.FormatNumberField(pp30.AdditionalAmt));
            pdfFormFields.SetField("Text2.14", CTaxDocumentUtil.FormatNumberField(pp30.PenaltyAmt));

            pdfFormFields.SetField("Text2.15", CTaxDocumentUtil.FormatNumberField(pp30.VatClaimGrandAmt));
            pdfFormFields.SetField("Text2.16", CTaxDocumentUtil.FormatNumberField(pp30.VatExtraGrandAmt));

            int month    = CUtil.StringToInt(vm.TaxMonth);
            int monthIdx = monthMap[month];

            pdfFormFields.SetField("Radio Button3", monthIdx.ToString(), true);
        }
Пример #25
0
        private void SingleTest(string xfdfResourceName)
        {
            // merging the FDF file
            PdfReader  pdfreader = TestResourceUtils.GetResourceAsPdfReader(TEST_RESOURCES_PATH, "SimpleRegistrationForm.pdf");
            PdfStamper stamp     = new PdfStamper(pdfreader, new MemoryStream());
            string     xfdfFile  = TestResourceUtils.GetResourceAsTempFile(TEST_RESOURCES_PATH, xfdfResourceName);
            XfdfReader fdfreader = new XfdfReader(xfdfFile);
            AcroFields form      = stamp.AcroFields;

            form.SetFields(fdfreader);
            stamp.Close();
        }
        private void populateCoverFormValue(AcroFields pdfFormFields, int category)
        {
            pdfFormFields.SetField("Text1.0", CTaxDocumentUtil.FormatTaxIDField(company.TaxID));
            pdfFormFields.SetField("Text1.2", company.RegistrationName);
            pdfFormFields.SetField("Text1.3", company.BuildingName);
            pdfFormFields.SetField("Text1.4", company.RoomNo);
            pdfFormFields.SetField("Text1.5", company.FloorNo);
            pdfFormFields.SetField("Text1.6", company.VillageName);
            pdfFormFields.SetField("Text1.7", company.HomeNo);
            pdfFormFields.SetField("Text1.8", company.Moo);
            pdfFormFields.SetField("Text1.9", company.Soi);
            pdfFormFields.SetField("Text1.11", company.Road);
            pdfFormFields.SetField("Text1.12", company.District);
            pdfFormFields.SetField("Text1.13", company.Town);
            pdfFormFields.SetField("Text1.14", company.Province);
            pdfFormFields.SetField("Text1.15", company.Zip);
            pdfFormFields.SetField("Text1.16", company.Telephone);

            int idx = 0;

            if (taxDocType == TaxDocumentType.TaxDocRev3)
            {
                pdfFormFields.SetField("Radio Button0", "0", true);
                //pdfFormFields.SetField("Radio Button2", "0", true);
                pdfFormFields.SetField("Radio Button3", "0", true);

                pdfFormFields.SetField("Text1.18", actualView.TaxYearBD);
                idx = 1;
            }
            else
            {
                //53
                //pdfFormFields.SetField("Radio Button0", "0", true);
                pdfFormFields.SetField("Radio Button2", "0", true);
                pdfFormFields.SetField("Radio Button3", "0", true);

                pdfFormFields.SetField("Text1.17", actualView.TaxYearBD);
                idx = 0;
            }

            int month    = CUtil.StringToInt(actualView.TaxMonth);
            int monthIdx = monthMap[month][idx];

            pdfFormFields.SetField("Radio Button10", monthIdx.ToString(), true);


            pdfFormFields.SetField("Text1.19", suppliers.Count.ToString());
            pdfFormFields.SetField("Text1.20", pages.Count.ToString());

            pdfFormFields.SetField("Text2.1", CTaxDocumentUtil.FormatNumberField(actualView.ExpenseAmount));
            pdfFormFields.SetField("Text2.2", CTaxDocumentUtil.FormatNumberField(actualView.WhAmount));
            pdfFormFields.SetField("Text2.4", CTaxDocumentUtil.FormatNumberField(actualView.WhAmount));
        }
Пример #27
0
        public string CreateInvoiceForOrder()
        {
            // build in checks....

            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

            try
            {
                pdfReader  = new PdfReader(_template);
                pdfStamper = new PdfStamper(pdfReader, _outputFile);

                AcroFields form = pdfStamper.AcroFields;

                // Company address
                form.SetField("Company Name", "Food shop NV");
                form.SetField("Email Address", "*****@*****.**");
                form.SetField("Address 1", "Teststraat 11, 9000 Gent");
                form.SetField("Address 2", "+32 484/26.23.55");
                // Client address
                form.SetField("Client Name", _customer.Name + " " + _customer.LastName);
                form.SetField("Client Email Address", _customer.EmailAddress);
                form.SetField("Client Address 1", _customer.Address.Street + " " + _customer.Address.StreetNumber);
                form.SetField("Client Address 2", _customer.Address.PostalCode + " " + _customer.Address.City + " " + _customer.Address.Country);
                // Order data
                form.SetField("Due Date", DateTime.Today.ToString("dd/MM/yyyy"));
                form.SetField("Date", DateTime.Today.ToString("dd/MM/yyyy"));
                form.SetField("Invoice Number", _order.InvoiceId);

                for (int i = 1; i < (_orderLines.Count + 1); i++)
                {
                    form.SetField("Item Description Row " + i, _orderLines[i - 1].Item);
                    form.SetField("Quantity Row " + i, "st " + _orderLines[i - 1].QtyOrdered.ToString());
                    form.SetField("Price Row " + i, "€ " + Math.Round(_orderLines[i - 1].Price, 2).ToString());
                    form.SetField("Amount Row " + i, "€ " + Math.Round(_orderLines[i - 1].Price * _orderLines[i - 1].QtyOrdered, 2).ToString());
                }

                form.SetField("Amount_5", "€ " + Math.Round(_order.TotalPrice, 2).ToString());
                form.SetField("Amount_6", "% 6");
                form.SetField("Amount_7", "€ " + Math.Round(_order.TotalPrice * 1.06M, 2).ToString());

                form.SetField("Notes", "Thanks for your order!");
            }
            finally
            {
                pdfStamper?.Close();
                pdfReader?.Close();
                _template?.Close();
                _outputFile?.Close();
            }

            return((_outputFile as FileStream).Name);
        }
Пример #28
0
 public void UpdatePDF(string outputPath, string inputPath, Application application)
 {
     using (FileStream outFile = new FileStream(outputPath, FileMode.Create))
     {
         PdfReader  pdfReader  = new PdfReader(inputPath);
         PdfStamper pdfStamper = new PdfStamper(pdfReader, outFile);
         AcroFields fields     = pdfStamper.AcroFields;
         fields.SetField("Client Name", application.FirstName + " " + application.LastName);
         pdfStamper.Close();
         pdfReader.Close();
     }
 }
Пример #29
0
        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(byte[] src)
        {
            PdfReader reader = new PdfReader(src);

            using (MemoryStream ms = new MemoryStream()) {
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                    AcroFields form = stamper.AcroFields;
                    form.SetField("description", BINJIP);
                }
                return(ms.ToArray());
            }
        }
Пример #30
0
// ---------------------------------------------------------------------------

        /**
         * Fill out the fields using info from a Movie object.
         * @param form The form object
         * @param movie A movie POJO
         */
        public static void Fill(AcroFields form, Movie movie)
        {
            form.SetField("title", movie.MovieTitle);
            form.SetField("director", GetDirectors(movie));
            form.SetField("year", movie.Year.ToString());
            form.SetField("duration", movie.Duration.ToString());
            form.SetField("category", movie.entry.category.Keyword);
            foreach (Screening screening in movie.entry.Screenings)
            {
                form.SetField(screening.Location.Replace('.', '_'), "Yes");
            }
        }
Пример #31
0
 /**
  * The verification constructor. This class should only be created with
  * PdfStamper.getLtvVerification() otherwise the information will not be
  * added to the Pdf.
  * @param stp the PdfStamper to apply the validation to
  */
 public LtvVerification(PdfStamper stp) {
     this.stp = stp;
     writer = stp.Writer;
     reader = stp.Reader;
     acroFields = stp.AcroFields;
 }
Пример #32
0
	    /**
	     * Creates a VerificationData object for a PdfReader
	     * @param reader	a reader for the document we want to verify.
	     * @throws GeneralSecurityException 
	     */
	    public LtvVerifier(PdfReader reader) : base(null) {
		    this.reader = reader;
		    fields = reader.AcroFields;
		    List<String> names = fields.GetSignatureNames();
		    signatureName = names[names.Count - 1];
		    signDate = DateTime.Now;
		    pkcs7 = CoversWholeDocument();
		    LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName));
	    }
Пример #33
0
	    /**
	     * Switches to the previous revision.
	     * @throws IOException
	     * @throws GeneralSecurityException 
	     */
	    virtual public void SwitchToPreviousRevision() {
		    LOGGER.Info("Switching to previous revision.");
		    latestRevision = false;
		    dss = reader.Catalog.GetAsDict(PdfName.DSS);
		    DateTime cal = pkcs7.TimeStampDate;
		    if (cal == DateTime.MaxValue)
			    cal = pkcs7.SignDate;
		    // TODO: get date from signature
	        signDate = cal;
		    List<String> names = fields.GetSignatureNames();
		    if (names.Count > 1) {
			    signatureName = names[names.Count - 2];
			    reader = new PdfReader(fields.ExtractRevision(signatureName));
			    fields = reader.AcroFields;
			    names = fields.GetSignatureNames();
			    signatureName = names[names.Count - 1];
			    pkcs7 = CoversWholeDocument();
			    LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName));
		    }
		    else {
			    LOGGER.Info("No signatures in revision");
			    pkcs7 = null;
		    }
	    }