public Stream FillForm(Stream inputStream, PDFSampleForm model)
        {
            Stream     outStream  = new MemoryStream();
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;
            Stream     inStream   = null;

            try
            {
                pdfReader  = new PdfReader(inputStream);
                pdfStamper = new PdfStamper(pdfReader, outStream);
                AcroFields form = pdfStamper.AcroFields;
                form.SetField(SampleFormFieldNames.FirstName, model.FirstName);
                form.SetField(SampleFormFieldNames.LastName, model.LastName);
                form.SetField(SampleFormFieldNames.IAmAwesomeCheck, model.AwesomeCheck ? "Yes" : "Off");
                // set this if you want the result PDF to be uneditable.
                pdfStamper.FormFlattening = true;
                return(outStream);
            }
            finally
            {
                pdfStamper?.Close();
                pdfReader?.Close();
                inStream?.Close();
            }
        }
예제 #2
0
        public Stream FillForm(Stream inputStream, Models.PDF.Invoice model)
        {
            Stream     outStream  = new MemoryStream();
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;
            Stream     inStream   = null;

            try
            {
                pdfReader  = new PdfReader(inputStream);
                pdfStamper = new PdfStamper(pdfReader, outStream);

                AcroFields form = pdfStamper.AcroFields;
                Font       font = GetTHSarabunNew();
                foreach (string key in form.Fields.Keys)
                {
                    form.SetFieldProperty(key, "textfont", font.BaseFont, null);
                    form.RegenerateField(key);
                }
                form.SetField("txt_CustomerName", "เจนวิทย์ เพ็ญจำรัส");
                //  form.SetField("rdb_ans_1","Choice1");

                //  form.SetField("txt_CardName", model.CardName);
                //form.SetField("txt_DocNum", model.Docnum);
                // set this if you want the result PDF to not be editable.
                pdfStamper.FormFlattening = true;
                return(outStream);
            }
            finally
            {
                pdfStamper?.Close();
                pdfReader?.Close();
                inStream?.Close();
            }
        }
예제 #3
0
        public Stream FromValues(string pdfTemplate, IDictionary <string, string> values)
        {
            var pdfStream = new FileStream(path: pdfTemplate, mode: FileMode.Open);
            var outStream = new MemoryStream();

            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

            try
            {
                pdfReader  = new PdfReader(pdfStream);
                pdfStamper = new PdfStamper(pdfReader, outStream);
                AcroFields form = pdfStamper.AcroFields;

                foreach (string f in values.Keys)
                {
                    form.SetField(f, values[f]);
                }

                // set this if you want the result PDF to not be editable.
                pdfStamper.FormFlattening = true;
                return(outStream);
            }
            finally
            {
                pdfStamper?.Close();
                pdfReader?.Close();
            }
        }
예제 #4
0
        public Stream FillForm(Stream inputStream, Profile profile)
        {
            Stream     outStream  = new MemoryStream();
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;
            Stream     inStream   = null;

            try
            {
                pdfReader  = new PdfReader(inputStream);
                pdfStamper = new PdfStamper(pdfReader, outStream);
                AcroFields form = pdfStamper.AcroFields;
                form.SetField("FirstName", $"{profile.FirstName}");
                form.SetField("LastName", $"{profile.LastName}");
                form.SetField("IDNumber", $"{profile.IDNumber}");
                form.SetField("Nationality", $"{profile.Nationality}");
                form.SetField("Email", $"{profile.Email}");
                form.SetField("PhoneNumber", $"{profile.PhoneNumber}");
                pdfStamper.FormFlattening = true;
                return(outStream);
            }
            finally
            {
                pdfStamper?.Close();
                pdfReader?.Close();
                inStream?.Close();
            }
        }
예제 #5
0
        public void ExtractPagesByRange(string filePath, string outputFilePath, int startpage, int endpage)
        {
            var pdfReader = new PdfReader(filePath);

            try
            {
                pdfReader.SelectPages($"{startpage}-{endpage}");
                using (var fs = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
                {
                    PdfStamper stamper = null;
                    try
                    {
                        stamper = new PdfStamper(pdfReader, fs);
                    }
                    finally
                    {
                        stamper?.Close();
                    }
                }
            }
            finally
            {
                pdfReader.Close();
            }
        }
예제 #6
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);
        }
