Close() public method

public Close ( ) : void
return void
コード例 #1
0
ファイル: Class1.cs プロジェクト: hagi07/Checador
        //Permite cargar en un PDF información en los formularios preestablecidos.
        public void llenarFormulario(string archivoOrigen, string archivoFinal, string dato)
        {
            //Establece el archivo de entrada y de salida.
            string pdfTemplate = archivoOrigen;
            string newFile = archivoFinal;

            PdfReader pdfReader = new PdfReader(pdfTemplate);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.OpenOrCreate));

            AcroFields pdfFormFields = pdfStamper.AcroFields;

            // Asigna los campos
            pdfFormFields.SetField("Colono", dato);

            //Muestra mensaje.
            //MessageBox.Show(sTmp, "Terminado");

            // Cambia la propiedad para que no se pueda editar el PDF
            pdfStamper.FormFlattening = true;
            pdfStamper.FreeTextFlattening = true;
            pdfStamper.Writer.CloseStream = true;
            pdfStamper.Close();

            // Cierra el PDF
            pdfStamper.Close();
            pdfReader.Close();
        }
コード例 #2
0
        // samples taken from
        // http://www.c-sharpcorner.com/uploadfile/scottlysle/pdfgenerator_cs06162007023347am/pdfgenerator_cs.aspx
        // http://blog.codecentric.de/en/2010/08/pdf-generation-with-itext/
        public string SetFields(string PathSource, string PathTarget, System.Object myFields)
        {
            try
            {
                GeneXus.Utils.GXProperties Fields = (GeneXus.Utils.GXProperties)myFields;
                // create a new PDF reader based on the PDF template document
                iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(PathSource);

                iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(pdfReader, new System.IO.FileStream(PathTarget, System.IO.FileMode.Create));

                GeneXus.Utils.GxKeyValuePair item = Fields.GetFirst();
                while (item != null)
                {
                    pdfStamper.AcroFields.SetField(item.Key, item.Value);
                    item = Fields.GetNext();
                }

                // flatten the form to remove editting options, set it to false to leave the form open to subsequent manual edits
                pdfStamper.FormFlattening = false;

                // close the pdf
                pdfStamper.Close();
                pdfReader.Close();
                return("");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
コード例 #3
0
        public virtual void TestFlattening()
        {
            const string INPUT_FOLDER = RESOURCES_FOLDER + "input/";
            const string CMP_FOLDER = RESOURCES_FOLDER + "cmp/";
            if (File.Exists(INPUT_FOLDER))
                Assert.Fail("Input folder can't be found (" + INPUT_FOLDER + ")");

            Directory.CreateDirectory(OUTPUT_FOLDER);

            String[] files = Directory.GetFiles(INPUT_FOLDER, "*.pdf");

            foreach (String file in files)
            {
                // flatten fields
                PdfReader reader = new PdfReader(file);
                PdfStamper stamper = new PdfStamper(reader, new FileStream(OUTPUT_FOLDER + Path.GetFileName(file), FileMode.Create));
                stamper.FormFlattening = true;
                stamper.Close();

                // compare
                CompareTool compareTool = new CompareTool();
                String errorMessage = compareTool.Compare(OUTPUT_FOLDER + Path.GetFileName(file), CMP_FOLDER + Path.GetFileName(file), OUTPUT_FOLDER, "diff");
                if (errorMessage != null)
                {
                    Assert.Fail(errorMessage);
                }
            }
        }
コード例 #4
0
 /// <summary>
 /// Fills out and flattens a form with the name, company and country.
 /// </summary>
 /// <param name="src"> the path to the original form </param>
 /// <param name="dest"> the path to the filled out form </param>
 public void ManipulatePdf(String src, String dest)
 {
     PdfReader reader = new PdfReader(src);
     PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)); // create?
     int n = reader.NumberOfPages;
     Rectangle pagesize;
     for (int i = 1; i <= n; i++)
     {
         PdfContentByte under = stamper.GetUnderContent(i);
         pagesize = reader.GetPageSize(i);
         float x = (pagesize.Left + pagesize.Right)/2;
         float y = (pagesize.Bottom + pagesize.Top)/2;
         PdfGState gs = new PdfGState();
         gs.FillOpacity = 0.3f;
         under.SaveState();
         under.SetGState(gs);
         under.SetRGBColorFill(200, 200, 0);
         ColumnText.ShowTextAligned(under, Element.ALIGN_CENTER,
             new Phrase("Watermark", new Font(Font.FontFamily.HELVETICA, 120)),
             x, y, 45);
         under.RestoreState();
     }
     stamper.Close();
     reader.Close();
 }
コード例 #5
0
        internal Boolean DecryptFile(
            string inputFile,
            string outputFile,
            IEnumerable<string> userPasswords)
        {
            foreach (var pwd in userPasswords)
            {
                try
                {
                    using (var reader = new PdfReader(inputFile, new ASCIIEncoding().GetBytes(pwd)))
                    {
                        reader.GetType().Field("encrypted").SetValue(reader, false);

                        using (var outStream = File.OpenWrite(outputFile))
                        {
                            using (var stamper = new PdfStamper(reader, outStream))
                            {
                                stamper.Close();
                            }
                        }
                    }

                    return true;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat(ex, "Error trying to decrypt file {0}: {1}", inputFile, ex.Message);
                }
            }
            return false;

        }
コード例 #6
0
        public virtual void ImprimirComprobante(long turnoId)
        {
            var turno = SessionFactory.GetCurrentSession().Load<Turno>(turnoId);
            //Valido que sea del paciente actual
            if (turno.Paciente.Id != User.As<Paciente>().Id)
                throw new SecurityException("El usuario actual no es al que se le otorgó el turno.");

            // Read the template
            var reader = new PdfReader(Server.MapPath("~/Reports/ComprobanteTurno.pdf"));

            // Writes the modified template to http response
            this.HttpContext.Response.Clear();
            this.HttpContext.Response.ContentType = "application/pdf";
            var stamper = new PdfStamper(reader, this.HttpContext.Response.OutputStream);

            // Retrieve the PDF form fields defined in the template
            var form = stamper.AcroFields;

            // Set values for the fields
            form.SetField("Fecha", turno.FechaTurno.ToString());
            form.SetField("Profesional", turno.Profesional.Persona.NombreCompleto);
            form.SetField("Especialidad", turno.Especialidad.Nombre);
            form.SetField("Paciente", turno.Paciente.Persona.NombreCompleto);
            form.SetField("Consultorio", turno.Consultorio.Nombre);

            // Setting this to true to make the document read-only
            stamper.FormFlattening = true;

            //Close the stamper instance
            stamper.Close();
        }
コード例 #7
0
        /// <summary>
        /// uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf, called instead of PdfReader.open
        /// </summary>
        public static PdfDocument Open(MemoryStream sourceStream, string password = null)
        {
            PdfDocument outDoc;
            sourceStream.Position = 0;
            var mode = PdfDocumentOpenMode.Modify;

            try
            {
                outDoc = PdfReader.Open(sourceStream, mode);
            }
            catch (PdfReaderException)
            {
                sourceStream.Position = 0;
                var outputStream = new MemoryStream();

                var reader = password == null ?
                    new TextSharp.PdfReader(sourceStream) :
                    new TextSharp.PdfReader(sourceStream, Encoding.UTF8.GetBytes(password));

                var pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream) { FormFlattening = true };
                pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4);
                pdfStamper.Writer.CloseStream = false;
                pdfStamper.Close();

                outDoc = PdfReader.Open(outputStream, mode);
            }

            return outDoc;
        }