예제 #7
0
        public static void RemoveSignatures(string src, string dest)
        {
            using (var reader = new PdfReader(src))
            {
                var names = reader.AcroFields.GetSignatureNames();
                using (var memStream = new MemoryStream())
                {
                    using (var stamper = new PdfStamper(reader, memStream, '\0', true))
                    {
                        foreach (var name in names)
                        {
                            stamper.AcroFields.RemoveField(name);
                        }

                        stamper.Close();
                        File.WriteAllBytes(dest, memStream.ToArray());
                    }
                }
            }
        }
        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());
            }
        }
예제 #9
0
 private static byte[] AddWatermark(byte[] bytes, BaseFont baseFont, string watermarkText, BaseColor color, int align, int rotationD = 45, int fontSize = 50, float opFill = 0.35F, float opStroke = 0.3F, float xP = 0.5F, float yP = 0.5F)
 {
     using (var ms = new MemoryStream(10 * 1024))
     {
         using (var reader = new PdfReader(bytes))
             using (var stamper = new PdfStamper(reader, ms))
             {
                 var pages = reader.NumberOfPages;
                 for (var i = 1; i <= pages; i++)
                 {
                     var dc = stamper.GetOverContent(i);
                     AddWaterMarkText(dc, watermarkText, baseFont, fontSize, rotationD, color,
                                      reader.GetPageSizeWithRotation(i), opFill, opStroke, xP, yP, align
                                      );
                 }
                 stamper.Close();
             }
         return(ms.ToArray());
     }
 }
예제 #10
0
        public static void AddImage(Stream inputPdfStream, Stream outputPdfStream, Stream inputImageStream)
        {
            PdfReader reader = new PdfReader(inputPdfStream);

            iTextSharp.text.Rectangle size = reader.GetPageSize(1);

            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
            image.SetAbsolutePosition(size.Width - 98, size.Height - 98);

            PdfStamper stamper = new PdfStamper(reader, outputPdfStream);

            int page = 1;

            {
                PdfContentByte pdfContentByte = stamper.GetOverContent(page);

                pdfContentByte.AddImage(image);
            }
            stamper.Close();
        }
 private void fillPDFForm()
 {
     string formFile = Server.MapPath(P_InputStream);
     string newFile = Server.MapPath(P_OutputStream);
     PdfReader reader = new PdfReader(formFile);
     using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create)))
     {
         AcroFields fields = stamper.AcroFields;
 
         // set form fields
         fields.SetField("name", "John Doe");
         fields.SetField("address", "xxxxx, yyyy");
         fields.SetField("postal_code", "12345");
         fields.SetField("email", "*****@*****.**");
 
         // flatten form fields and close document
         stamper.FormFlattening = true;
         stamper.Close();
     }
 }
예제 #12
0
        public static byte[] GeneratePDF(string pdfPath, Dictionary <string, string> formFieldMap)
        {
            var output     = new MemoryStream();
            var reader     = new PdfReader(pdfPath);
            var stamper    = new PdfStamper(reader, output);
            var formFields = stamper.AcroFields;

            foreach (var fieldName in formFieldMap.Keys)
            {
                formFields.SetField(fieldName, formFieldMap[fieldName]);
            }

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

            return(output.ToArray());
        }
예제 #13
0
        static void Main(string[] args)
        {
            string inputFile = "PdfDocument.pdf";

            PdfReader pdfReader = new PdfReader(inputFile);

            PdfReader.unethicalreading = true;

            string outputFile = "OutputPdfFile.pdf";

            PdfStamper pdfStamp = new PdfStamper(pdfReader, new FileStream(outputFile, FileMode.Create));

            AcroFields fields = pdfStamp.AcroFields;

            fields.SetField("Field Name", "Input Value"); // If you do not know *field name*, you can run *GetFormFieldNames(pdfReader)* function to learn

            pdfStamp.Close();

            pdfReader.Close();
        }
예제 #14
0
        /// <summary>
        /// Sets the value of the specified form field in the content
        /// </summary>
        /// <param name="content">The content in which to set the form field</param>
        /// <param name="fieldName">The name of the field to set</param>
        /// <param name="value">The value to set the field to</param>
        /// <returns>The updated content</returns>
        public byte[] SetPdfFormField(byte[] content, string fieldName, string value)
        {
            // Create a pdf reader to read the document content, and a pdf stamper to modify it and output to a memory stream
            var reader  = new PdfReader(content);
            var oStream = new MemoryStream();
            var stamper = new PdfStamper(reader, oStream);

            // Set the form field
            stamper.AcroFields.SetField(fieldName, value);

            // Close the pdf stamper to flush the output memory stream
            stamper.Writer.CloseStream = false;
            stamper.Close();

            // Move the stream position to the beginning
            oStream.Seek(0, SeekOrigin.Begin);

            // Return updated content
            return(oStream.ToArray());
        }
예제 #15
0
        public void SaveComments(string namePDF, int page)
        {
            string oldFile = namePDF;
            string newFile = "temporal.pdf";

            PdfReader  pdfReader  = new PdfReader(oldFile);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));

            Point[] finalcoor = coorComentario.ToArray();
            for (int i = 1; i <= cantComentarios; i++)
            {
                string imageURL = directorio + "\\comment" + i + ".jpg";

                Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read, FileShare.Read);

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
                //int xpos = finalcoor[i - 1].X;
                //int ypos = finalcoor[i - 1].Y;
                Console.WriteLine("estas son las coordenadas" + finalcoor[i - 1].X + " y " + finalcoor[i - 1].Y);
                int xpos = 100;
                int ypos = 100;
                iTextSharp.text.Rectangle rect     = new iTextSharp.text.Rectangle(35 + xpos, 650 - ypos, 35 + xpos + Convert.ToSingle(image.Width * 0.5), 650 - ypos + Convert.ToSingle(image.Height * 0.5));
                PdfAnnotation             pdfStamp = PdfAnnotation.CreateStamp(pdfStamper.Writer, rect, null, Guid.NewGuid().ToString());
                image.SetAbsolutePosition(0, 0);
                PdfAppearance app = pdfStamper.GetOverContent(1).CreateAppearance(Convert.ToSingle(image.Width * 0.5), Convert.ToSingle(image.Height * 0.5));
                image.ScalePercent(50);
                app.AddImage(image);
                pdfStamp.SetAppearance(PdfName.N, app);
                pdfStamp.SetPage();
                pdfStamp.Flags = PdfAnnotation.FLAGS_PRINT;
                pdfStamper.AddAnnotation(pdfStamp, 1);
            }


            pdfStamper.Close();
            pdfReader.Close();
            File.Replace(newFile, oldFile, @"backup.pdf.bac");

            Console.WriteLine("Pdf modificado con exito, se ha guardado un backup de la versión anterior ");
            //axAcroPDF1.src = "C:\\Users\\Denisse\\Desktop\\prototipos\\prot2_ReconocerTexto\\prot2_ReconocerTexto\\bin\\Debug\\ejemploOK.pdf";
        }
        public string GenerateInvestorDocument(InvestorInfo investorInfo)
        {
            string fullName = string.Concat(investorInfo.FirstName, " ", investorInfo.LastName);

            string filePath = @"Template_Investor\";

            string fileNameExisting = @"TemplateInvestor.pdf";
            string fileNameNew      = @"InvestorContract_" + fullName.Replace(" ", "").Trim() + ".pdf";

            string fullNewPath      = filePath + fileNameNew;
            string fullExistingPath = filePath + fileNameExisting;

            using (var existingFileStream = new FileStream(fullExistingPath, FileMode.Open))

                using (var newFileStream = new FileStream(fullNewPath, FileMode.Create))
                {
                    // Open existing PDF
                    var pdfReader = new PdfReader(existingFileStream);

                    // PdfStamper, which will create
                    var stamper = new PdfStamper(pdfReader, newFileStream);

                    AcroFields fields = stamper.AcroFields;
                    fields.SetField("FULLNAME", fullName);
                    fields.SetField("DOCNUMBER", investorInfo.DocumentNumber);
                    fields.SetField("RUCNUMBER", investorInfo.RUCNumber);
                    fields.SetField("FULLADDRESS", investorInfo.FullAddress);
                    fields.SetField("SIGNATUREFULLNAME", fullName);
                    fields.SetField("SIGNATUREDOCNUMBER", investorInfo.DocumentNumber);
                    fields.SetField("SIGNATURERUCNUMBER", investorInfo.RUCNumber);

                    // "Flatten" the form so it wont be editable/usable anymore
                    stamper.FormFlattening = true;

                    stamper.Close();
                    pdfReader.Close();

                    //return new FileStreamResult(newFileStream, "application/pdf");
                    return(fileNameNew);
                }
        }
        public ActionResult Index(PrescricaoDataModel model)
        {
            // Guarantees that the "App_Data" folder exists.
            if (!Directory.Exists(StorageMock.AppDataPath))
            {
                Directory.CreateDirectory(StorageMock.AppDataPath);
            }
            var filename = Guid.NewGuid() + ".pdf";
            var userFile = Path.Combine(StorageMock.AppDataPath, filename);

            using (var stream = new FileStream(userFile, FileMode.OpenOrCreate)) {
                // PdfGeneration.ReceitaSimples(), to see how the custom sample pdf is generated.
                var content = PdfGeneration.ReceitaSimples(model.Name, model.Crm, model.CrmUf);

                var reader  = new PdfReader(content);
                var stamper = new PdfStamper(reader, stream);

                // REQUIRED!!!
                // Add all the required receita simples metadata,
                // when value is not specified it uses empty strings.
                var infos = new Hashtable
                {
                    { DocumentType.PrescricaoMedicamento.GetValue(), "Prescrição de medicamento" },
                    { FieldName.Crm.GetValue(), model.Crm },
                    { FieldName.CrmUF.GetValue(), model.CrmUf },
                    { FieldName.CrmEspecialidade.GetValue(), "" },
                    { FieldName.Crf.GetValue(), "" },
                    { FieldName.CrfUF.GetValue(), "" },
                    { FieldName.CrfEspecialidade.GetValue(), "" }
                };

                // Add metadata to pdf
                stamper.MoreInfo = infos;
                stamper.Close();
                reader.Close();
            }
            return(RedirectToAction("Start", new SignatureStartModel()
            {
                UserFile = filename.Replace(".", "_")
            }));
        }