コード例 #8
0
        public static void WritePDF(string outFilename, Dictionary<string, string> keys)
        {
            using (var existingFileStream = new FileStream(DefaultTemplatePath, FileMode.Open))
            using (var newFileStream = new FileStream(outFilename, FileMode.Create))
            {
                var pdfReader = new PdfReader(existingFileStream);
                var stamper = new PdfStamper(pdfReader, newFileStream);

                try
                {
                    var form = stamper.AcroFields;
                    var fieldKeys = form.Fields.Keys;
                    //File.WriteAllLines(@"fields.txt", fieldKeys.OfType<string>().ToArray());
                    foreach (string fieldKey in fieldKeys)
                    {
                        if (keys.ContainsKey(fieldKey))
                        {
                            form.SetField(fieldKey, keys[fieldKey]);
                        }
                    }
                    stamper.FormFlattening = true;
                }
                finally
                {
                    stamper.Close();
                    pdfReader.Close();
                }
            }
        }
コード例 #9
0
 public bool WatermarkPDF_SN(string SourcePdfPath, string OutputPdfPath, string WatermarkPath, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg)
 {
     try
     {
         PdfReader reader = new PdfReader(SourcePdfPath);
         PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create));
         int n = reader.NumberOfPages;
         int i = 0;
         PdfContentByte under;
         iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath);
         im.SetAbsolutePosition(positionX, positionY);
         im.ScaleAbsolute(WatermarkWidth, WatermarkHeight);
         while (i < n)
         {
             i++;
             under = stamp.GetUnderContent(i);
             under.AddImage(im, true);
         }
         stamp.Close();
         reader.Close();
     }
     catch (Exception ex)
     {
         msg = ex.Message;
         return false;
     }
     msg = "��ˮӡ�ɹ���";
     return true;
 }
コード例 #10
0
ファイル: Notes iTextSharp.cs プロジェクト: nofuture-git/31g
        public static void CropPdf()
        {
            var xll    = 200;
            var yll    = 170;
            var w      = 800;
            var h      = 800;
            var reader = new iTextSharp.text.pdf.PdfReader(@"C:\Projects\31g\trunk\temp\pdf\20140208110036_20.pdf");
            var n      = reader.NumberOfPages;

            iTextSharp.text.pdf.PdfDictionary pageDict;

            var pfgRect = new iTextSharp.text.pdf.PdfRectangle(xll, yll, w, h);

            for (var i = 1; i <= n; i++)
            {
                pageDict = reader.GetPageN(i);
                pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, pfgRect);
            }

            var stamper = new iTextSharp.text.pdf.PdfStamper(reader,
                                                             new System.IO.FileStream(string.Format(@"C:\Projects\31g\trunk\Notes\misc\Maps\Europe_565BCE.pdf", xll, yll, w, h), FileMode.Create));

            stamper.Close();
            reader.Close();
        }
コード例 #11
0
        public bool WatermarkPDF_SW(string SourcePdfPath, string OutputPdfPath, string WatermarkImageUrl, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg)
        {
            try
            {
                PdfReader reader = new PdfReader(SourcePdfPath);
                PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create));
                int n = reader.NumberOfPages;
                int i = 0;
                PdfContentByte under;
                WatermarkWidth = WatermarkWidth / n;
                //����ط�Ҫע�⣬�Ǹ���ҳ������̬����ͼƬ��ַ���м�ҳ�ͼ��ؼ�ҳ��ͼƬ
                string WatermarkPath = Server.MapPath(Request.ApplicationPath + "/HTProject/Pages/Images/��ͬ��������" + n + "/");
                string WatermarkPath2 = "";
                while (i < n)
                {
                    i++;
                    WatermarkPath2 = WatermarkPath + i + ".gif";
                    iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath2);
                    im.SetAbsolutePosition(positionX, positionY);
                    im.ScaleAbsolute(WatermarkWidth, WatermarkHeight);

                    under = stamp.GetUnderContent(i);
                    under.AddImage(im, true);
                }
                stamp.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }
            msg = "��ˮӡ�ɹ���";
            return true;
        }