예제 #18
0
        public void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, System.Drawing.Point point)
        {
            //variables
            string pathin  = inputPdfPath;
            string pathout = outputPdfPath;

            //create PdfReader object to read from the existing document
            PdfReader reader = new PdfReader(pathin);

            {
                //create PdfStamper object to write to get the pages from reader
                PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create));
                {
                    //select two pages from the original document
                    reader.SelectPages("1-2");

                    //gettins the page size in order to substract from the iTextSharp coordinates
                    var pageSize = reader.GetPageSize(1);

                    // PdfContentByte from stamper to add content to the pages over the original content
                    PdfContentByte pbover = stamper.GetOverContent(1);

                    //add content to the page using ColumnText
                    //iTextSharp.text.Font font = new iTextSharp.text.Font();
                    iTextSharp.text.Font font = FontFactory.GetFont("Arial", 30, Font.BOLD, new BaseColor(125, 88, 15));
                    // font.Size = 25;



                    //setting up the X and Y coordinates of the document
                    int x = point.X;
                    int y = point.Y;

                    x = (int)(pageSize.Width - x);
                    y = (int)(pageSize.Height - y);

                    ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
                } stamper.Close();
            }
            reader.Close();
        }
예제 #19
0
        private static void fillAlmRes(string FilePath, string TemplatePath, int anio, int mes)
        {
            PdfReader  reader  = null;
            PdfStamper stamper = null;

            try
            {
                reader  = new PdfReader(TemplatePath);
                stamper = new PdfStamper(reader, new FileStream(FilePath, FileMode.Create));

                AcroFields fields = stamper.AcroFields;

                // set form fields

                CultureInfo ci       = new CultureInfo("es-MX");
                DateTime    fechaRpt = DateTime.Today;
                fields.SetField("Fecha", fechaRpt.ToString("dd \\de MMMM \\de yyyy", ci));

                DateTime fechaMes = new DateTime(anio, mes, 1);
                fields.SetField("mes", fechaMes.ToString("MMMM-yy", ci).ToUpper());

                DataTable dt = new DocAlmacenResumen().getData(anio, mes);
                DataRow   dr = dt.Rows[0];
                fields.SetField("saldoIni", Convert.ToDouble(dr["saldoIni"]).ToString("N0"));
                fields.SetField("entradas", Convert.ToDouble(dr["entradas"]).ToString("N0"));
                fields.SetField("salidas", Convert.ToDouble(dr["salidas"]).ToString("N0"));
                fields.SetField("saldo", Convert.ToDouble(dr["saldoFin"]).ToString("N0"));
                fields.SetField("piezasTot", Convert.ToDouble(dr["saldoTot"]).ToString("N0"));

                stamper.FormFlattening = true;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                stamper.Close();
                reader.Close();
            }
        }