コード例 #12
0
        /// <summary>
        /// Compress a pdf
        /// </summary>
        /// <param name="base64Pdf">A small model to hold a base64 encoded pdf object { "content" : "somebase64" }</param>
        /// <returns>{ "content" : "smallerBase64" }</returns>
        public IHttpActionResult Post(Base64Pdf base64Pdf)
        {
            try
            {
                if (base64Pdf.data == null)
                    return BadRequest("Check supplied pdf model");

                byte[] data = Convert.FromBase64String(base64Pdf.data);

                //Compress
                byte[] compressedData;
                using (var memStream = new MemoryStream())
                {
                    var reader = new PdfReader(data);
                    var stamper = new PdfStamper(reader, memStream, PdfWriter.VERSION_1_4);
                    var pageNum = reader.NumberOfPages;

                    for (var i = 1; i <= pageNum; i++)
                        reader.SetPageContent(i, reader.GetPageContent(i));

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

                    compressedData = memStream.ToArray();
                }
                var compressedBase64 = Convert.ToBase64String(compressedData);

                return Json(new Base64Pdf { data = compressedBase64 });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
コード例 #13
0
ファイル: pdflib.cs プロジェクト: Zawulon/jseverywhere
        private string SaveTest(string pdfTemplate, string pdfXmldata, string result)
        {
            string src = @"tmpl\PIT-36_2012.pdf";
            string data = @"tmpl\PIT-36.xml";
            string res = @"tmpl\PIT-36_2012_result.pdf";

            src = pdfTemplate;
            data = pdfXmldata;
            res = result;

           
            using (FileStream existingPdf = new FileStream(src, FileMode.Open))
            using (FileStream sourceXml = new FileStream(data, FileMode.Open))
            using (FileStream newPdf = new FileStream(res, FileMode.Create))
            {
                // Open existing PDF  
                PdfReader pdfReader = new PdfReader(existingPdf);
                PdfReader.unethicalreading = true;

                // PdfStamper, which will create  
                PdfStamper stamper = new PdfStamper(pdfReader, newPdf, '0', true);
                stamper.AcroFields.Xfa.FillXfaForm(sourceXml);

                stamper.Close();
                pdfReader.Close();
            }
            return res;
        }
コード例 #14
0
    public void setPDF()
    {
        string imgpath       = Server.MapPath("~/Sign/21.jpg");
        string pdfpath       = Server.MapPath("~/TemplateStore/Forms/Nf packet.pdf");
        string pdfpathourput = Server.MapPath("~/TemplateStore/Forms/Demo.pdf");

        using (Stream inputPdfStream = new FileStream(pdfpath, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (Stream inputImageStream = new FileStream(imgpath, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream outputPdfStream = new FileStream(pdfpathourput, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    var reader = new iTextSharp.text.pdf.PdfReader(inputPdfStream);

                    int val = reader.NumberOfPages;

                    var stamper = new iTextSharp.text.pdf.PdfStamper(reader, outputPdfStream);

                    var pdfContentByte = stamper.GetOverContent(1);

                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);

                    image.SetAbsolutePosition(759f, 459f);

                    pdfContentByte.AddImage(image);
                    stamper.Close();
                }
    }
コード例 #15
0
        /// <summary>
        /// uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf, called instead of PdfReader.open
        /// </summary>
        static public PdfDocument Open(MemoryStream sourceStream, string password = null)
        {
            PdfDocument outDoc;

            sourceStream.Position = 0;
            var mode = PdfDocumentOpenMode.Modify;

            try
            {
                outDoc = PdfReader.Open(sourceStream, mode);
            }
            catch (PdfReaderException)
            {
                sourceStream.Position = 0;
                var outputStream = new MemoryStream();

                var reader = password == null ?
                             new TextSharp.PdfReader(sourceStream) :
                             new TextSharp.PdfReader(sourceStream, Encoding.UTF8.GetBytes(password));

                var pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream)
                {
                    FormFlattening = true
                };
                pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4);
                pdfStamper.Writer.CloseStream = false;
                pdfStamper.Close();

                outDoc = PdfReader.Open(outputStream, mode);
            }

            return(outDoc);
        }
コード例 #16
0
ファイル: WritePdf.cs プロジェクト: half-ogre/chardown
        public static void WritePdf(Character character, string pathToPdf)
        {
            using (Stream stream = typeof(Functions).Assembly.GetManifestResourceStream("CharDown.CharacterSheet.pdf"))
            {
                var pdfReader = new PdfReader(stream);
                var pdfStamper = new PdfStamper(pdfReader, new FileStream(pathToPdf, FileMode.Create));
                var fields = pdfStamper.AcroFields;

                fields.SetField("CharacterName", character.CharacterName);

                fields.SetField("STR", character.Strength);
                fields.SetField("STRmod", character.StrengthModifier);
                fields.SetField("DEX", character.Dexterity);
                fields.SetField("DEXmod ", character.DexterityModifier);
                fields.SetField("CON", character.Constitution);
                fields.SetField("CONmod", character.ConstitutionModifier);
                fields.SetField("INT", character.Intelligence);
                fields.SetField("INTmod", character.IntelligenceModifier);
                fields.SetField("WIS", character.Wisdom);
                fields.SetField("WISmod", character.WisdomModifier);
                fields.SetField("CHA", character.Charisma);
                fields.SetField("CHamod", character.CharismaModifier);

                pdfStamper.Close();
            }
        }
コード例 #17
0
        public byte[] FillIRS941Form(ReportPayrollCompanyTotal payrollData)
        {
            string iRS941FormTemplate = HttpContext.Current.Server.MapPath("~/FormTemplates/IRS2015Form941.pdf");
            byte[] formResults;

            using (PdfReader pdfReader = new PdfReader(iRS941FormTemplate))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (PdfStamper pdfStamper = new PdfStamper(pdfReader, ms))
                    {
                        AcroFields pdfFormFields = pdfStamper.AcroFields;
                        var s = pdfFormFields.GetSignatureNames();
                        var e = pdfFormFields.GetBlankSignatureNames();

                        pdfFormFields.SetField("f1_10_0_", "Suitland Road Baptist Church");

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

                    formResults = ms.GetBuffer();
                }
            }

            return formResults;
        }
コード例 #18
0
ファイル: PDFForm.cs プロジェクト: PavelElis/PGRLF.MainWeb
        public void FillForm(
            Dictionary<string, string> items,
            Stream formStream)
        {
            PdfStamper pdfStamper = new PdfStamper(pdfReader, formStream);
            AcroFields pdfFormFields = pdfStamper.AcroFields;
            BaseFont arialBaseFont;
            string arialFontPath;
            try
            {
                arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
                arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            }
            catch (IOException)
            {
                arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIAL.TTF");
                arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            }

            pdfFormFields.AddSubstitutionFont(arialBaseFont);
            foreach (KeyValuePair<string, string> item in items)
            {
                pdfFormFields.SetFieldProperty(item.Key, "textfont", arialBaseFont, null);
                if (item.Value!=null) pdfFormFields.SetField(item.Key, item.Value);
            }
            pdfStamper.FormFlattening = false;
            pdfStamper.Close();
        }
コード例 #19
0
        public string AddSignature(string PathSource, string PathTarget, string CertPath, string CertPass, int lx = 100, int ly = 100, int ux = 250, int uy = 150, int page = 1, bool Visible = true)
        {
            try
            {
                Org.BouncyCastle.Crypto.AsymmetricKeyParameter Akp   = null;
                Org.BouncyCastle.X509.X509Certificate[]        Chain = null;

                string alias = null;
                Org.BouncyCastle.Pkcs.Pkcs12Store pk12;


                pk12 = new Org.BouncyCastle.Pkcs.Pkcs12Store(new System.IO.FileStream(CertPath, System.IO.FileMode.Open, System.IO.FileAccess.Read), CertPass.ToCharArray());

                IEnumerable aliases = pk12.Aliases;
                foreach (string aliasTemp in aliases)
                {
                    alias = aliasTemp;
                    if (pk12.IsKeyEntry(alias))
                    {
                        break;
                    }
                }

                Akp = pk12.GetKey(alias).Key;
                Org.BouncyCastle.Pkcs.X509CertificateEntry[] ce = pk12.GetCertificateChain(alias);
                Chain = new Org.BouncyCastle.X509.X509Certificate[ce.Length];
                for (int k = 0; k < ce.Length; ++k)
                {
                    Chain[k] = ce[k].Certificate;
                }

                iTextSharp.text.pdf.PdfReader              reader = new iTextSharp.text.pdf.PdfReader(PathSource);
                iTextSharp.text.pdf.PdfStamper             st     = iTextSharp.text.pdf.PdfStamper.CreateSignature(reader, new System.IO.FileStream(PathTarget, System.IO.FileMode.Create, System.IO.FileAccess.Write), '\0', null, true);
                iTextSharp.text.pdf.PdfSignatureAppearance sap    = st.SignatureAppearance;

                if (Visible == true)
                {
                    page = (page <1 || page> reader.NumberOfPages) ? 1 : page;
                    sap.SetVisibleSignature(new iTextSharp.text.Rectangle(lx, ly, ux, uy), page, null);
                }

                sap.CertificationLevel = iTextSharp.text.pdf.PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;

                // digital signature - http://itextpdf.com/examples/iia.php?id=222

                IExternalSignature es = new PrivateKeySignature(Akp, "SHA-256"); // "BC"
                MakeSignature.SignDetached(sap, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);

                st.Close();
                return("");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
コード例 #20
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();
 }
コード例 #21
0
 public static void AddMetadataToExistingPdfFile(string filename, string json) {
     var reader = new PdfReader(filename);
     using (var outputFs = new FileStream(filename + "output.pdf", FileMode.Create)) {
         var stamper = new PdfStamper(reader, outputFs);
         var info = reader.Info;
         info.Add("HADocsOpenData", json);
         stamper.MoreInfo = info;
         stamper.Close();
     }
     reader.Close();
 }
コード例 #22
0
 public void ManipulatePdf(String src, String dest)
 {
     PdfReader reader = new PdfReader(src);
     PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
     Rectangle linkLocation = new Rectangle(523, 770, 559, 806);
     PdfDestination destination = new PdfDestination(PdfDestination.FIT);
     PdfAnnotation link = PdfAnnotation.CreateLink(stamper.Writer,
         linkLocation, PdfAnnotation.HIGHLIGHT_INVERT,
         3, destination);
     stamper.AddAnnotation(link, 1);
     stamper.Close();
 }
コード例 #23
0
        protected void Replace_Click(object sender, EventArgs e)
        {
            string    ReplacingVariable = txtReplace.Text;
            string    sourceFile        = "Source File Path";
            string    descFile          = "Destination File Path";
            PdfReader pReader           = new PdfReader(sourceFile);

            stamper = new iTextSharp.text.pdf.PdfStamper(pReader, new System.IO.FileStream(descFile, System.IO.FileMode.Create));
            PDFTextGetter("ExistingVariableinPDF", ReplacingVariable, StringComparison.CurrentCultureIgnoreCase, sourceFile, descFile);
            stamper.Close();
            pReader.Close();
        }
コード例 #24
0
ファイル: Notes iTextSharp.cs プロジェクト: nofuture-git/31g
        public static void RotatePdf()
        {
            var reader   = new iTextSharp.text.pdf.PdfReader(@"C:\Projects\31g\trunk\temp\pdf\Europe_565BCE.pdf");
            var pageDict = reader.GetPageN(1);

            pageDict.Put(iTextSharp.text.pdf.PdfName.ROTATE, new iTextSharp.text.pdf.PdfNumber(270));

            var stamper = new iTextSharp.text.pdf.PdfStamper(reader,
                                                             new System.IO.FileStream(@"C:\Projects\31g\trunk\Notes\misc\Maps\Europe_565BCE.pdf", FileMode.Create));

            stamper.Close();
            reader.Close();
        }
コード例 #25
0
ファイル: MainWindow.xaml.cs プロジェクト: oeai/medx
        public void thisRead(string formFile)
        {
            string newFile = "new_print.pdf";
               // FontFactory.Register("c:\\windows\\fonts\\arial.ttf");
            PdfReader reader = new PdfReader(formFile);
            PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
            AcroFields fields = stamper.AcroFields;

            fields.SetField("NumericField1", "121");
            fields.SetField("TextField2", "there");
            stamper.FormFlattening = false;
            stamper.Close();
            reader.Close();
        }
コード例 #26
0
ファイル: PDFHelper.cs プロジェクト: two4suited/FlyballStats
        public static string CreateStatCheatPDF1RacePerPage(string path, string filename, string templatePath, TournamentTeam tournamentTeam)
        {
            int count = 1;
            List<string> files = new List<string>();
            foreach (StatSheet statsheet in StatSheet.SetupStatSheet1RacePerPage(tournamentTeam))
            {
                string tempFileName = path + count.ToString() + "_" + filename;
                using (var existingFileStream = new FileStream(templatePath, FileMode.Open))
                using (var newFileStream = new FileStream(tempFileName, FileMode.Create))
                {
                    // Open existing PDF
                    var pdfReader = new PdfReader(existingFileStream);

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

                    af.SetField("Team", statsheet.Team);
                    af.SetField("Tournament", statsheet.Tournament);
                    af.SetField("Date", statsheet.Date);
                    af.SetField("Dog1", statsheet.Dog1);
                    af.SetField("Dog2", statsheet.Dog2);
                    af.SetField("Dog3", statsheet.Dog3);
                    af.SetField("Dog4", statsheet.Dog4);
                    af.SetField("Dog5", statsheet.Dog5);
                    af.SetField("Dog6", statsheet.Dog6);
                    af.SetField("RaceNumber", statsheet.RaceNumber1);
                    af.SetField("Lane", statsheet.Lane1);
                    af.SetField("Opponent", statsheet.Opponent1);

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

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

                count++;
                files.Add(tempFileName);
            }

            string mergeFileName = MergePdfs(files, path + filename);

            foreach (string file in files)
            {
                File.Delete(file);
            }

            return mergeFileName;
        }
コード例 #27
0
 public static int Authorization(int ID)
 {
     DateTime def = new DateTime(1, 1, 1);
     DateTime temp;
     string Document = "4-AUTHORIZATION FOR RELEASE OF PSYCHIATRIC.pdf";
     string PDF = GlobalVar.FILEPATH + Document;
     string newPDF = GlobalVar.FILEPATH + ID.ToString() + Document;
     PdfReader PDFnew = new PdfReader(PDF);
     PdfStamper pdfStamper = new PdfStamper(PDFnew, new FileStream(newPDF, FileMode.Create));
     AcroFields pdfFormFields = pdfStamper.AcroFields;
     string autofill2 = " SELECT * FROM ClientInfo WHERE " + ID.ToString() + " = ClientID";
     MySqlConnection connect2 = new MySqlConnection(GlobalVar.SERVER);
     MySqlCommand command2 = new MySqlCommand(autofill2, connect2);
     connect2.Open();
     MySqlDataReader reader2 = command2.ExecuteReader();
     if (reader2.Read())
     {
         if (reader2.GetInt32("ClientNum") != 0)
         {
             pdfFormFields.SetField("ClientName", reader2.GetString("ClientName"));
             temp = reader2.GetDateTime("DOB");
             if (temp != def)
             {
                 pdfFormFields.SetField("DoB", temp.Date.ToString("d"));
             }
             pdfFormFields.SetField("ClientNum", reader2.GetString("ClientNum"));
         }
     }
     else
     {
         pdfStamper.Close();
         return 0;
     }
     pdfStamper.Close();
     return print(newPDF);
 }
コード例 #28
0
        public void SetPageContentTest01()  {
            String outPdf = DestFolder + "out1.pdf";
            PdfReader reader =
                new PdfReader(TestResourceUtils.GetResourceAsStream(TestResourcesPath, "in.pdf"));
            PdfStamper stamper = new PdfStamper(reader, new FileStream(outPdf, FileMode.Create));
            reader.EliminateSharedStreams();
            int total = reader.NumberOfPages + 1;
            for (int i = 1; i < total; i++) {
                byte[] bb = reader.GetPageContent(i);
                reader.SetPageContent(i, bb);
            }
            stamper.Close();

            Assert.Null(new CompareTool().CompareByContent(outPdf, TestResourceUtils.GetResourceAsTempFile(TestResourcesPath, "cmp_out1.pdf"), DestFolder, "diff_"));
        }
コード例 #29
0
        public void PDFTextGetter(string pSearch, StringComparison SC, string SourceFile, string DestinationFile)
        {
            iTextSharp.text.pdf.PdfStamper     stamper = null;
            iTextSharp.text.pdf.PdfContentByte cb      = null;

            this.Cursor = Cursors.WaitCursor;
            if (File.Exists(SourceFile))
            {
                PdfReader pReader = new PdfReader(SourceFile);

                stamper    = new iTextSharp.text.pdf.PdfStamper(pReader, new System.IO.FileStream(DestinationFile, FileMode.Create));
                PB.Value   = 0;
                PB.Maximum = pReader.NumberOfPages;
                for (int page = 1; page <= pReader.NumberOfPages; page++)
                {
                    myLocationTextExtractionStrategy strategy = new myLocationTextExtractionStrategy();
                    cb = stamper.GetUnderContent(page);

                    //Send some data contained in PdfContentByte, looks like the first is always cero for me and the second 100, but i'm not sure if this could change in some cases
                    strategy.UndercontentCharacterSpacing  = cb.CharacterSpacing;
                    strategy.UndercontentHorizontalScaling = cb.HorizontalScaling;

                    //It's not really needed to get the text back, but we have to call this line ALWAYS,
                    //because it triggers the process that will get all chunks from PDF into our strategy Object
                    string currentText = PdfTextExtractor.GetTextFromPage(pReader, page, strategy);

                    //The real getter process starts in the following line
                    List <iTextSharp.text.Rectangle> MatchesFound = strategy.GetTextLocations(pSearch, SC);

                    //Set the fill color of the shapes, I don't use a border because it would make the rect bigger
                    //but maybe using a thin border could be a solution if you see the currect rect is not big enough to cover all the text it should cover
                    cb.SetColorFill(BaseColor.PINK);

                    //MatchesFound contains all text with locations, so do whatever you want with it, this highlights them using PINK color:

                    foreach (iTextSharp.text.Rectangle rect in MatchesFound)
                    {
                        cb.Rectangle(rect.Left, rect.Bottom, rect.Width, rect.Height);
                    }
                    cb.Fill();

                    PB.Value = PB.Value + 1;
                }
                stamper.Close();
                pReader.Close();
            }
            this.Cursor = Cursors.Default;
        }
コード例 #30
0
ファイル: PDFHelper.cs プロジェクト: BaqerNaqvi/Btado
        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();

            return output.ToArray();
        }
コード例 #31
0
ファイル: ManipPdf.cs プロジェクト: hcdocsdev/benjanderson
        public void FillInFields(string filePath, Dictionary<string, string> fields, string outPutFile)
        {
            var pdfReader = new PdfReader(filePath);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outPutFile, FileMode.Create));
            AcroFields pdfFormFields = pdfStamper.AcroFields;

            if (fields != null)
            {
                foreach (KeyValuePair<string, string> kvp in fields.Where(field => !string.IsNullOrEmpty(field.Value)))
                {
                    pdfFormFields.SetField(kvp.Key, kvp.Value);
                }
            }
            pdfStamper.Close();
            pdfReader.Close();
        }
コード例 #32
0
ファイル: Downloader.aspx.cs プロジェクト: jwebb-vtg/WSCIEMP
        private void LoadPDF()
        {
            /*
             * ContractNumber1
                ContractNumber2
                SumOfMoneyPerTon
                CropYear1
                WithdrawalDate
                CurrentDayMonth
                Shareholder Signature
                PrintLandOwnerName
                PrintShareholderName
                ShareholderAddress
                Director WSCPAC
                Company Representative
                CurrentTwoDigitYear
            */
            var pdfReader = new PdfReader(System.Web.HttpContext.Current.Server.MapPath("~/PDF/2015.pdf"));
            var output = new MemoryStream();
            var stamper = new PdfStamper(pdfReader, output);
            var date = DateTime.Now;
            DateTimeFormatInfo mfi = new DateTimeFormatInfo();
            string strMonthName = mfi.GetMonthName(date.Month).ToString();

            stamper.AcroFields.SetField("ContractNumber1", "");
            stamper.AcroFields.SetField("ContractNumber2", "");
            stamper.AcroFields.SetField("SumOfMoneyPerTon", "");
            stamper.AcroFields.SetField("CropYear1", "");
            stamper.AcroFields.SetField("WithdrawalDate", "");
            stamper.AcroFields.SetField("CurrentDayMonth", mfi.GetMonthName(date.Month).ToString() + " " + date.Day);
            stamper.AcroFields.SetField("Shareholder Signature", "");
            stamper.AcroFields.SetField("PrintLandOwnerName", "");
            stamper.AcroFields.SetField("PrintShareholderName", "");
            stamper.AcroFields.SetField("ShareholderAddress", "");
            stamper.AcroFields.SetField("Director WSCPAC", "");
            stamper.AcroFields.SetField("Company Representative", "");
            stamper.AcroFields.SetField("CurrentTwoDigitYear", date.ToString("yy"));

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

            Response.AddHeader("Content-Disposition", "attachment; filename=YourPDF.pdf");
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(output.ToArray());
            Response.End();
        }
コード例 #33
0
        // Add annotation to PDF using iTextSharp
        private void addTextAnnotationToPDF(string filePath, string contents, int pageNum, int x, int y, int width, int height)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamp = null;

            try
            {
                using (var inStream = new FileStream(filePath, FileMode.Open))
                {
                    pdfReader = new PdfReader(inStream);
                }

                using (var outStream = new FileStream(filePath, FileMode.Create))
                {
                    pdfStamp = new PdfStamper(pdfReader, outStream, (char)0, true);

                    var rect = new iTextSharp.text.Rectangle((float)x, (float)y, (float)x + width, (float)y + height);

                    // Generating the annotation's appearance using a TextField
                    TextField textField = new TextField(pdfStamp.Writer, rect, null);
                    textField.Text = contents;
                    textField.FontSize = 8;
                    textField.TextColor = BaseColor.DARK_GRAY;
                    textField.BackgroundColor = new BaseColor(Color.LightGoldenrodYellow);
                    textField.BorderColor = new BaseColor(Color.BurlyWood);
                    textField.Options = TextField.MULTILINE;
                    textField.SetExtraMargin(2f, 2f);
                    textField.Alignment = Element.ALIGN_TOP | Element.ALIGN_LEFT;
                    PdfAppearance appearance = textField.GetAppearance();

                    // Create the annotation
                    PdfAnnotation annotation = PdfAnnotation.CreateFreeText(pdfStamp.Writer, rect, null, new PdfContentByte(null));
                    annotation.SetAppearance(PdfName.N, appearance);
                    annotation.Flags = PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_LOCKED | PdfAnnotation.FLAGS_PRINT;
                    annotation.Put(PdfName.NM, new PdfString(Guid.NewGuid().ToString()));

                    // Add annotation to PDF
                    pdfStamp.AddAnnotation(annotation, pageNum);
                    pdfStamp.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not add signature image to PDF with error: " + ex.Message);
            }
        }
コード例 #34
0
        public HttpResponseMessage UpdatePdfDoc(UpdatePDF updatePDF)
        {
            HttpResponseMessage response = null;

            try
            {
                string ExistingVariableinPDF = updatePDF.ExistingVariableinPDF;
                string ReplacingVariable     = updatePDF.ReplacingVariable;
                string ReplacingDateVariable = updatePDF.ReplacingDateVariable;
                string sourceFile            = @updatePDF.sourceFile;
                Guid   guid = Guid.NewGuid();

                FileInfo fileInfo     = new FileInfo(sourceFile);
                string   tempfilename = Path.Combine(fileInfo.Directory.FullName, guid.ToString() + fileInfo.Extension);
                string   destFile     = @tempfilename;

                PdfReader  pReader       = new PdfReader(sourceFile);
                int        numberOfPages = pReader.NumberOfPages;
                FileStream fileStream    = new System.IO.FileStream(destFile, System.IO.FileMode.Create);
                stamper = new iTextSharp.text.pdf.PdfStamper(pReader, fileStream);
                PDFTextGetter(ExistingVariableinPDF, ReplacingVariable, StringComparison.CurrentCultureIgnoreCase, sourceFile, destFile);
                if (!String.IsNullOrEmpty(ReplacingDateVariable))
                {
                    PDFTextGetter(ReplacingDateVariable, DateTime.Now.DisplayWithSuffix(), StringComparison.CurrentCultureIgnoreCase, sourceFile, destFile);
                }

                stamper.Close();
                stamper.Dispose();
                pReader.Close();
                pReader.Dispose();
                fileStream.Close();
                fileInfo.Refresh();

                File.Delete(sourceFile);
                response = Request.CreateResponse(System.Net.HttpStatusCode.OK, guid.ToString());
            }
            catch (Exception ex)
            {
                response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
                Logger.WriteLog("Exception while UpdatePdfDoc " + ex.Message + Environment.NewLine + ex.StackTrace);
            }

            // File.Move(tempfilename, sourceFile);
            return(response);
        }
コード例 #35
0
        private static InsertResult InsertImpl(IInput context, Stream input, int page, PdfImage image, PointF imageOffset, PdfImageStyle style)
        {
            var outputStream = new MemoryStream();

            try
            {
                var reader  = new TextSharp.PdfReader(input);
                var stamper = new TextSharp.PdfStamper(reader, outputStream);

                var pages = reader.NumberOfPages;
                for (var pdfPage = 1; pdfPage <= pages; pdfPage++)
                {
                    if (pdfPage != page)
                    {
                        continue;
                    }

                    var cb = stamper.GetOverContent(pdfPage);
                    image.Image.SetAbsolutePosition(imageOffset.X, imageOffset.Y);
                    cb.AddImage(image.Image);
                    break;
                }

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

                return(InsertResult.CreateSuccessResult(new InsertResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = new MemoryStream(outputStream.GetBuffer())
                }));
            }
            catch (Exception ex)
            {
                return(InsertResult.FromException(
                           ex,
                           new InsertResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }
        }
コード例 #36
0
        /// <summary>
        /// Fills out and flattens a form with the name, company and country.
        /// </summary>
        /// <param name="src"> the path to the original form </param>
        /// <param name="dest"> the path to the filled out form </param>
        public void ManipulatePdf(String src, String dest)
        {
            PdfReader reader = new PdfReader(src);
            PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
            PdfContentByte under = stamper.GetUnderContent(1);

            PdfGState gs = new PdfGState();
            gs.FillOpacity = 0.3f;
            under.SaveState();
            under.SetGState(gs);
            under.SetRGBColorFill(200, 200, 0);
            ColumnText.ShowTextAligned(under, Element.ALIGN_CENTER,
                new Phrase("Watermark", new Font(Font.FontFamily.HELVETICA, 120)),
                297, 421, 45);
            under.RestoreState();
            stamper.Close();
            reader.Close();
        }
コード例 #37
0
ファイル: RepeatImage.cs プロジェクト: newlysoft/itextsharp
 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();
 }
コード例 #38
0
        public void fieldFieldsAndFlattenTest() {
            String acroFormFileName = "SF2809.pdf";
            String filledAcroFormFileName = "SF2809_filled.pdf";
            String flattenAcroFormFileName = "SF2809_alt.pdf";
            PdfReader reader = new PdfReader(CMP_FOLDER + acroFormFileName);
            PdfStamper stamper = new PdfStamper(reader, new FileStream(OUT_FOLDER + filledAcroFormFileName, FileMode.Create));
            AcroFields form = stamper.AcroFields;
            foreach (String key in form.Fields.Keys) {
                form.SetField(key, key);
            }
            stamper.Close();

            LoggerFactory.GetInstance().SetLogger(new SysoLogger());
            reader = new PdfReader(OUT_FOLDER + filledAcroFormFileName);
            MCFieldFlattener flattener = new MCFieldFlattener();
            flattener.Process(reader, new FileStream(OUT_FOLDER + flattenAcroFormFileName, FileMode.Create));
            //Compare(OUT_FOLDER + flattenAcroFormFileName, CMP_FOLDER + flattenAcroFormFileName);
        }
コード例 #39
0
        private void CleanUp(String input, String output, IList<PdfCleanUpLocation> cleanUpLocations) {
            DirectoryInfo outDir = new DirectoryInfo(OUTPUT_PATH);

            if (!outDir.Exists) {
                outDir.Create();
            }

            PdfReader reader = new PdfReader(input);
            Stream fos = new FileStream(output, FileMode.Create);
            PdfStamper stamper = new PdfStamper(reader, fos);

            PdfCleanUpProcessor cleaner = (cleanUpLocations == null)? new PdfCleanUpProcessor(stamper) : new PdfCleanUpProcessor(cleanUpLocations, stamper);
            cleaner.CleanUp();

            stamper.Close();
            fos.Close();
            reader.Close();
        }
コード例 #40
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();
 }
コード例 #41
0
ファイル: Program.cs プロジェクト: wk-j/itext
        static void ManipulatePdf()
        {
            using (var ms = new MemoryStream()) {
                var pdf     = "resources/Project.pdf";
                var reader  = new iTextSharp.text.pdf.PdfReader(pdf);
                var stamper = new iTextSharp.text.pdf.PdfStamper(reader, ms);

                var box  = reader.GetCropBox(1);
                var left = box.Left;
                var top  = box.Top;

                // var newRectangle = new iTextSharp.text.Rectangle(left + 20, top - 20, left + 250, top - 40);
                var newRectangle = new iTextSharp.text.Rectangle(left, top, left + 250, top - 40);
                newRectangle.UseVariableBorders = false;

                var pcb = new iTextSharp.text.pdf.PdfContentByte(stamper.Writer);
                pcb.SetColorFill(iTextSharp.text.BaseColor.RED);


                var text = "Hello, world!";

                var annot = iTextSharp.text.pdf.PdfAnnotation.CreateFreeText(stamper.Writer, newRectangle, text, pcb);
                annot.Flags = iTextSharp.text.pdf.PdfAnnotation.FLAGS_PRINT;

                // annot.BorderStyle = new iTextSharp.text.pdf.PdfBorderDictionary(0, 0);
                // annot.Color = GetBaseColor(Color.Yellow);
                // annot.Put(PdfName.DS, new PdfString("font: " + "Tohama" + " " +
                //           (10 * 0.75f) + "pt; text-align: left; color: " +
                //           GetBaseColor(Color.Blue)));
                // annot.Put(PdfName.RC, new PdfString(text.Replace("(?i)<br */?> ", "\n").Replace(" & nbsp; ", " ")));
                // annot.Put(PdfName.ROTATE, new PdfNumber(0));

                stamper.AddAnnotation(annot, 1);
                stamper.Close();

                var output = ms.ToArray();
                System.IO.File.WriteAllBytes(".output/Hello.pdf", output);
            }
        }