예제 #20
0
        private static byte[] AddPdfSignatureField(byte[] src,
                                                   ICollection <Org.BouncyCastle.X509.X509Certificate> chain, X509Certificate2 pk,
                                                   string digestAlgorithm, CryptoStandard subfilter,
                                                   string reason, string location,
                                                   ICollection <ICrlClient> crlList,
                                                   IOcspClient ocspClient,
                                                   ITSAClient tsaClient,
                                                   int estimatedSize, int page, Rectangle rectangle, string signatureFieldName)
        {
            // Creating the reader and the stamper
            PdfReader  reader  = null;
            PdfStamper stamper = null;
            var        os      = new MemoryStream();

            try
            {
                reader  = new PdfReader(src);
                stamper = PdfStamper.CreateSignature(reader, os, '\0');
                // Creating the appearance
                var appearance = stamper.SignatureAppearance;
                appearance.Reason   = reason;
                appearance.Location = location;
                appearance.SetVisibleSignature(rectangle, page, signatureFieldName);
                // Creating the signature
                IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
                MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize,
                                           subfilter);
                return(os.ToArray());
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (stamper != null)
                {
                    stamper.Close();
                }
            }
        }
예제 #21
0
        /// <summary>
        /// Simulates a green card
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public byte[] GetDemoPDF(SDK.DTO.GreenCard.Car.GreenCardRequestInfo request)
        {
            string pdfSourcePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/cartevertetemplate.pdf");

            using (var pdfReader = new PdfReader(pdfSourcePath))
            {
                var memoryStream  = new MemoryStream();
                var pdfStamper    = new PdfStamper(pdfReader, memoryStream);
                var pdfFormFields = pdfStamper.AcroFields;


                pdfFormFields.SetField(CarteVerteSimulationFields.LicencePlate, request.LicencePlate);
                pdfFormFields.SetField(CarteVerteSimulationFields.VIN, request.VIN);

                string infos = "";
                if (request.RequestDetails.VehicleOwner.IsCompany)
                {
                    infos = $@"CREATION  Client COMPANY : {request.RequestDetails.VehicleOwner.Company.Name} 

Vehicule : {request.RequestDetails.CarDetails.Make} {request.RequestDetails.CarDetails.Model}

Généré le {DateTime.UtcNow} (UTC)
";
                }
                else
                {
                    infos = $@"CREATION  Client : {request.RequestDetails.VehicleOwner.Person.FirstName} {request.RequestDetails.VehicleOwner.Person.LastName} 

Vehicule : {request.RequestDetails.CarDetails.Make} {request.RequestDetails.CarDetails.Model}

Généré le {DateTime.UtcNow} (UTC)
";
                }
                pdfFormFields.SetField(CarteVerteSimulationFields.infos, infos);//infos

                pdfStamper.FormFlattening = false;
                pdfStamper.Close();

                return(memoryStream.ToArray());
            }
        }