コード例 #42
0
ファイル: CompareTool.cs プロジェクト: w16014936/itextsharp
        public String Compare(String outPath, String differenceImagePrefix, Dictionary <int, List <Rectangle> > ignoredAreas)
        {
            if (gsExec == null || !File.Exists(gsExec))
            {
                return(undefinedGsPath);
            }

            try {
                DirectoryInfo    targetDir;
                FileSystemInfo[] allImageFiles;
                FileSystemInfo[] imageFiles;
                FileSystemInfo[] cmpImageFiles;
                if (Directory.Exists(outPath))
                {
                    targetDir     = new DirectoryInfo(outPath);
                    allImageFiles = targetDir.GetFileSystemInfos("*.png");
                    imageFiles    = Array.FindAll(allImageFiles, PngPredicate);
                    foreach (FileSystemInfo fileSystemInfo in imageFiles)
                    {
                        fileSystemInfo.Delete();
                    }

                    cmpImageFiles = Array.FindAll(allImageFiles, CmpPngPredicate);
                    foreach (FileSystemInfo fileSystemInfo in cmpImageFiles)
                    {
                        fileSystemInfo.Delete();
                    }
                }
                else
                {
                    targetDir = Directory.CreateDirectory(outPath);
                }

                if (File.Exists(outPath + differenceImagePrefix))
                {
                    File.Delete(outPath + differenceImagePrefix);
                }

                if (ignoredAreas != null && ignoredAreas.Count > 0)
                {
                    PdfReader  cmpReader  = new PdfReader(cmpPdf);
                    PdfReader  outReader  = new PdfReader(outPdf);
                    PdfStamper outStamper = new PdfStamper(outReader,
                                                           new FileStream(outPath + ignoredAreasPrefix + outPdfName, FileMode.Create));
                    PdfStamper cmpStamper = new PdfStamper(cmpReader,
                                                           new FileStream(outPath + ignoredAreasPrefix + cmpPdfName, FileMode.Create));

                    foreach (KeyValuePair <int, List <Rectangle> > entry in ignoredAreas)
                    {
                        int pageNumber = entry.Key;
                        List <Rectangle> rectangles = entry.Value;

                        if (rectangles != null && rectangles.Count > 0)
                        {
                            PdfContentByte outCB = outStamper.GetOverContent(pageNumber);
                            PdfContentByte cmpCB = cmpStamper.GetOverContent(pageNumber);

                            foreach (Rectangle rect in rectangles)
                            {
                                rect.BackgroundColor = BaseColor.BLACK;
                                outCB.Rectangle(rect);
                                cmpCB.Rectangle(rect);
                            }
                        }
                    }

                    outStamper.Close();
                    cmpStamper.Close();

                    outReader.Close();
                    cmpReader.Close();

                    init(outPath + ignoredAreasPrefix + outPdfName, outPath + ignoredAreasPrefix + cmpPdfName);
                }

                String  gsParams = this.gsParams.Replace("<outputfile>", outPath + cmpImage).Replace("<inputfile>", cmpPdf);
                Process p        = new Process();
                p.StartInfo.FileName               = @gsExec;
                p.StartInfo.Arguments              = @gsParams;
                p.StartInfo.UseShellExecute        = false;
                p.StartInfo.RedirectStandardError  = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.CreateNoWindow         = true;
                p.Start();

                String line;
                while ((line = p.StandardOutput.ReadLine()) != null)
                {
                    Console.Out.WriteLine(line);
                }
                p.StandardOutput.Close();;
                while ((line = p.StandardError.ReadLine()) != null)
                {
                    Console.Out.WriteLine(line);
                }
                p.StandardError.Close();
                p.WaitForExit();
                if (p.ExitCode == 0)
                {
                    gsParams                           = this.gsParams.Replace("<outputfile>", outPath + outImage).Replace("<inputfile>", outPdf);
                    p                                  = new Process();
                    p.StartInfo.FileName               = @gsExec;
                    p.StartInfo.Arguments              = @gsParams;
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.RedirectStandardError  = true;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.CreateNoWindow         = true;
                    p.Start();
                    while ((line = p.StandardOutput.ReadLine()) != null)
                    {
                        Console.Out.WriteLine(line);
                    }
                    p.StandardOutput.Close();;
                    while ((line = p.StandardError.ReadLine()) != null)
                    {
                        Console.Out.WriteLine(line);
                    }
                    p.StandardError.Close();
                    p.WaitForExit();

                    if (p.ExitCode == 0)
                    {
                        allImageFiles = targetDir.GetFileSystemInfos("*.png");
                        imageFiles    = Array.FindAll(allImageFiles, PngPredicate);
                        cmpImageFiles = Array.FindAll(allImageFiles, CmpPngPredicate);
                        bool bUnexpectedNumberOfPages = imageFiles.Length != cmpImageFiles.Length;
                        int  cnt = Math.Min(imageFiles.Length, cmpImageFiles.Length);
                        if (cnt < 1)
                        {
                            return("No files for comparing!!!\nThe result or sample pdf file is not processed by GhostScript.");
                        }
                        Array.Sort(imageFiles, new ImageNameComparator());
                        Array.Sort(cmpImageFiles, new ImageNameComparator());
                        String differentPagesFail = null;
                        for (int i = 0; i < cnt; i++)
                        {
                            Console.Out.WriteLine("Comparing page " + (i + 1).ToString() + " (" + imageFiles[i].FullName + ")...");
                            FileStream is1       = new FileStream(imageFiles[i].FullName, FileMode.Open);
                            FileStream is2       = new FileStream(cmpImageFiles[i].FullName, FileMode.Open);
                            bool       cmpResult = CompareStreams(is1, is2);
                            is1.Close();
                            is2.Close();
                            if (!cmpResult)
                            {
                                if (File.Exists(compareExec))
                                {
                                    String compareParams = this.compareParams.Replace("<image1>", imageFiles[i].FullName).Replace("<image2>", cmpImageFiles[i].FullName).Replace("<difference>", outPath + differenceImagePrefix + (i + 1).ToString() + ".png");
                                    p = new Process();
                                    p.StartInfo.FileName              = @compareExec;
                                    p.StartInfo.Arguments             = @compareParams;
                                    p.StartInfo.UseShellExecute       = false;
                                    p.StartInfo.RedirectStandardError = true;
                                    p.StartInfo.CreateNoWindow        = true;
                                    p.Start();

                                    while ((line = p.StandardError.ReadLine()) != null)
                                    {
                                        Console.Out.WriteLine(line);
                                    }
                                    p.StandardError.Close();
                                    p.WaitForExit();
                                    if (p.ExitCode == 0)
                                    {
                                        if (differentPagesFail == null)
                                        {
                                            differentPagesFail =
                                                differentPages.Replace("<filename>", outPdf).Replace("<pagenumber>",
                                                                                                     (i + 1).ToString());
                                            differentPagesFail += "\nPlease, examine " + outPath + differenceImagePrefix + (i + 1).ToString() +
                                                                  ".png for more details.";
                                        }
                                        else
                                        {
                                            differentPagesFail =
                                                "File " + outPdf + " differs.\nPlease, examine difference images for more details.";
                                        }
                                    }
                                    else
                                    {
                                        differentPagesFail = differentPages.Replace("<filename>", outPdf).Replace("<pagenumber>", (i + 1).ToString());
                                        Console.Out.WriteLine("Invalid compareExec variable.");
                                    }
                                }
                                else
                                {
                                    differentPagesFail =
                                        differentPages.Replace("<filename>", outPdf).Replace("<pagenumber>",
                                                                                             (i + 1).ToString());
                                    differentPagesFail += "\nYou can optionally specify path to ImageMagick compare tool (e.g. -DcompareExec=\"C:/Program Files/ImageMagick-6.5.4-2/compare.exe\") to visualize differences.";
                                    break;
                                }
                            }
                            else
                            {
                                Console.Out.WriteLine("done.");
                            }
                        }
                        if (differentPagesFail != null)
                        {
                            return(differentPagesFail);
                        }
                        else
                        {
                            if (bUnexpectedNumberOfPages)
                            {
                                return(unexpectedNumberOfPages.Replace("<filename>", outPdf) + "\n" + differentPagesFail);
                            }
                        }
                    }
                    else
                    {
                        return(gsFailed.Replace("<filename>", outPdf));
                    }
                }
                else
                {
                    return(gsFailed.Replace("<filename>", cmpPdf));
                }
            } catch (Exception) {
                return(cannotOpenTargetDirectory.Replace("<filename>", outPdf));
            }

            return(null);
        }
コード例 #43
0
        //metodo para crear el pdf al vuelo del saef
        public byte[] FormarPDF(string HTML, string fileName, string Cabecera, string Pie, string Folio, bool nuevo)
        {
            PdfConverter pdfConverter = new PdfConverter();

            byte[] bPdf  = null;
            byte[] bResp = null;

            try
            {
                pdfConverter.LicenseKey = "f1ROX0dfTk9OTl9KUU9fTE5RTk1RRkZGRg==";


                //Header
                pdfConverter.PdfDocumentOptions.ShowHeader   = true;
                pdfConverter.PdfHeaderOptions.HeaderHeight   = 190;
                pdfConverter.PdfHeaderOptions.HtmlToPdfArea  = new HtmlToPdfArea(Cabecera, null);
                pdfConverter.PdfHeaderOptions.DrawHeaderLine = false;

                if (nuevo == false)
                {
                    //pie
                    pdfConverter.PdfFooterOptions.FooterHeight   = 100;
                    pdfConverter.PdfFooterOptions.HtmlToPdfArea  = new HtmlToPdfArea(Pie, null);
                    pdfConverter.PdfDocumentOptions.ShowFooter   = true;
                    pdfConverter.PdfFooterOptions.DrawFooterLine = false;
                }


                //poner el numero de paginacion
                pdfConverter.PdfFooterOptions.TextArea = new TextArea(5, -5, "Página &p; de &P; ",
                                                                      new System.Drawing.Font(new System.Drawing.FontFamily("Arial"), 8,
                                                                                              System.Drawing.GraphicsUnit.Point));
                pdfConverter.PdfFooterOptions.TextArea.EmbedTextFont = true;
                pdfConverter.PdfFooterOptions.TextArea.TextAlign     = HorizontalTextAlign.Right;

                pdfConverter.PdfDocumentOptions.PdfPageSize         = PdfPageSize.Letter;
                pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;


                //margenes
                pdfConverter.PdfDocumentOptions.LeftMargin   = 40;
                pdfConverter.PdfDocumentOptions.RightMargin  = 40;
                pdfConverter.PdfDocumentOptions.StretchToFit = true;

                bPdf = pdfConverter.GetPdfBytesFromHtmlString(HTML);

                if (nuevo)
                {
                    //metodo para poner el logo de fondo
                    try
                    {
                        string rutaFondo = "https://sistemas.indaabin.gob.mx/ImagenesComunes/nuevoescudo.png";


                        MemoryStream stream = new MemoryStream();

                        iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(bPdf);
                        //crear el objeto pdfstamper que se utiliza para agregar contenido adicional al archivo pdf fuente
                        iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(pdfReader, stream);

                        //iterar a través de todas las páginas del archivo fuente pdf
                        for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
                        {
                            PdfContentByte        overContent = pdfStamper.GetOverContent(pageIndex);
                            iTextSharp.text.Image jpeg        = iTextSharp.text.Image.GetInstance(rutaFondo);
                            overContent.SaveState();
                            overContent.SetGState(new PdfGState
                            {
                                FillOpacity   = 0.3f,
                                StrokeOpacity = 0.3f//0.3
                            });

                            overContent.AddImage(jpeg, 560f, 0f, 0f, 820f, 0f, 0f);

                            overContent.RestoreState();
                        }

                        //cerrar stamper y filestream de salida
                        pdfStamper.Close();
                        stream.Close();
                        pdfReader.Close();

                        bResp = stream.ToArray();

                        pdfStamper = null;
                        pdfReader  = null;
                        stream     = null;
                    }
                    catch (Exception ex)
                    {
                    }
                }

                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ContentType = "application/pdf";
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=Acessibilidad" + " " + fileName + " " + Folio + ".pdf");

                if (nuevo)
                {
                    HttpContext.Current.Response.BinaryWrite(bResp);
                }
                else
                {
                    HttpContext.Current.Response.BinaryWrite(bPdf);
                }

                HttpContext.Current.Response.Flush();

                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
            }

            return(bPdf);

            //return bPdf;
        }