예제 #22
0
        public MemoryStream CreateCompanyRegistrationDocument(string fileName, string companyName, string companyNumber)
        {
            using (var stumpedDocStream = new MemoryStream())
            {
                PdfReader  reader  = null;
                PdfStamper stamper = null;
                try
                {
                    reader  = new PdfReader(fileName);
                    stamper = new PdfStamper(reader, stumpedDocStream);
                    var bf   = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    var font = new Font(bf, textSize);
                    for (var pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
                    {
                        var canvas = stamper.GetOverContent(pageNumber);
                        canvas.SetFontAndSize(bf, textSize);
                        RenderPhase(pageNumber, companyNameLocations, canvas, companyName, font);
                        RenderPhase(pageNumber, companyNumberLocations, canvas, companyNumber, font);
                    }
                }
                finally
                {
                    try
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                    finally
                    {
                        if (stamper != null)
                        {
                            stamper.Close();
                        }
                    }
                }

                return(new MemoryStream(EncryptPdf(stumpedDocStream.ToArray())));
            }
        }
예제 #23
0
        public void FlatteningRadioButtonFieldsTest()
        {
            String     outFile = OUT_FOLDER + "flatteningRadioButtonFieldsTest.pdf";
            FileStream file    = new FileStream(outFile, FileMode.Create);

            PdfReader reader = new PdfReader(new FileStream(TEST_RESOURCES_PATH + "radios_src.pdf", FileMode.Open));

            PdfStamper stamper    = new PdfStamper(reader, file);
            AcroFields acroFields = stamper.AcroFields;

            acroFields.SetField("radiogroup", "1");
            stamper.Close();

            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(outFile, TEST_RESOURCES_PATH + "cmp_flatteningRadioButtonFieldsTest.pdf", OUT_FOLDER, "diff_");

            if (errorMessage != null)
            {
                Assert.Fail(errorMessage);
            }
        }
예제 #24
0
        /// <summary>
        /// Test for BadPasswordException while opening and editing pdf file of current testhelper job.
        /// File gets opened with PDFReader by using the Password (Leave out Password, to test without Password).
        /// </summary>>
        /// <param name="testFile">PDF test file</param>
        /// <param name="canOpen">Set true if opening should be authorized, else false</param>
        /// <param name="canEdit">Set true if editing should be authorized, else false</param>
        /// /// <param name="password">Password to be tested on file (Leave out, to test without Password)</param>
        private static void PasswordTest(string testFile, bool canOpen, bool canEdit, string password)
        {
            //Testing Opening
            Assert.That(() => { var reader = new PdfReader(testFile, Encoding.Default.GetBytes(password)); reader.Close(); },
                        canOpen ? !Throws.Exception.TypeOf <BadPasswordException>() : Throws.Exception.TypeOf <BadPasswordException>());

            //Testing Editing
            Assert.That(() =>
            {
                var r = new PdfReader(testFile, Encoding.Default.GetBytes(password));
                FileStream f;
                string file = testFile + "PasswordTestCopy.pdf";
                using (f = new FileStream(file, FileMode.Create, FileAccess.Write))
                {
                    var s = new PdfStamper(r, f);
                    s.Close();
                    f.Close();
                }
                File.Delete(file);
            }, canEdit ? !Throws.Exception.TypeOf <BadPasswordException>() : Throws.Exception.TypeOf <BadPasswordException>());
        }
예제 #25
0
        /// <summary>
        /// Accepts a list of MyItem objects and draws a colored rectangle for each
        /// item in the list.
        /// </summary>
        /// <param name="items">The list of items</param>
        /// <param name="reader">The reader instance that has access to the PDF file</param>
        /// <param name="pageNum">The page number of the page that needs to be parsed</param>
        /// <param name="destination">The path for the altered PDF file</param>
        public void Highlight(List <MyItem> items, PdfReader reader, int pageNum, String destination)
        {
            PdfStamper     stamper = new PdfStamper(reader, new FileStream(destination, FileMode.Create));
            PdfContentByte over    = stamper.GetOverContent(pageNum);

            foreach (MyItem item in items)
            {
                if (item.Color == null)
                {
                    continue;
                }
                over.SaveState();
                over.SetColorStroke(item.Color);
                over.SetLineWidth(2);
                Rectangle r = item.Rectangle;
                over.Rectangle(r.Left, r.Bottom, r.Width, r.Height);
                over.Stroke();
                over.RestoreState();
            }
            stamper.Close();
        }
예제 #26
0
        public void SpecialCharactersInAcroFieldTest()
        {
            String     outFile = OUT_FOLDER + "specialCharactersInAcroFieldTest.pdf";
            FileStream file    = new FileStream(outFile, FileMode.Create);

            PdfReader reader = new PdfReader(new FileStream(TEST_RESOURCES_PATH + "HelveticaFont.pdf", FileMode.Open));

            PdfStamper stamper    = new PdfStamper(reader, file);
            AcroFields acroFields = stamper.AcroFields;

            acroFields.SetField("Mitarbeiter", "öäü߀@");
            stamper.Close();

            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(outFile, TEST_RESOURCES_PATH + "cmp_specialCharactersInAcroFieldTest.pdf", OUT_FOLDER, "diff_");

            if (errorMessage != null)
            {
                Assert.Fail(errorMessage);
            }
        }
예제 #27
0
        public void TestFreeTextRecangleBBoxInteraction()
        {
            String file = "freeTextRectangleBBoxInteraction.pdf";

            PdfReader  pdfReader  = new PdfReader(RESOURCES_FOLDER + file);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(OUTPUT_FOLDER + file, FileMode.Create));

            pdfStamper.FormFlattening     = true;
            pdfStamper.FreeTextFlattening = true;
            pdfStamper.Close();
            pdfReader.Close();
            // compare
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, RESOURCES_FOLDER + "cmp_" + file,
                                                                    OUTPUT_FOLDER, "diff");

            if (errorMessage != null)
            {
                Assert.Fail(errorMessage);
            }
        }