コード例 #44
0
    public byte[] AddSignatureAppearance(byte[] pdfToStamBytes, string stampString)
    {
        using (var ms = new MemoryStream())
        {
            try
            {
                var imageWidth  = 425;
                var imageHeight = 89;
                var fontSize    = 0;
                if (stampString.Length > 25)
                {
                    fontSize = 8;
                }
                else
                {
                    fontSize = 12;
                }

                //TODO: Make configurable
                string path           = "emptyPath";
                string xsdFileLinux   = @"/var/local/lawtrust/configs/signatureFont.ttf";
                string xsdFileWindows = @"C:/lawtrust/configs/signatureFont.ttf";

                if (File.Exists(xsdFileLinux))
                {
                    path = xsdFileLinux;
                }
                else if (File.Exists(xsdFileWindows))
                {
                    path = xsdFileWindows;
                }
                if (!path.Equals("emptyPath"))
                {
                    var reader   = new iTextSharp.text.pdf.PdfReader(pdfToStamBytes);
                    var stamper  = new iTextSharp.text.pdf.PdfStamper(reader, ms);
                    var rotation = reader.GetPageRotation(1);
                    var box      = reader.GetPageSizeWithRotation(1);
                    var bf       = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    var pcb      = stamper.GetOverContent(1);
                    var f        = new Font(bf, fontSize);
                    var p        = new Phrase(stampString, f);

                    //TODO: Make coordinates configurable
                    if (rotation == 90)
                    {
                        //landscape
                        ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 740, 10, 0);
                    }
                    else if (rotation == 180)
                    {
                        //normal PDF
                        ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 500, 10, 0);
                    }
                    else if (rotation == 270)
                    {
                        //landscape
                        ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 740, 10, 0);
                    }
                    else
                    {
                        //normal PDF
                        ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 500, 10, 0);
                    }

                    pcb.SaveState();
                    stamper.Close();
                    reader.Close();
                    return(ms.ToArray());
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                //need error handling
                return(null);
            }
        }
    }
コード例 #45
0
        void ManipulatePdf(string src, string dest, MetaData md)
        {
            using (var reader = new ip.PdfReader(src))
            {
                var catalog        = reader.Catalog;
                var structTreeRoot = catalog.GetAsDict(ip.PdfName.STRUCTTREEROOT);

                Manipulate(structTreeRoot);
                using (var stamper = new ip.PdfStamper(reader, new FileStream(dest, FileMode.Create)))
                {
                    var page = reader.GetPageN(1);
                    using (var ms = new MemoryStream())
                    {
                        var dic = new ip.PdfDictionary();

                        DateTime time = DateTime.Now;

                        if (reader.Info.ContainsKey(ip.PdfName.CREATIONDATE.ToString().Substring(1)))
                        {
                            var temp = reader.Info[ip.PdfName.CREATIONDATE.ToString().Substring(1)].Substring(2).Replace('\'', ':');
                            temp = temp.Substring(0, temp.Length - 1);
                            time = DateTime.ParseExact(temp, "yyyyMMddHHmmsszzz", CultureInfo.InvariantCulture);
                        }

                        dic.Put(ip.PdfName.PRODUCER, new ip.PdfString(md.Creator));
                        dic.Put(ip.PdfName.TITLE, new ip.PdfString(Path.GetFileNameWithoutExtension(dest)));
                        dic.Put(ip.PdfName.CREATOR, new ip.PdfString(md.Creator));
                        dic.Put(ip.PdfName.AUTHOR, new ip.PdfString(md.Author));
                        dic.Put(ip.PdfName.CREATIONDATE, new ip.PdfDate(time));


                        var xmp = new XmpWriter(ms, dic);
                        xmp.Close();
                        var reference = stamper.Writer.AddToBody(new ip.PdfStream(ms.ToArray()));
                        page.Put(ip.PdfName.METADATA, reference.IndirectReference);

                        if (ms != null)
                        {
                            var d   = Encoding.UTF8.GetString(ms.ToArray());
                            var xml = new XmlDocument();
                            xml.LoadXml(d);
                            var node = xml.DocumentElement.FirstChild;
                            node = node.FirstChild;

                            if (node != null)
                            {
                                //node.AppendAttribute("xmlns:pdfaid", "http://www.aiim.org/pdfa/ns/id/");
                                var attrId = xml.CreateAttribute("xmlns:pdfaid");
                                attrId.Value = "http://www.aiim.org/pdfa/ns/id/";
                                node.Attributes.Append(attrId);

                                var attrPart = xml.CreateAttribute("pdfaid:part", "http://www.aiim.org/pdfa/ns/id/");
                                attrPart.Value = "1";
                                node.Attributes.Append(attrPart);

                                var attrConf = xml.CreateAttribute("pdfaid:conformance", "http://www.aiim.org/pdfa/ns/id/");
                                attrConf.Value = "A";
                                node.Attributes.Append(attrConf);

                                if (md.CustomMetadata != null && md.CustomMetadata.Length > 0)
                                {
                                    var dataNode = node.OwnerDocument.CreateElement("CustomMetaData");
                                    node.AppendChild(dataNode);
                                    dataNode.InnerText = System.Convert.ToBase64String(md.CustomMetadata);
                                }
                            }

                            ms.Position = 0;
                            xml.Save(ms);
                            d = Encoding.UTF8.GetString(ms.ToArray());
                        }

                        stamper.XmpMetadata = ms.ToArray();

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