예제 #28
0
        private MemoryStream GeneratePdf(string fileName, Dictionary <string, string> formFields)
        {
            string       formFile     = HttpContext.Server.MapPath("~/Content/Forms/" + fileName);
            PdfReader    reader       = new PdfReader(formFile);
            MemoryStream memoryStream = new MemoryStream();
            PdfStamper   stamper      = new PdfStamper(reader, memoryStream);
            AcroFields   fields       = stamper.AcroFields;

            // set form fields
            foreach (KeyValuePair <string, string> formField in formFields)
            {
                fields.SetField(formField.Key, formField.Value);
            }

            stamper.FormFlattening = true;
            // release file
            stamper.Close();
            reader.Close();

            return(memoryStream);
        }
예제 #29
0
        public void ManipulatePdf(string src, string dest)
        {
            PdfReader reader = new PdfReader(src);
            // We assume that there's a single large picture on the first page
            PdfDictionary page      = reader.GetPageN(1);
            PdfDictionary resources = page.GetAsDict(PdfName.RESOURCES);
            PdfDictionary xobjects  = resources.GetAsDict(PdfName.XOBJECT);

            Dictionary <PdfName, PdfObject> .KeyCollection.Enumerator enumerator = xobjects.Keys.GetEnumerator();
            enumerator.MoveNext();
            PdfName imgName = enumerator.Current;
            Image   img     = Image.GetInstance((PRIndirectReference)xobjects.GetAsIndirectObject(imgName));

            img.SetAbsolutePosition(0, 0);
            img.ScaleAbsolute(reader.GetPageSize(1));
            PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));

            stamper.GetOverContent(1).AddImage(img);
            stamper.Close();
            reader.Close();
        }
예제 #30
0
        public static Stream GeneratePDF(Stream modelFile, Dictionary <string, string> contents)
        {
            BaseFont  baseFont = BaseFont.CreateFont("font.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            PdfReader reader   = new PdfReader(modelFile);

            MemoryStream stream = new MemoryStream();
            PdfStamper   stamp  = new PdfStamper(reader, stream);
            AcroFields   form   = stamp.AcroFields;

            stamp.FormFlattening = true;

            foreach (KeyValuePair <string, string> parameter in contents)
            {
                form.SetFieldProperty(parameter.Key, "textfont", baseFont, null);
                form.SetField(parameter.Key, parameter.Value);
            }

            stamp.Close();
            reader.Close();
            return(stream);
        }
예제 #31
0
 /**
  * Processes a properly tagged PDF form.
  * @param reader the PdfReader instance holding the PDF
  * @throws IOException
  * @throws DocumentException 
  */
 virtual public void Process(PdfReader reader, Stream os) {
     int n = reader.NumberOfPages;
     // getting the root dictionary
     PdfDictionary catalog = reader.Catalog;
     // flattening means: remove AcroForm
     catalog.Remove(PdfName.ACROFORM);
     // read the structure and create a parser
     StructureItems items = new StructureItems(reader);
     MCParser parser = new MCParser(items);
     // loop over all pages
     for(int i = 1; i <= n; i++) {
         // make one stream of a content stream array
         reader.SetPageContent(i, reader.GetPageContent(i));
         // parse page
         parser.Parse(reader.GetPageN(i), reader.GetPageOrigRef(i));
     }
     reader.RemoveUnusedObjects();
     // create flattened file
     PdfStamper stamper = new PdfStamper(reader, os);
     items.WriteParentTree(stamper.Writer);
     stamper.Close();
 }