Пример #1
0
        public static string SavePDF(string strInputFile, string strOutputFile)
        {
            iTextSharp.text.Document doc = null;
            try
            {
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(strInputFile);
                iTextSharp.text.Rectangle rectDocSize = new iTextSharp.text.Rectangle(img.Width, img.Height);
                doc = new iTextSharp.text.Document(rectDocSize);

                iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(strOutputFile, FileMode.Create));
                doc.Open();
                //doc.Add(new iTextSharp.text.Paragraph("GIF"));
                doc.Add(img);
            }
            catch (iTextSharp.text.DocumentException dex)
            {
                throw dex;
            }
            catch (IOException ioex)
            {
                throw ioex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if(doc != null)
                    doc.Close();
            }
            return strOutputFile;
        }
        public override void RenderText(TextRenderInfo renderInfo)
        {
            base.RenderText(renderInfo);

            var bottomLeft = renderInfo.GetDescentLine().GetStartPoint();
            var topRight = renderInfo.GetAscentLine().GetEndPoint();

            var rect = new iTextSharp.text.Rectangle(
                bottomLeft[Vector.I1],
                bottomLeft[Vector.I2],
                topRight[Vector.I1],
                topRight[Vector.I2]
            );

            this.containers.Add(new TextContainer()
            {
                Container = rect,
                Text = renderInfo.GetText()
            });
        }
Пример #3
0
        public static void ConvertImageToPdf(string srcFilename, string dstFilename)
        {
            iTextSharp.text.Rectangle pageSize = null;

            using (var srcImage = new Bitmap(srcFilename))
            {
                pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
            }
            using (var ms = new MemoryStream())
            {
                var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
                iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
                document.Open();
                var image = iTextSharp.text.Image.GetInstance(srcFilename);
                document.Add(image);
                document.Close();

                File.WriteAllBytes(dstFilename, ms.ToArray());
            }
        }
Пример #4
0
        public static void SetAppearance(YapsConfig config, PdfSignatureAppearance sap)
        {
            var appearance = config.Appearance ?? new SignatureAppearance();
            sap.Reason = appearance.Reason;
            sap.Contact = appearance.Contact;
            sap.Location = appearance.Location;
            sap.SignDate = DateTime.Now;
            sap.Acro6Layers = true;
            if (!config.Visible || !appearance.ValidateRect())
                return;

            //iTextSharp.text.Rectangle rect = st.Reader.GetPageSize(sigAP.Page);
            var xi = appearance.X + appearance.Width;
            var yi = appearance.Y + appearance.Height;
            var rect = new iTextSharp.text.Rectangle(appearance.X, appearance.Y, xi, yi);
            //sap.Image = sigAP.RawData == null ? null : iTextSharp.text.Image.GetInstance(sigAP.RawData);
            if (!string.IsNullOrEmpty(appearance.CustomText))
                sap.Layer2Text = appearance.CustomText;
            //sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 300, 200), 1, "Signature");
            sap.SetVisibleSignature(rect, appearance.Page, "Signature");
        }
        public void RenderText(iTextSharp.text.pdf.parser.TextRenderInfo renderInfo)
        {
            string curFont = renderInfo.GetFont().PostscriptFontName;
              //Check if faux bold is used
              if ((renderInfo.GetTextRenderMode() == (int)TextRenderMode.FillThenStrokeText))
              {
            curFont += "-Bold";
              }

              //This code assumes that if the baseline changes then we're on a newline
              Vector curBaseline = renderInfo.GetBaseline().GetStartPoint();
              Vector topRight = renderInfo.GetAscentLine().GetEndPoint();
              iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(curBaseline[Vector.I1], curBaseline[Vector.I2], topRight[Vector.I1], topRight[Vector.I2]);
              Single curFontSize = rect.Height;

              //See if something has changed, either the baseline, the font or the font size
              if ((this.lastBaseLine == null) || (curBaseline[Vector.I2] != lastBaseLine[Vector.I2]) || (curFontSize != lastFontSize) || (curFont != lastFont))
              {
            //if we've put down at least one span tag close it
            if ((this.lastBaseLine != null))
            {
              this.result.AppendLine("</span>");
            }
            //If the baseline has changed then insert a line break
            if ((this.lastBaseLine != null) && curBaseline[Vector.I2] != lastBaseLine[Vector.I2])
            {
              this.result.AppendLine("<br />");
            }
            //Create an HTML tag with appropriate styles
            this.result.AppendFormat("<span style=\"font-family:{0};font-size:{1}\">", curFont, curFontSize);
              }

              //Append the current text
              this.result.Append(renderInfo.GetText());

              //Set currently used properties
              this.lastBaseLine = curBaseline;
              this.lastFontSize = curFontSize;
              this.lastFont = curFont;
        }
Пример #6
0
        //Automatically called for each chunk of text in the PDF
        public override void RenderText(TextRenderInfo renderInfo)
        {
            base.RenderText(renderInfo);

            //See if the current chunk contains the text
            var startPosition = System.Globalization.CultureInfo.CurrentCulture.CompareInfo.IndexOf(
                renderInfo.GetText(), this.TextToSearchFor, this.CompareOptions);

            //If not found bail
            if (startPosition < 0)
            {
                return;
            }

            //Grab the individual characters
            var chars =
                renderInfo.GetCharacterRenderInfos().Skip(startPosition).Take(this.TextToSearchFor.Length).ToList();

            //Grab the first and last character
            var firstChar = chars.First();
            var lastChar = chars.Last();

            //Get the bounding box for the chunk of text
            var bottomLeft = firstChar.GetDescentLine().GetStartPoint();
            var topRight = lastChar.GetAscentLine().GetEndPoint();

            //Create a rectangle from it
            var rect = new iTextSharp.text.Rectangle(
                bottomLeft[Vector.I1],
                bottomLeft[Vector.I2],
                topRight[Vector.I1],
                topRight[Vector.I2]
                );

            //Add this to our main collection
            this.myPoints.Add(new RectAndText(rect, this.TextToSearchFor));
        }
        //Automatically called for each chunk of text in the PDF
        public override void RenderText(TextRenderInfo renderInfo) {
            base.RenderText(renderInfo);

            //Get the bounding box for the chunk of text
            var bottomLeft = renderInfo.GetDescentLine().GetStartPoint();
            var topRight = renderInfo.GetAscentLine().GetEndPoint();

            //Create a rectangle from it
            var rect = new iTextSharp.text.Rectangle(
                                                    bottomLeft[Vector.I1],
                                                    bottomLeft[Vector.I2],
                                                    topRight[Vector.I1],
                                                    topRight[Vector.I2]
                                                    );

            //Add this to our main collection
            this.myPoints.Add(new RectAndText(rect, renderInfo.GetText()));
        }
Пример #8
0
        public PdfResult ViewPdf(object model, string fileName, string viewName, bool download = false, iTextSharp.text.Rectangle pageSize = null)
        {
            ViewData.Model = model;

            if (pageSize == null)
            {
                pageSize = iTextSharp.text.PageSize.A4;
            }

            return(new PdfResult()
            {
                ViewName = viewName,
                FileName = fileName,
                TempData = TempData,
                ViewData = ViewData,
                Download = download,
                PageSize = pageSize
            });
        }
Пример #9
0
        public void Sign(PDFSignatureAP sigAP, bool encrypt, PDFEncryption Enc)
        {
            PdfReader reader = new PdfReader(this.inputPDF);

            FileStream fs = new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write);


            PdfStamper st;

            if (this.myCert == null) //No signature just write meta-data and quit
            {
                st = new PdfStamper(reader, fs);
            }
            else
            {
                st = PdfStamper.CreateSignature(reader, fs, '\0', null, sigAP.Multi);
            }

            if (encrypt && Enc != null)
            {
                Enc.Encrypt(st);
            }
            //st.SetEncryption(PdfWriter.STRENGTH128BITS, "user", "owner", PdfWriter.ALLOW_COPY);

            st.MoreInfo    = this.metadata.getMetaData();
            st.XmpMetadata = this.metadata.getStreamedMetaData();

            if (this.myCert == null) //No signature just write meta-data and quit
            {
                st.Close();
                return;
            }

            PdfSignatureAppearance sap = st.SignatureAppearance;

            //sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED);

            sap.SetCrypto(null, this.myCert.Chain, null, PdfSignatureAppearance.SELF_SIGNED);

            sap.Reason   = sigAP.SigReason;
            sap.Contact  = sigAP.SigContact;
            sap.Location = sigAP.SigLocation;
            if (sigAP.Visible)
            {
                iTextSharp.text.Rectangle rect = st.Reader.GetPageSize(sigAP.Page);
                sap.Image      = sigAP.RawData == null ? null : iTextSharp.text.Image.GetInstance(sigAP.RawData);
                sap.Layer2Text = sigAP.CustomText;

                sap.SetVisibleSignature(new iTextSharp.text.Rectangle(sigAP.SigX, sigAP.SigY, sigAP.SigX + sigAP.SigW, sigAP.SigY + sigAP.SigH), sigAP.Page, null);
            }



            /////
            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));

            dic.Reason           = sap.Reason;
            dic.Location         = sap.Location;
            dic.Contact          = sap.Contact;
            dic.Date             = new PdfDate(sap.SignDate);
            sap.CryptoDictionary = dic;

            int contentEstimated = 15000;
            // Preallocate excluded byte-range for the signature content (hex encoded)
            Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();

            exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
            sap.PreClose(exc);

            PdfPKCS7 sgn           = new PdfPKCS7(this.myCert.Akp, this.myCert.Chain, null, "SHA1", false);
            IDigest  messageDigest = DigestUtilities.GetDigest("SHA1");
            Stream   data          = sap.RangeStream;

            byte[] buf = new byte[8192];
            int    n;

            while ((n = data.Read(buf, 0, buf.Length)) > 0)
            {
                messageDigest.BlockUpdate(buf, 0, n);
            }
            byte[] hash = new byte[messageDigest.GetDigestSize()];
            messageDigest.DoFinal(hash, 0);
            DateTime cal = DateTime.Now;

            byte[] ocsp = null;
            if (this.myCert.Chain.Length >= 2)
            {
                String url = PdfPKCS7.GetOCSPURL(this.myCert.Chain[0]);
                if (url != null && url.Length > 0)
                {
                    ocsp = new OcspClientBouncyCastle(this.myCert.Chain[0], this.myCert.Chain[1], url).GetEncoded();
                }
            }
            byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp);
            sgn.Update(sh, 0, sh.Length);


            byte[] paddedSig = new byte[contentEstimated];


            if (this.myCert.Tsc != null)
            {
                byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, this.myCert.Tsc, ocsp);
                System.Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length);
                if (contentEstimated + 2 < encodedSigTsa.Length)
                {
                    throw new Exception("Not enough space for signature");
                }
            }
            else
            {
                byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal);
                System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
                if (contentEstimated + 2 < encodedSig.Length)
                {
                    throw new Exception("Not enough space for signature");
                }
            }



            PdfDictionary dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);

            //////
            //st.Close();
        }
Пример #10
0
        static void Main(string[] args)
        {
            PdfReader  pdfReaderLocal = null;
            FileStream fout = null;
            float      RectRight = 0; float RectLeft = 0; float RectTop = 0; float RectBottom = 0;

            try
            {
                bool             isVisibleSignature = true;
                int              noOfPage           = 0;
                bool             iscert             = false;
                X509Certificate2 mcert = null;
                X509Store        store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certificates = store.Certificates;
                if (certificates.Count == 0)
                {
                    store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                }
                foreach (X509Certificate2 certs in certificates)
                {
                    if (certs.GetName().Contains("Exalca DS Ver2.0"))
                    {
                        iscert = true;
                        mcert  = certs;
                        Console.WriteLine("found cert Exalca DS Ver2.0");
                    }
                }
                //string Internal_path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Signed_Doc") + "\\" + InvoiceName;
                string inptfldr = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "InputFldr");

                if (!Directory.Exists(inptfldr))
                {
                    Directory.CreateDirectory(inptfldr);
                }

                string outfldr = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OutputFldr");
                if (!Directory.Exists(outfldr))
                {
                    Directory.CreateDirectory(outfldr);
                }
                if (iscert)
                {
                    string           Sign_Location = "Bengaluru";
                    string           Sign_AllPages = "N";
                    X509Certificate2 cert          = mcert; //get certificate based on thumb print

                    Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
                    Org.BouncyCastle.X509.X509Certificate[]     chain = new Org.BouncyCastle.X509.X509Certificate[] {
                        cp.ReadCertificate(cert.RawData)
                    };

                    IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA1");
                    //PdfReader pdfReader = new PdfReader(sourceDocument);
                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();
                    //ErrorLog.WriteHistoryLog("Open for write");
                    //signatureAppearance.SignatureGraphic = Image.GetInstance(pathToSignatureImage);
                    //signatureAppearance.Reason = reason; signpdf method
                    pdfReaderLocal = new PdfReader(inptfldr + "//s.pdf");
                    noOfPage       = pdfReaderLocal.NumberOfPages;

                    iTextSharp.text.Rectangle mediabox = pdfReaderLocal.GetPageSize(1);
                    fout = new FileStream(outfldr + "\\123.pdf", FileMode.Append, FileAccess.Write);
                    PdfStamper             stamper             = PdfStamper.CreateSignature(pdfReaderLocal, fout, '\0', null, true);
                    PdfSignatureAppearance signatureAppearance = stamper.SignatureAppearance;

                    signatureAppearance.ReasonCaption   = "";
                    signatureAppearance.Reason          = "Exalca";
                    signatureAppearance.LocationCaption = "";

                    signatureAppearance.Location    = "Bengaluru";
                    signatureAppearance.Acro6Layers = false;
                    signatureAppearance.Layer4Text  = PdfSignatureAppearance.questionMark;

                    BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    signatureAppearance.Layer2Font = new iTextSharp.text.Font(bf, 8, iTextSharp.text.Font.NORMAL);
                    var rec1 = new iTextSharp.text.Rectangle(610, 75, 440, 150);
                    signatureAppearance.SetVisibleSignature(rec1, 1, "Signature" + 1); //i-->Page no,Signature1--->Field name

                    MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
                    signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (pdfReaderLocal != null)
                {
                    pdfReaderLocal.Close();
                    pdfReaderLocal.Dispose();
                }
                if (fout != null)
                {
                    fout.Close();
                    fout.Dispose();
                }
            }
        }
Пример #11
0
        private void Scrape(CancellationToken token, string path)
        {
            PdfReader reader = new PdfReader(path);
            string    sUri   = "";

            try
            {
                // Pagination
                for (var i = 1; i <= reader.NumberOfPages; i++)
                {
                    //get current page
                    var pageDict = reader.GetPageN(i);

                    //get all annotations from current page
                    var annotArray = (PdfArray)PdfReader.GetPdfObject(pageDict.Get(PdfName.ANNOTS));

                    //ensure array isn't empty
                    if (annotArray == null)
                    {
                        continue;
                    }
                    if (annotArray.Length <= 0)
                    {
                        continue;
                    }

                    // check every annotation on the page
                    foreach (var annot in annotArray.ArrayList)
                    {
                        //convert the iTextSharp-specific object to a generic PDF object
                        var annotDict = (PdfDictionary)PdfReader.GetPdfObject(annot);

                        //ensure the object isnt empty
                        if (annotDict == null)
                        {
                            continue;
                        }

                        //get the annotation subtype and ensure it is a link
                        var subtype = annotDict.Get(PdfName.SUBTYPE).ToString();
                        Log("Subtype: " + subtype);
                        if (subtype != "/Link")
                        {
                            continue;
                        }


                        //get the annotations ACTION
                        var linkDict = (PdfDictionary)annotDict.GetDirectObject(PdfName.A);
                        if (linkDict == null)
                        {
                            continue;
                        }

                        if (!linkDict.Get(PdfName.S).Equals(PdfName.GOTO))
                        {
                            //get the link from the annotation
                            sUri = linkDict.Get(PdfName.URI).ToString();
                            Log("URI: " + sUri);
                            if (String.IsNullOrEmpty(sUri))
                            {
                                continue;
                            }
                        }


                        //build the link address into a string
                        string linkTextBuilder;

                        //create a rectangle, define its paramteres, read the text under the rectangle (the anchor text for the link) and write it to the string
                        var                       LinkLocation   = annotDict.GetAsArray(PdfName.RECT);
                        List <string>             linestringlist = new List <string>();
                        iTextSharp.text.Rectangle rect           = new iTextSharp.text.Rectangle(((PdfNumber)LinkLocation[0]).FloatValue, ((PdfNumber)LinkLocation[1]).FloatValue, ((PdfNumber)LinkLocation[2]).FloatValue, ((PdfNumber)LinkLocation[3]).FloatValue);
                        RenderFilter[]            renderFilter   = new RenderFilter[1];
                        renderFilter[0] = new RegionTextRenderFilter(rect);
                        ITextExtractionStrategy textExtractionStrategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), renderFilter);
                        linkTextBuilder = PdfTextExtractor.GetTextFromPage(reader, i, textExtractionStrategy).Trim();
                        Log(linkTextBuilder);

                        String sUriHTTPSPrefix = sUri.Substring(0, 5);
                        String sUriWWWPrefix   = sUri.Substring(0, 3);

                        if (sUriHTTPSPrefix.Equals("https"))
                        {
                            Log("Prefix: " + sUriHTTPSPrefix);
                        }
                        else if (sUriWWWPrefix.Equals("www"))
                        {
                            Log("Prefix: " + sUriWWWPrefix);
                        }


                        if (sUri.Length.Equals(70) && sUriHTTPSPrefix.Equals("https"))
                        {
                            //instantiate the web request and response objects
                            WebRequest  httpReq  = WebRequest.Create(sUri);
                            WebResponse response = httpReq.GetResponse();

                            //check website response from request and save status to string
                            string webStatus = ((HttpWebResponse)response).StatusDescription.ToString();
                            Log("Webstatus: " + webStatus);

                            //check website response url from request and save url to string
                            string responseURL = ((HttpWebResponse)response).ResponseUri.ToString();
                            Log("Response URI: " + responseURL);

                            //split the response url string to just sku number after the "="
                            string webSite = responseURL.Split('=')[1];
                            Log("Response SKU: " + webSite);

                            //split the link harvested from the annotations in the pdf after the "="
                            string sku = sUri.Split('=')[1];
                            Log("PDF SKU: " + sku);

                            //truncate the split string to just the sku (removes any extra symbols, such as copywright, which were captured in the rectangle)
                            string finalSku = sku.Substring(0, 7);
                            Log("PDF SKU Final: " + finalSku);

                            //delete asteriks from sku
                            var deleteChars = new string[] { "*" };
                            foreach (var c in deleteChars)
                            {
                                linkTextBuilder = finalSku.Replace(c, string.Empty);
                            }

                            //truncate the split string to just the sku (removes any extra symbols, such as copywright, which were captured in the rectangle)
                            string linkText = linkTextBuilder.Substring(0, 7);
                            Log("Link SKU Final: " + linkText);

                            //default status of string match is "NO MATCH"
                            string match = "\tNO MATCH";

                            //make a blank IPEndPoint
                            IPEndPoint remoteEP = null;

                            //create a new httpwebrequest
                            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sUri);

                            //bind IPEndPoint from the remote end point to a variable
                            req.ServicePoint.BindIPEndPointDelegate = delegate(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
                            {
                                remoteEP = remoteEndPoint;
                                return(null);
                            };

                            //get the response from the request
                            req.GetResponse();
                            Log("HTTP response: " + req.GetResponse());

                            //set remoteEndPoint to string for display
                            string hostIP = remoteEP.Address.ToString();
                            Log("Host IP: " + hostIP);

                            //stop the request to make way for a new request on next iteration
                            req.Abort();

                            //if sku from PDF link, website response link, and pdf anchor text all match then change match
                            if (linkText.Equals(sku) && webSite.Equals(sku))
                            {
                                match = "MATCH";
                            }

                            //add data to datagridview
                            this.skuGrid.Rows.Add(i, sku, linkTextBuilder, webSite, match, webStatus, hostIP);
                            //close http request and response
                            response.Close();

                            if (token.IsCancellationRequested)
                            {
                                // Clean up here, then...
                                token.ThrowIfCancellationRequested();
                                Log("Cancellation token: " + token);
                                MessageBox.Show("Scrape stopped");
                                throbber.Hide();
                                skuGrid.Show();
                            }
                        }
                        else if (!sUri.Length.Equals(70) && sUriWWWPrefix.Equals("www") ||
                                 !sUri.Length.Equals(70) && sUriHTTPSPrefix.Equals("https"))
                        {
                            //instantiate the web request and response objects
                            WebRequest  httpReq  = WebRequest.Create(sUri);
                            WebResponse response = httpReq.GetResponse();

                            //check website response from request and save status to string
                            string webStatus = ((HttpWebResponse)response).StatusDescription.ToString();
                            Log("Web Status: " + webStatus);

                            //check website response url from request and save url to string
                            string responseURL = ((HttpWebResponse)response).ResponseUri.ToString();
                            Log("Response URI: " + responseURL);

                            //split the response url string to just sku number after the "="
                            string webSite = responseURL;
                            Log("Response SKU: " + webSite);

                            //default status of string match is "NO MATCH"
                            string match = "\tNO MATCH";

                            //make a blank IPEndPoint
                            IPEndPoint remoteEP = null;

                            //create a new httpwebrequest
                            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sUri);

                            //bind IPEndPoint from the remote end point to a variable
                            req.ServicePoint.BindIPEndPointDelegate = delegate(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
                            {
                                remoteEP = remoteEndPoint;
                                return(null);
                            };

                            //get the response from the request
                            req.GetResponse();
                            Log("HTTP Response: " + req.GetResponse());

                            //set remoteEndPoint to string for display
                            string hostIP = remoteEP.Address.ToString();
                            Log("Host IP: " + hostIP);

                            //stop the request to make way for a new request on next iteration
                            req.Abort();

                            //delete asteriks from sku
                            var deleteChars = new string[] { "*" };
                            foreach (var c in deleteChars)
                            {
                                linkTextBuilder = linkTextBuilder.Replace(c, string.Empty);
                            }

                            //if sku from PDF link, website response link, and pdf anchor text all match then change match
                            if (linkTextBuilder.Equals(webSite))
                            {
                                match = "MATCH";
                            }

                            //add data to datagridview
                            this.skuGrid.Rows.Add(i, null, linkTextBuilder, webSite, match, webStatus, hostIP);
                            //close http request and response
                            response.Close();

                            if (token.IsCancellationRequested)
                            {
                                // Clean up here, then...
                                token.ThrowIfCancellationRequested();
                                Log("Cancellation token: " + token);
                                MessageBox.Show("Scrape stopped");
                                throbber.Hide();
                                skuGrid.Show();
                            }
                        }
                    }
                }
                MessageBox.Show("Scrape complete");
                throbber.Hide();
                skuGrid.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Log("EXCEPTION ERROR: " + ex + " " + ex.HelpLink);
                throbber.Hide();
                skuGrid.Show();
            }
            finally
            {
                taskIsRunning = false;

                //update grid
                skuGrid.Update();

                //close PDF reader
                reader.Close();

                WriteLog(log);
            }
        }
Пример #12
0
		protected iTextSharp.text.Rectangle ConvertToPdfRectangle ()
		{
			ScreenRectToPdfRectConverter rectangleConverter = new ScreenRectToPdfRectConverter(this.converter);
			
			iTextSharp.text.Rectangle r = (iTextSharp.text.Rectangle)rectangleConverter.ConvertTo(null,System.Globalization.CultureInfo.InvariantCulture,
			                                                                                      this.styleDecorator.DisplayRectangle,
			                                                                                      typeof(iTextSharp.text.Rectangle));
			
			iTextSharp.text.Rectangle rr = new iTextSharp.text.Rectangle(r.Left,r.Bottom -2,
			                                                             r.Left + r.Width,r.Bottom  + r.Height);
			
			return rr;
		}
Пример #13
0
 public RectAndText(iTextSharp.text.Rectangle rect, String text)
 {
     this.Rect = rect;
     this.Text = text;
 }
Пример #14
0
        private void Sign(string fieldName, int signaturePage, iTextSharp.text.Rectangle signatureLocation, string defaultSignName, string defaultSignEmail, string defaultSignReason)
        {
            CertificateSelector certSelector = new CertificateSelector();

            if (certSelector.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            string certPath = certSelector.CertificatePath;
            string certPwd  = certSelector.CertificatePassPhrase;

            NameReasonInput nameReasonInput = new NameReasonInput();
            DialogResult    dialogResult    = nameReasonInput.ShowDialog(sigDb, defaultSignName, defaultSignEmail, defaultSignReason);

            if (dialogResult == DialogResult.Cancel)
            {
                return;
            }
            string name     = nameReasonInput.SignName;
            string reason   = nameReasonInput.SignReason;
            string email    = nameReasonInput.SignEmail;
            double dsvScore = 1.0;

            bool doVerification = true;

            SigObj sigRef = GetRefSigFromDb(name, email);

            if (sigRef == null)
            {
                DialogResult dr = MessageBox.Show("Reference signature not found in database, do you want to proceed without signature verification?", Application.ProductName, MessageBoxButtons.YesNo);
                if (dr == DialogResult.No)
                {
                    return;
                }
                else
                {
                    doVerification = false;
                }
            }

            SigObj sigTest = CaptureSignature(name, reason);

            if (sigTest == null)
            {
                MessageBox.Show("Signature Capture failed");
                return;
            }

            if (DemoMode)
            {
                doVerification = false;
            }

            if (doVerification)
            {
                SignatureVerifier verifier = new SignatureVerifier();
                CompareResult     res      = verifier.Verify(sigRef, sigTest);
                if (res == null)
                {
                    if (verifier.VerificationStatus == SignatureVerifier.Status.Error)
                    {
                        if (MessageBox.Show("Signature verification error - " + verifier.ErrorMessage + Environment.NewLine + "Do you want to continue?", Application.ProductName, MessageBoxButtons.YesNo) == DialogResult.No)
                        {
                            return;
                        }
                    }
                }

                SignatureCompareForm sigCompareForm = new SignatureCompareForm();
                dsvScore = res.score;
                if (sigCompareForm.ShowDialog(sigRef, sigTest, res.score) == DialogResult.Cancel)
                {
                    return;
                }
            }
            else
            {
                SignatureCompareForm sigCompareForm = new SignatureCompareForm();
                if (sigCompareForm.ShowDialog(sigRef, sigTest, 1, true) == DialogResult.Cancel)
                {
                    return;
                }
            }

            byte[] signature = RenderSignatureImageBytes(sigTest, new Size(400, 200), 0.5f, 0xff0000, 0xffffff);
            if (signature == null)
            {
                MessageBox.Show("Render signature fail");
                return;
            }

            string newFile = PdfSign(signature, certPath, certPwd, name, reason,
                                     signatureLocation,
                                     signaturePage,
                                     fieldName,
                                     dsvScore
                                     );

            if (newFile == null)
            {
                MessageBox.Show("PDF signing procedure failed");
                return;
            }
            loadPdf(newFile, false);
        }
Пример #15
0
 private Page(double width, double height, DSCore.Color color)
 {
     Rectangle = new iTextSharp.text.Rectangle((float)width, (float)height);
     Color     = color;
 }
        public JObject ObtenerFiguras(string nombrePDF)
        {
            string oldFile = nombrePDF;
            //string newFile = "C:\\Users\\Denisse\\Desktop\\EDDIE-Augmented-Reading-master\\AugmentedReadingApp\\bin\\x86\\Debug\\temporal.pdf"
            PdfReader     reader   = new PdfReader(oldFile);
            PdfDictionary pageDict = reader.GetPageN(1);



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

            double anchoPDF = pagesize.Width - 30;
            double altoPDF  = pagesize.Height - 30;
            // MessageBox.Show("Tamano pagina pdf --> ancho :" + anchoPDF + " y alto : " + altoPDF);
            float anchoImagen = 400;
            float altoImagen  = 450;
            //MessageBox.Show("Tamano imagen --> ancho :" + anchoImagen+ " y alto : " + altoImagen);

            PdfArray annotArray = pageDict.GetAsArray(PdfName.ANNOTS);

            for (int i = 0; i < annotArray.Size; ++i)
            {
                PdfDictionary curAnnot = annotArray.GetAsDict(i);
                var           subtype  = curAnnot.Get(PdfName.SUBTYPE);
                var           rect     = curAnnot.Get(PdfName.RECT);
                var           contents = curAnnot.Get(PdfName.CONTENTS);
                var           page     = curAnnot.Get(PdfName.P);
                //MessageBox.Show("Subtipo "+subtype + " coordenadas: "+rect + " y contenido "+contents);
                if (subtype.ToString() == "/Square")
                {
                    Console.WriteLine("Encontro un rectangulo/cuadrado ");

                    //MessageBox.Show("Figura rectangular detectada coor "+rect);
                    var aux_rect = rect.ToString().Split(',');
                    aux_rect[0] = aux_rect[0].Remove(0, 1);
                    aux_rect[3] = aux_rect[3].Remove(aux_rect[3].Length - 1);
                    aux_rect[0] = aux_rect[0].Replace(".", ",");
                    aux_rect[1] = aux_rect[1].Replace(".", ",");
                    aux_rect[2] = aux_rect[2].Replace(".", ",");
                    aux_rect[3] = aux_rect[3].Replace(".", ",");
                    //MessageBox.Show("el split primero " + aux_rect[0]+ " el split ultimo "+ aux_rect[3]);
                    // MessageBox.Show("Esto es rect " + aux_rect[0] + " " + aux_rect[1] + " " + aux_rect[2] + " " + aux_rect[3]);
                    int puntox1 = Convert.ToInt32(Convert.ToSingle(aux_rect[0]));
                    int puntoy1 = Convert.ToInt32(Convert.ToSingle(aux_rect[1]));
                    int puntox2 = Convert.ToInt32(Convert.ToSingle(aux_rect[2]));
                    int puntoy2 = Convert.ToInt32(Convert.ToSingle(aux_rect[3]));
                    // MessageBox.Show("puntos "+ puntox1+" ,"+ puntoy1+ " , "+ puntox2+" , "+ puntoy2);

                    // TRANSFORMAR COORDENADAS DESDE PDF
                    int nuevoX1 = (Convert.ToInt32(anchoImagen) * (puntox1 * 100 / Convert.ToInt32(anchoPDF))) / 100;
                    int nuevoX2 = (Convert.ToInt32(anchoImagen) * (puntox2 * 100 / Convert.ToInt32(anchoPDF))) / 100;
                    int nuevoY1 = ((Convert.ToInt32(altoImagen) * (puntoy1 * 100 / Convert.ToInt32(altoPDF))) / 100);
                    int nuevoY2 = ((Convert.ToInt32(altoImagen) * (puntoy2 * 100 / Convert.ToInt32(altoPDF))) / 100);
                    // MessageBox.Show("puntos " + nuevoX1 + " ," + nuevoY1 + " , " + nuevoX2 + " , " + nuevoY2);

                    Rectangle rectangulo = new Rectangle(puntox1, puntoy1, puntox1 + puntox2, puntoy1 + puntoy2);

                    //Rectangle rectangulo = new Rectangle(0, 0, 100, 200);
                    //fondo.Draw(rectangulo, new Bgr(Color.Cyan), 1);
                    Rectangle rectangulo2 = new Rectangle(nuevoX1, (int)altoImagen - nuevoY1, nuevoX2 - nuevoX1, nuevoY2 - nuevoY1);
                    //Rectangle rectangulo = new Rectangle(0, 0, 100, 200);
                    //fondo.Draw(rectangulo2, new Bgr(Color.Red), 1);
                    rectList.Add(rectangulo2);
                }


                if (subtype.ToString() == "/Circle")
                {
                    var aux_rect = rect.ToString().Split(',');
                    aux_rect[0] = aux_rect[0].Remove(0, 1);
                    aux_rect[3] = aux_rect[3].Remove(aux_rect[3].Length - 1);
                    aux_rect[0] = aux_rect[0].Replace(".", ",");
                    aux_rect[1] = aux_rect[1].Replace(".", ",");
                    aux_rect[2] = aux_rect[2].Replace(".", ",");
                    aux_rect[3] = aux_rect[3].Replace(".", ",");
                    //MessageBox.Show("el split primero " + aux_rect[0]+ " el split ultimo "+ aux_rect[3]);
                    // MessageBox.Show("Esto es rect " + aux_rect[0] + " " + aux_rect[1] + " " + aux_rect[2] + " " + aux_rect[3]);
                    int puntox1 = Convert.ToInt32(Convert.ToSingle(aux_rect[0]));
                    int puntoy1 = Convert.ToInt32(Convert.ToSingle(aux_rect[1]));
                    int puntox2 = Convert.ToInt32(Convert.ToSingle(aux_rect[2]));
                    int puntoy2 = Convert.ToInt32(Convert.ToSingle(aux_rect[3]));
                    // MessageBox.Show("puntos "+ puntox1+" ,"+ puntoy1+ " , "+ puntox2+" , "+ puntoy2);

                    // TRANSFORMAR COORDENADAS DESDE PDF
                    int nuevoX1 = (Convert.ToInt32(anchoImagen) * (puntox1 * 100 / Convert.ToInt32(anchoPDF))) / 100;
                    int nuevoX2 = (Convert.ToInt32(anchoImagen) * (puntox2 * 100 / Convert.ToInt32(anchoPDF))) / 100;
                    int nuevoY1 = ((Convert.ToInt32(altoImagen) * (puntoy1 * 100 / Convert.ToInt32(altoPDF))) / 100);
                    int nuevoY2 = ((Convert.ToInt32(altoImagen) * (puntoy2 * 100 / Convert.ToInt32(altoPDF))) / 100);
                    // MessageBox.Show("puntos " + nuevoX1 + " ," + nuevoY1 + " , " + nuevoX2 + " , " + nuevoY2);

                    Rectangle rectangulo = new Rectangle(puntox1, puntoy1, puntox1 + puntox2, puntoy1 + puntoy2);
                    //Rectangle rectangulo = new Rectangle(0, 0, 100, 200);
                    //fondo.Draw(rectangulo, new Bgr(Color.Cyan), 1);
                    Rectangle rectangulo2 = new Rectangle(nuevoX1, nuevoY1, nuevoX2 - nuevoX1, nuevoY2 - nuevoY1);
                    float     mitadX      = nuevoX1 + (rectangulo2.Width / 2) - 30;
                    float     mitadY      = (int)altoImagen - nuevoY1 + (rectangulo2.Height / 2);
                    Console.WriteLine("x1 " + nuevoX1 + "y x2 " + nuevoX2);
                    Console.WriteLine("Mitades " + mitadX + " y " + mitadY);
                    Console.WriteLine("tamanos " + rectangulo2.Width + " y " + rectangulo2.Height);

                    Ellipse elip = new Ellipse(new PointF(mitadX, mitadY), new Size(rectangulo2.Width - 30, rectangulo2.Height), 90);
                    //Rectangle rectangulo = new Rectangle(0, 0, 100, 200);

                    //fondo.Draw(elip, new Bgr(Color.Blue), 1);
                    //pictureBox1.Image = fondo.Bitmap;
                    ellipseList.Add(elip);
                }
            }



            //Guarda figuras en formato json
            string resultado = "{\"figuras\" : {\"rectangulos\" : [";
            string auxRes    = "";
            int    j         = 0;

            if (rectList.Count == 0)
            {
                auxRes = auxRes + "],";
            }
            else
            {
                foreach (var item in rectList)
                {
                    if (rectList.Count - 1 == j)
                    {
                        // auxRes = auxRes + "\"rect" + j + "\":{";
                        auxRes = auxRes + "{\"puntoX\":";
                        auxRes = auxRes + "\"" + item.X + "\",";
                        auxRes = auxRes + "\"puntoY\":";
                        auxRes = auxRes + "\"" + item.Y + "\",";
                        auxRes = auxRes + "\"width\":";
                        auxRes = auxRes + "\"" + item.Width + "\",";
                        auxRes = auxRes + "\"height\":";
                        auxRes = auxRes + "\"" + item.Height + "\"}]";
                    }
                    else
                    {
                        // auxRes = auxRes + "\"rect" + j + "\":{";
                        auxRes = auxRes + "{\"puntoX\":";
                        auxRes = auxRes + "\"" + item.X + "\",";
                        auxRes = auxRes + "\"puntoY\":";
                        auxRes = auxRes + "\"" + item.Y + "\",";
                        auxRes = auxRes + "\"width\":";
                        auxRes = auxRes + "\"" + item.Width + "\",";
                        auxRes = auxRes + "\"height\":";
                        auxRes = auxRes + "\"" + item.Height + "\"},";
                    }

                    j = j + 1;
                }
            }


            auxRes = auxRes + " ,\"circulos\": [";
            //Agregar circulos y elipses
            j = 0;
            if (ellipseList.Count == 0)
            {
                auxRes = auxRes + "]";
            }
            else
            {
                foreach (var item in ellipseList)
                {
                    RotatedRect aux_ellipse = item.RotatedRect;

                    if (ellipseList.Count - 1 == j)
                    {
                        // auxRes = auxRes + "\"circ" + j + "\":{";
                        auxRes = auxRes + "{\"puntoX\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Center.X + "\",";
                        auxRes = auxRes + "\"puntoY\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Center.Y + "\",";
                        auxRes = auxRes + "\"width\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Size.Width + "\",";
                        auxRes = auxRes + "\"height\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Size.Height + "\"}]";
                    }
                    else
                    {
                        //auxRes = auxRes + "\"circ" + j + "\":{";
                        auxRes = auxRes + "{\"puntoX\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Center.X + "\",";
                        auxRes = auxRes + "\"puntoY\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Center.Y + "\",";
                        auxRes = auxRes + "\"width\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Size.Width + "\",";
                        auxRes = auxRes + "\"height\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Size.Height + "\"},";
                    }

                    j = j + 1;
                }
            }

            auxRes    = auxRes + "}}";
            resultado = resultado + auxRes;
            Console.WriteLine("Este es el resultado " + resultado);
            var final = JObject.Parse(resultado);


            return(final);
        }
Пример #17
0
        public PdfResult ViewPdf(object model, string fileName, bool download = false, iTextSharp.text.Rectangle pageSize = null)
        {
            ViewData.Model = model;

            return(new PdfResult()
            {
                FileName = fileName,
                TempData = TempData,
                ViewData = ViewData,
                Download = download
            });
        }
Пример #18
0
        public static string PrintPDFResize(string fileNamePath)
        {
            Debug.Log("CashmaticApp", "PrintPDFResize");
            string fileDirectory = Path.GetDirectoryName(fileNamePath);
            string fileName      = Path.GetFileNameWithoutExtension(fileNamePath);
            string newFile       = fileDirectory + "\\" + fileName + "_print.pdf";



            try
            {
                // open the reader
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(fileNamePath);

                iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
                //Document document = new Document(size);
                iTextSharp.text.Document document = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(size.Width + 15, size.Height + Global.CardPaymentPrintPageSizeAddHeight));

                // open the writer
                FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs);
                document.Open();

                // the pdf content
                iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;

                if (Global.cardholderReceipt != "")
                {
                    // select the font properties
                    iTextSharp.text.pdf.BaseFont bf = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER_BOLD, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED);
                    cb.SetColorFill(iTextSharp.text.BaseColor.BLACK);
                    cb.SetFontAndSize(bf, 8);

                    int StartAt = Global.CardPaymentPrintStartAt + Global.CardPaymentPrintPageSizeAddHeight;

                    foreach (string line in Global.cardholderReceipt.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
                    {
                        // write the text in the pdf content
                        cb.BeginText();
                        // put the alignment and coordinates here
                        cb.ShowTextAligned(0, line, Global.CardPaymentPrintLeft, StartAt, 0);
                        cb.EndText();
                        StartAt = StartAt - Global.CardPaymentPrintLineHeight;
                    }
                }

                //// create the new page and add it to the pdf
                iTextSharp.text.pdf.PdfImportedPage page = writer.GetImportedPage(reader, 1);
                cb.AddTemplate(page, 10, +Global.CardPaymentPrintPageSizeAddHeight);

                // close the streams and voilá the file should be changed :)
                document.Close();
                fs.Close();
                writer.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                Debug.Log("CashmaticApp", ex.ToString());
            }

            return(newFile);
        }
        private void AddSignature(PdfReader pdf, PdfSignatureAppearance sap, Juschubut.PdfDigitalSign.CertificateInfo certificate)
        {
            int anchoPagina = (int)pdf.GetPageSize(1).Width;

            var rectangle = this.Appearance.GetRectangle(anchoPagina);

            var signatureRect = new iTextSharp.text.Rectangle((float)rectangle.X, (float)rectangle.Y, (float)(rectangle.X + rectangle.Width), (float)(rectangle.Y + rectangle.Height));

            int pagina = pdf.NumberOfPages;

            if (this.Appearance.Page.HasValue && this.Appearance.Page.Value <= pdf.NumberOfPages)
            {
                pagina = this.Appearance.Page.Value;
            }

            sap.SetVisibleSignature(signatureRect, pagina, null);

            sap.SignDate    = DateTime.Now;
            sap.Acro6Layers = true;

            sap.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;

            if (!string.IsNullOrEmpty(this.Appearance.SignatureImage))
            {
                var fileInfo = new FileInfo(this.Appearance.SignatureImage);

                if (!fileInfo.Exists)
                {
                    this.Log(string.Format("No se encontro archivo de firma ológrafa ({0})", this.Appearance.SignatureImage));
                }
                else if (fileInfo.Length == 0)
                {
                    this.Log(string.Format("El archivo de firma ológrafa está vacio ({0})", this.Appearance.SignatureImage));
                }
                else
                {
                    try
                    {
                        sap.SignatureGraphic = iTextSharp.text.Image.GetInstance(new Uri(this.Appearance.SignatureImage));
                    }
                    catch (Exception ex)
                    {
                        Log(string.Format("Error al leer el archivo de firma ológrafo. El archivo esta dañado, no es un archivo .png, o no se puede tener acceso de lectura. {0}", this.Appearance.SignatureImage));

                        StringBuilder sb = new StringBuilder();

                        var ex2 = ex;

                        do
                        {
                            sb.AppendLine(ex2.Message);

                            ex2 = ex2.InnerException;
                        }while (ex2 != null);

                        Log("Error: " + sb.ToString());


                        if (!string.IsNullOrEmpty(this.Appearance.SignatureImageDefault))
                        {
                            try
                            {
                                Log("Cargando firma por default");

                                sap.SignatureGraphic = iTextSharp.text.Image.GetInstance(new Uri(this.Appearance.SignatureImageDefault));
                            }
                            catch (Exception ex3)
                            {
                                Log(ex3.Message);
                            }
                        }
                    }

                    sap.SignatureRenderingMode     = PdfSignatureAppearance.RenderingMode.GRAPHIC;
                    sap.SignatureGraphic.Alignment = iTextSharp.text.Image.ALIGN_TOP;
                }
            }

            // Descripcion de la Firma
            iTextSharp.text.Font textFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, (float)10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

            var phrase = new iTextSharp.text.Phrase();

            phrase.Font = textFont;
            int fontPre   = 6;
            int fontFirma = this.Appearance.Height < 100 ? 8 : 10;
            int fontPost  = this.Appearance.Height < 100 ? 7 : 10;

            if (this.Appearance.PreFirma != null)
            {
                AddTexto(phrase, this.Appearance.PreFirma, iTextSharp.text.Font.NORMAL, fontPre);
            }

            AddTexto(phrase, certificate.CN, iTextSharp.text.Font.BOLD, fontFirma);

            if (this.Appearance.PostFirma != null)
            {
                AddTexto(phrase, this.Appearance.PostFirma, iTextSharp.text.Font.NORMAL, fontPost);
            }

            PdfTemplate n2 = sap.GetLayer(0);
            ColumnText  ct = new ColumnText(n2);

            float x = n2.BoundingBox.Left;
            float y = n2.BoundingBox.Top;
            float w = n2.BoundingBox.Width;
            float h = n2.BoundingBox.Height;

            float x1 = x;
            float y1 = y;
            float x2 = x + w;
            float y2 = y - h;

            // new working code: crreate a table
            PdfPTable table = new PdfPTable(1);

            table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            table.SetWidths(new[] { 1 });
            table.WidthPercentage = 100;
            table.AddCell(new PdfPCell(phrase)
            {
                HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER,
                VerticalAlignment   = iTextSharp.text.Element.ALIGN_BOTTOM,
                FixedHeight         = y1,
                Border = iTextSharp.text.Rectangle.NO_BORDER
            });
            ct.SetSimpleColumn(x1, y1, x2, y2);
            ct.AddElement(table);
            ct.Go();
        }
 /// <summary>
 /// Gets itextsharp rectangle from string
 /// </summary>
 /// <param name="pagesize"></param>
 /// <returns></returns>
 public static iTextSharp.text.Rectangle PageSize(string pagesize)
 {
     iTextSharp.text.Rectangle r = iTextSharp.text.PageSize.GetRectangle(pagesize);
     return(r);
 }
Пример #21
0
 public ChunksAndRects(iTextSharp.text.Rectangle rect, string text)
 {
     Rect = rect;
     Text = text;
 }
Пример #22
0
 public iTextSharp.text.Rectangle ToPDF()
 {
     iTextSharp.text.Rectangle PDFPage = Rectangle;
     PDFPage.BackgroundColor = Color.ToPDFColor();
     return(PDFPage);
 }
Пример #23
0
 public static System.Drawing.SizeF GetPageSize2(this PdfReader pr, int pageI)
 {
     iTextSharp.text.Rectangle r = pr.GetPageSize(pageI);
     return(new System.Drawing.SizeF(r.Width, r.Height));
 }
Пример #24
0
 /// <summary>
 /// Sets the page size to PageSize.A4 for instance.
 /// </summary>
 /// <param name="pageSize">selected page size</param>
 public void CustomPageSize(iTextSharp.text.Rectangle pageSize)
 {
     _pdfReport.DataBuilder.DefaultPageSize(pageSize);
 }
Пример #25
0
 /* ----------------------------------------------------------------- */
 ///
 /// ToSize
 ///
 /// <summary>
 /// Converts from iTextSharp.text.Rectable to SizeF.
 /// </summary>
 ///
 /* ----------------------------------------------------------------- */
 private static SizeF ToSize(this iTextSharp.text.Rectangle src) =>
 new SizeF(src.Width, src.Height);
Пример #26
0
 private void Sign(string fieldName, int signaturePage, iTextSharp.text.Rectangle signatureLocation)
 {
     Sign(fieldName, signaturePage, signatureLocation, null, null, null);
 }
Пример #27
0
        /// <summary>
        /// 添加倾斜水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="waterMarkName"></param>
        /// <param name="userPassWord"></param>
        /// <param name="ownerPassWord"></param>
        /// <param name="permission"></param>
        public void PdfStampInExistingFileV4(string inputfilepath, string outputfilepath, string waterMarkName, string userPassWord, string ownerPassWord, int permission)
        {
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

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

                int            total = pdfReader.NumberOfPages + 1;
                PdfContentByte content;
                BaseFont       font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState      gs   = new PdfGState();
                gs.FillOpacity = 0.2f;//透明度


                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
                float width  = psize.Width;
                float height = psize.Height;

                int  j = waterMarkName.Length;
                char c;
                int  rise = 0;

                float ta = 1f, tb = 0f, tc = 0f, td = 1f, tx = 0f, ty = 0f;
                ta = ta + 2f;
                td = td + 2f;
                ty = ty - 0.15f;
                tc = tc + 0.3f;

                for (int i = 1; i < total; i++)
                {
                    rise    = 100;
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    content.BeginText();
                    content.SetColorFill(iTextSharp.text.BaseColor.LIGHT_GRAY);
                    content.SetFontAndSize(font, 60);
                    content.SetTextRise(rise);
                    content.SetGState(gs);
                    //content.SetTextMatrix(ta, tb, tc, td, tx, ty);
                    content.ShowTextAligned(iTextSharp.text.Element.ALIGN_LEFT, waterMarkName, 300, 500, 45);


                    //content.SetTextRise(rise);

                    content.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, waterMarkName, 400, 400, 45);


                    content.ShowTextAligned(iTextSharp.text.Element.ALIGN_RIGHT, waterMarkName, 500, 300, 45);
                    //for (int k = 0; k < j; k++)
                    //{
                    //    content.SetTextRise(rise);
                    //    content.SetGState(gs);
                    //    c = waterMarkName[k];
                    //    content.ShowText(c + "");
                    //    rise -= 20;
                    //}
                    content.EndText();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
        }
Пример #28
0
        private string PdfSign(byte[] signature, string certPath, string password, string name, string reason, iTextSharp.text.Rectangle signatureRect, int signaturePage, string fieldName, double dsvScore)
        {
            FileStream  ksfs = null;
            Pkcs12Store pk12 = null;

            try
            {
                ksfs = new FileStream(certPath, FileMode.Open);
                pk12 = new Pkcs12Store(ksfs, password.ToCharArray());

                string alias = "";
                foreach (string al in pk12.Aliases)
                {
                    if (pk12.IsKeyEntry(al) && pk12.GetKey(al).Key.IsPrivate)
                    {
                        alias = al;
                        break;
                    }
                }

                Org.BouncyCastle.Pkcs.X509CertificateEntry[] ce = pk12.GetCertificateChain(alias);
                ICollection <X509Certificate> chain             = new List <X509Certificate>();
                foreach (X509CertificateEntry c in ce)
                {
                    chain.Add(c.Certificate);
                }

                AsymmetricKeyEntry         pk         = pk12.GetKey(alias);
                RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

                string tmpFile = System.IO.Path.GetTempFileName();

                FileStream fs      = new FileStream(tmpFile, FileMode.Create);
                PdfStamper stamper = PdfStamper.CreateSignature(reader, fs, '\0');

                PdfContentByte cb             = stamper.GetOverContent(signaturePage);
                Image          integrityImage = Properties.Resources.integrity_red;
                if (dsvScore > Properties.Settings.Default.GreenThreshold)
                {
                    integrityImage = Properties.Resources.integrity;
                }
                else if (dsvScore > Properties.Settings.Default.YellowThreshold)
                {
                    integrityImage = Properties.Resources.integrity_yellow;
                }
                iTextSharp.text.Image imgIntegrity = iTextSharp.text.Image.GetInstance(integrityImage, ImageFormat.Png);
                imgIntegrity.SetAbsolutePosition(signatureRect.Left, signatureRect.Bottom - 20);
                imgIntegrity.ScalePercent(50.0f);
                cb.AddImage(imgIntegrity);

                iTextSharp.text.Image imgVerified = iTextSharp.text.Image.GetInstance(Properties.Resources.verified, ImageFormat.Png);
                imgVerified.SetAbsolutePosition(signatureRect.Left + 20, signatureRect.Bottom - 20);
                imgVerified.ScalePercent(50.0f);
                cb.AddImage(imgVerified);

                PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                appearance.Reason = reason;

                //uncomment this portion only
                //appearance.SignatureGraphic = iTextSharp.text.Image.GetInstance(signature);
                //appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
                //appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(40, 110, 240, 210), 1, "Signature");
                appearance.SetVisibleSignature(signatureRect, signaturePage, fieldName);
                //appearance.Certificate = chain[0]; to remain commented out

                /*
                 * PdfTemplate n2 = appearance.GetLayer(2);
                 * ColumnText ct = new ColumnText(n2);
                 * ct.SetSimpleColumn(n2.BoundingBox);
                 * string backgroundText = "Digitally signed by " + Properties.Settings.Default.DefaultName + "\nOn: " + appearance.SignDate.ToString() + "\nReason: " + appearance.Reason;
                 * iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph(backgroundText);
                 * ct.AddElement(paragraph);
                 * ct.Go();
                 */
                string backgroundText = "Digitally signed by " + name + "\nOn: " + appearance.SignDate.ToString() + "\nReason: " + appearance.Reason;
                appearance.Layer2Text = backgroundText;
                appearance.Image      = iTextSharp.text.Image.GetInstance(signature);

                //appearance.ImageScale = 1;

                IExternalSignature pks = new PrivateKeySignature((ICipherParameters)parameters, DigestAlgorithms.SHA256);
                MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CADES);

                ksfs.Close();

                //stamper.Close();
                //fs.Close();

                return(tmpFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }
        }
Пример #29
0
        //PDF盖章
        private bool PDFWatermark(string inputfilepath, string outputfilepath, X509Certificate2 cert)
        {
            string ModelPicName = textGZpath.Text;    //印章文件路径
            int    zyz = comboYz.SelectedIndex;       //加印章方式
            int    zqfz = comboQfz.SelectedIndex;     //加骑缝章方式
            int    sftype = comboBoxBL.SelectedIndex; //印章缩放方式
            float  sfsize, qfzwzbl;

            float.TryParse(textBili.Text, out sfsize);  //印章缩放尺寸
            float.TryParse(textWzbl.Text, out qfzwzbl); //骑缝章位置比例
            float picbl = 1.003f;                       //别问我这个数值怎么来的
            float picmm = 2.842f;                       //别问我这个数值怎么来的

            PdfGState state = new PdfGState();

            state.FillOpacity = 0.6f;//印章图片整体透明度

            //throw new NotImplementedException();
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

            try
            {
                pdfReader = new PdfReader(inputfilepath);//选择需要印章的pdf
                if (comboQmtype.SelectedIndex != 0)
                {
                    //最后的true表示保留原签名
                    pdfStamper = PdfStamper.CreateSignature(pdfReader, new FileStream(outputfilepath, FileMode.Create), '\0', null, true);//加完印章后的pdf
                }
                else
                {
                    pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                }

                int numberOfPages = pdfReader.NumberOfPages;//pdf页数

                PdfContentByte waterMarkContent;

                if (zqfz == 0 && numberOfPages > 1)
                {
                    int      max = 20;//骑缝章最大分割数
                    int      ss  = numberOfPages / max + 1;
                    int      sy  = numberOfPages - ss * max / 2;
                    int      sys = sy / ss;
                    int      syy = sy % ss;
                    int      pp  = max / 2 + sys;
                    Bitmap[] nImage;
                    int      startpage = 0;
                    for (int i = 0; i < ss; i++)
                    {
                        int tmp = pp;
                        if (i < syy)
                        {
                            tmp++;
                        }
                        nImage = subImages(ModelPicName, tmp);
                        for (int x = 1; x <= tmp; x++)
                        {
                            int page = startpage + x;
                            waterMarkContent = pdfStamper.GetOverContent(page);                                                                         //获取当前页内容
                            int rotation = pdfReader.GetPageRotation(page);                                                                             //获取当前页的旋转度
                            iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(page);                                                              //获取当前页尺寸
                            iTextSharp.text.Image     image = iTextSharp.text.Image.GetInstance(nImage[x - 1], System.Drawing.Imaging.ImageFormat.Bmp); //获取骑缝章对应页的部分
                            image.Transparency = new int[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };                                                      //这里透明背景的图片会变黑色,所以设置黑色为透明
                            waterMarkContent.SaveState();                                                                                               //通过PdfGState调整图片整体的透明度
                            waterMarkContent.SetGState(state);
                            //image.GrayFill = 20;//透明度,灰色填充
                            //image.Rotation//旋转
                            //image.ScaleToFit(140F, 320F);//设置图片的指定大小
                            //image.RotationDegrees//旋转角度
                            float sfbl, imageW, imageH;
                            if (sftype == 0)
                            {
                                sfbl   = sfsize * picbl;//别问我为什么要乘这个
                                imageW = image.Width * sfbl / 100f;
                                imageH = image.Height * sfbl / 100f;
                                //image.ScalePercent(sfbl);//设置图片比例
                                image.ScaleToFit(imageW, imageH);//设置图片的指定大小
                            }
                            else
                            {
                                sfbl   = sfsize * picmm;//别问我为什么要乘这个
                                imageW = sfbl / tmp;
                                imageH = sfbl;
                                image.ScaleToFit(imageW, imageH);//设置图片的指定大小
                            }

                            //水印的位置
                            float xPos, yPos;
                            if (rotation == 90 || rotation == 270)
                            {
                                xPos = psize.Height - imageW;
                                yPos = (psize.Width - imageH) * (100 - qfzwzbl) / 100;
                            }
                            else
                            {
                                xPos = psize.Width - imageW;
                                yPos = (psize.Height - imageH) * (100 - qfzwzbl) / 100;
                            }
                            image.SetAbsolutePosition(xPos, yPos);
                            waterMarkContent.AddImage(image);
                            waterMarkContent.RestoreState();
                        }
                        startpage += tmp;
                    }
                }

                if (zyz != 0 || comboQmtype.SelectedIndex != 0)
                {
                    iTextSharp.text.Image img = null;
                    float sfbl, imgW = 0, imgH = 0;
                    float xPos = 0, yPos = 0;
                    bool  all = false;
                    int   signpage = 0;

                    if (zyz != 0)
                    {
                        img = iTextSharp.text.Image.GetInstance(ModelPicName);               //创建一个图片对象
                        img.Transparency = new int[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //这里透明背景的图片会变黑色,所以设置黑色为透明

                        if (sftype == 0)
                        {
                            sfbl = sfsize * picbl;//别问我为什么要乘这个
                            imgW = img.Width * sfbl / 100f;
                            imgH = img.Height * sfbl / 100f;
                            //img.ScalePercent(sfbl);//设置图片比例
                            img.ScaleToFit(imgW, imgH);//设置图片的指定大小
                        }
                        else
                        {
                            sfbl = sfsize * picmm;//别问我为什么要乘这个
                            imgW = sfbl;
                            imgH = sfbl * img.Height / img.Width;
                            img.ScaleToFit(imgW, imgH);//设置图片的指定大小,实际只能指定宽度,高度还是按照图片比例计算的
                        }
                    }

                    if (zyz == 1)
                    {
                        signpage = numberOfPages;
                    }
                    else if (zyz == 2)
                    {
                        signpage = 1;
                    }
                    else if (zyz == 3)
                    {
                        signpage = numberOfPages;
                        all      = true;
                    }

                    for (int i = 1; i <= numberOfPages; i++)
                    {
                        if (all || i == signpage)
                        {
                            waterMarkContent = pdfStamper.GetOverContent(i);            //获取当前页内容
                            int rotation = pdfReader.GetPageRotation(i);                //获取指定页面的旋转度
                            iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(i); //获取当前页尺寸

                            waterMarkContent.SaveState();                               //通过PdfGState调整图片整体的透明度
                            waterMarkContent.SetGState(state);

                            float     wbl    = 0;
                            float     hbl    = 1;
                            DataRow[] arrRow = dtPos.Select("Path = '" + inputfilepath + "' and Page = " + i);
                            if (arrRow == null || arrRow.Length == 0)
                            {
                                wbl = Convert.ToSingle(textPx.Text);     //这里根据比例来定位
                                hbl = 1 - Convert.ToSingle(textPy.Text); //这里根据比例来定位
                            }
                            else
                            {
                                DataRow dr = arrRow[0];
                                wbl = Convert.ToSingle(dr["X"].ToString());
                                hbl = 1 - Convert.ToSingle(dr["Y"].ToString());
                            }
                            if (rotation == 90 || rotation == 270)
                            {
                                xPos = (psize.Height - imgW) * wbl;
                                yPos = (psize.Width - imgH) * hbl;
                            }
                            else
                            {
                                xPos = (psize.Width - imgW) * wbl;
                                yPos = (psize.Height - imgH) * hbl;
                            }
                            img.SetAbsolutePosition(xPos, yPos);
                            waterMarkContent.AddImage(img);
                            waterMarkContent.RestoreState();

                            //普通印章跟数字印章已经完美重叠,所以就不需要通过以下方法特殊区分了
                            //同时启用印章和数字签名的话用最后一个印章用数字签名代替
                            //if (all)
                            //{
                            //    if (comboQmtype.SelectedIndex == 0)
                            //    {
                            //        //所有页要盖章,并且不是数字签名

                            //        waterMarkContent.AddImage(img);
                            //        waterMarkContent.RestoreState();
                            //    }
                            //    else if (i != numberOfPages)
                            //    {
                            //        //所有页要盖章,要数字签名,但是不是最后一页
                            //        waterMarkContent.AddImage(img);
                            //        waterMarkContent.RestoreState();
                            //    }
                            //}
                            //else if (comboQmtype.SelectedIndex == 0)
                            //{
                            //    //只有首页或尾页要盖章,并且不是数字签名
                            //    waterMarkContent.AddImage(img);
                            //    waterMarkContent.RestoreState();
                            //}


                            ////开始增加文本
                            //waterMarkContent.BeginText();

                            //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                            ////设置字体 大小
                            //waterMarkContent.SetFontAndSize(bf, 9);

                            ////指定添加文字的绝对位置
                            //waterMarkContent.SetTextMatrix(imgLeft, 200);
                            ////增加文本
                            //waterMarkContent.ShowText("GW INDUSTRIAL LTD");

                            ////结束
                            //waterMarkContent.EndText();


                            //如果不是所有页都盖章,那对应页盖完后直接跳出循环
                            if (!all && i == signpage)
                            {
                                break;
                            }
                        }
                    }

                    //加数字签名
                    if (comboQmtype.SelectedIndex != 0)
                    {
                        Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
                        Org.BouncyCastle.X509.X509Certificate[]     chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) };

                        Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair pk = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(cert.GetRSAPrivateKey());
                        IExternalSignature externalSignature = new PrivateKeySignature(pk.Private, DigestAlgorithms.SHA256);

                        PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
                        signatureAppearance.SignDate = DateTime.Now;
                        //signatureAppearance.SignatureCreator = "";
                        //signatureAppearance.Reason = "验证身份";
                        //signatureAppearance.Location = "深圳";
                        if (zyz == 0)
                        {
                            signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(0, 0, 0, 0), numberOfPages, null);
                        }
                        else
                        {
                            signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC; //仅体现图片
                            signatureAppearance.SignatureGraphic       = img;                                          //iTextSharp.text.Image.GetInstance(ModelPicName);
                            //signatureAppearance.Acro6Layers = true;

                            //StringBuilder buf = new StringBuilder();
                            //buf.Append("Digitally Signed by ");
                            //String name = cert.SubjectName.Name;
                            //buf.Append(name).Append('\n');
                            //buf.Append("Date: ").Append(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss zzz"));
                            //string text = buf.ToString();
                            //signatureAppearance.Layer2Text = text;

                            float bk = 2;//数字签名的图片要加上边框才能跟普通印章的位置完全一致
                            signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(xPos - bk, yPos - bk, xPos + imgW + bk, yPos + imgH + bk), signpage, "Signature");
                        }

                        MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(false);
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
        }
Пример #30
0
 public abstract void CreatePath(PdfContentByte contentByte,
                                 BaseLine line,
                                 IBaseStyleDecorator style,
                                 iTextSharp.text.Rectangle rectangle);
        //Automatically called for each chunk of text in the PDF
        public override void RenderText(TextRenderInfo renderInfo)
        {
            base.RenderText(renderInfo);

            var startPosition = System.Globalization.CultureInfo.CurrentCulture.CompareInfo.IndexOf(renderInfo.GetText(), this.TextToSearchFor, this.CompareOptions);
            var texto = renderInfo.GetText();
            var x = renderInfo.GetText().Contains(TextToSearchFor);
            //Get the bounding box for the chunk of text
            /*if (x)
            {
                var bottomLeft = renderInfo.GetDescentLine().GetStartPoint();
                var topRight = renderInfo.GetAscentLine().GetEndPoint();

                //Create a rectangle from it
                var rect = new iTextSharp.text.Rectangle(
                                                        bottomLeft[Vector.I1],
                                                        bottomLeft[Vector.I2],
                                                        topRight[Vector.I1],
                                                        topRight[Vector.I2]
                                                        );

                this.myPoints.Add(new RectAndText(rect, renderInfo.GetText()));
            }*/

            //This code assumes that if the baseline changes then we're on a newline
            Vector curBaseline = renderInfo.GetBaseline().GetStartPoint();
            Vector curBaseline2 = renderInfo.GetAscentLine().GetEndPoint();

            //See if the baseline has changed
            if ((this.lastBaseLine != null) && (curBaseline[Vector.I2] != lastBaseLine[Vector.I2]))
            {
                //See if we have text and not just whitespace
                if ((!String.IsNullOrWhiteSpace(this.result.ToString())))
                {
                    //Mark the previous line as done by adding it to our buffers
                    this.baselines.Add(this.lastBaseLine[Vector.I2]);
                    this.strings.Add(this.result.ToString());

                    if (this.result.ToString().Contains(TextToSearchFor))
                    {
                        //Create a rectangle from it
                        var rect = new iTextSharp.text.Rectangle(startPositionWord[Vector.I1],
                                                            startPositionWord[Vector.I2],
                                                            lastAscentLine[Vector.I1],
                                                            lastAscentLine[Vector.I2]);

                        this.myPoints.Add(new RectAndText(rect, this.result.ToString()));
                        startPositionWord = null;
                        endPositionWord = null;
                    }
                }
                //Reset our "line" buffer
                this.result.Clear();
                wordended = true;
            }

            //Append the current text to our line buffer
            if (!string.IsNullOrWhiteSpace(renderInfo.GetText()))
                this.result.Append(renderInfo.GetText());

            if (!string.IsNullOrWhiteSpace(result.ToString()) && wordended)
            {
                wordended = false;
                startPositionWord = renderInfo.GetDescentLine().GetStartPoint();
            }
            //Reset the last used line
            this.lastBaseLine = curBaseline;
            this.lastAscentLine = curBaseline2;
        }
Пример #32
0
        public Stream WriteToPdf(string sourceFile, string stringToWriteToPdf)
        {
            PdfReader  reader     = null;
            PdfStamper pdfStamper = null;

            try
            {
                reader = new PdfReader(System.IO.File.ReadAllBytes(sourceFile));
                iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
                float     width  = psize.Width;
                float     height = psize.Height;
                int       j      = stringToWriteToPdf.Length;
                PdfGState gs     = new PdfGState();
                gs.FillOpacity = 0.15f;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    pdfStamper = new PdfStamper(reader, memoryStream);
                    PdfContentByte content;

                    int rise = 100;
                    for (int i = 1; i <= reader.NumberOfPages; i++) // Must start at 1 because 0 is not an actual page.
                    {
                        iTextSharp.text.Rectangle pageSize = reader.GetPageSizeWithRotation(i);
                        float          textAngle           = (float)GetHypotenuseAngleInDegreesFrom(pageSize.Height, pageSize.Width);
                        PdfContentByte pdfPageContents     = pdfStamper.GetUnderContent(i);
                        BaseFont       baseFont            = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
                        pdfPageContents.BeginText();
                        pdfPageContents.SetFontAndSize(baseFont, 40);
                        pdfPageContents.SetRGBColorFill(255, 0, 0);
                        pdfPageContents.SetColorFill(iTextSharp.text.BaseColor.GRAY);
                        pdfPageContents.SetFontAndSize(font, 60);
                        pdfPageContents.SetTextRise(rise);
                        pdfPageContents.SetGState(gs);
                        pdfPageContents.ShowTextAligned(iTextSharp.text.Element.ALIGN_LEFT, stringToWriteToPdf, 300, 500, 45);
                        pdfPageContents.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, stringToWriteToPdf, 400, 400, 45);
                        pdfPageContents.ShowTextAligned(iTextSharp.text.Element.ALIGN_RIGHT, stringToWriteToPdf, 500, 300, 45);
                        pdfPageContents.EndText();
                    }
                    pdfStamper.FormFlattening = true;
                    pdfStamper.Close();

                    return(new System.IO.MemoryStream(memoryStream.ToArray()));
                }
            }
            catch (Exception ex)
            {
                return(new System.IO.MemoryStream(File.ReadAllBytes(sourceFile)));
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Пример #33
0
            public void RenderText(iTextSharp.text.pdf.parser.TextRenderInfo renderInfo)
            {
                string curFont  = renderInfo.GetFont().PostscriptFontName;
                string curColor = "";

                try
                {
                    curColor = renderInfo.GetFillColor().ToString();
                }
                catch (Exception) { }
                curColor = curColor.Replace("Color value[", "").Replace("]", "");
                //Console.WriteLine(curColor);
                //string curColor = renderInfo.GetStrokeColor().RGB.ToString();
                //Check if faux bold is used
                if ((renderInfo.GetTextRenderMode() == (int)TextRenderMode.FillThenStrokeText))
                {
                    curFont += "-Bold";
                }

                //This code assumes that if the baseline changes then we're on a newline
                Vector curBaseline = renderInfo.GetBaseline().GetStartPoint();
                Vector topRight    = renderInfo.GetAscentLine().GetEndPoint();


                iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(curBaseline[Vector.I1], curBaseline[Vector.I2], topRight[Vector.I1], topRight[Vector.I2]);
                Single curFontSize             = rect.Height;

                if (_doFootnoteCheck == true)
                {
                    string text = renderInfo.GetText();

                    //cislo < 3.92M && cislo > 3.8M
                    //cislo == 3.9104M || cislo == 3.910416M
                    if (Decimal.TryParse(curFontSize.ToString(), out currentFontSize) && (currentFontSize == 3.890762M))
                    {
                        string s = " ";
                        if (text == "1," || text == "2," || text == "3," || text == "4," || text == "5," || text == "6," || text == "7," ||
                            text == "1" || text == "2" || text == "3" || text == "4" || text == "5" || text == "6" || text == "7")
                        {
                            //Console.WriteLine(text);

                            if (_prevDoubleText.Length > 1)
                            {
                                s = _prevDoubleText.Substring(0, 1);
                            }
                            if (_prevDoubleText.Length == 2 && s == text && topRight[1] == _prevTopRight)
                            {
                                _badFootnoteFound = true;
                            }
                            _prevDoubleText = text;
                            _prevTopRight   = topRight[1];
                        }
                    }

                    //if (Decimal.TryParse(curFontSize.ToString(), out cislo) && (cislo > 3.5M || cislo < 4M) && !string.IsNullOrWhiteSpace(text) && Int32.TryParse(text, out icislo))
                    if (Decimal.TryParse(curFontSize.ToString(), out currentFontSize) && (currentFontSize == 3.9104M || currentFontSize == 3.910416M || currentFontSize == 3.910412M || currentFontSize == 3.890762M) && !string.IsNullOrWhiteSpace(text) && Int32.TryParse(text, out currentFootnoteValue))
                    {
                        if (topRight[1] > 0 && topRight[1] < 700)
                        {
                            //Console.WriteLine(pageCounter);

                            /*
                             * Console.WriteLine("------------------------------------------");
                             * Console.WriteLine(curFontSize);
                             * Console.WriteLine("page:" + pageCounter);
                             * Console.WriteLine("txt: " + text);
                             * Console.WriteLine("prv: " + prev_icislo);
                             * Console.WriteLine("trgh: " + topRight[1]);
                             * Console.WriteLine("------------------------------------------");
                             */
                            if (!dictionary.ContainsKey(currentFootnoteValue))
                            {
                                dictionary.Add(currentFootnoteValue, (float)topRight[1]);

                                dr             = dt.NewRow();
                                dr["Number"]   = currentFootnoteValue;
                                dr["Position"] = (float)topRight[1];
                                dr["Page"]     = (int)pageCounter;
                                dt.Rows.Add(dr);
                            }
                            else
                            {
                                if (replaceCounter < 10)
                                {
                                    dictionary[currentFootnoteValue] = (float)topRight[1];
                                    for (int i = 0; i < dt.Rows.Count; i++)
                                    {
                                        if (dt.Rows[i][0].ToString() == currentFootnoteValue.ToString().Trim())
                                        {
                                            dt.Rows[i][1] = (float)topRight[1];
                                            dt.Rows[i][2] = pageCounter;
                                        }
                                    }
                                    dr             = dt.NewRow();
                                    dr["Number"]   = currentFootnoteValue;
                                    dr["Position"] = (float)topRight[1];
                                    dr["Page"]     = (int)pageCounter;
                                    dt.Rows.Add(dr);
                                    replaceCounter++;
                                }
                            }
                        }
                        _prevInumber = currentFootnoteValue;
                    }
                }
                if (curColor == "FFFF0000")
                {
                    //Console.WriteLine("Red detected!");
                    //Console.WriteLine(curColor);
                    string s = renderInfo.GetText();
                    if (string.IsNullOrWhiteSpace(s))
                    {
                    }
                    else
                    {
                        //Console.WriteLine(s);
                        redWords.Add(s);
                        _redWords++;
                    }
                }
                //See if something has changed, either the baseline, the font or the font size
                if ((this.lastBaseLine == null) || (curBaseline[Vector.I2] != lastBaseLine[Vector.I2]) || (curFontSize != lastFontSize) || (curFont != lastFont))
                {
                    //if we've put down at least one span tag close it
                    if ((this.lastBaseLine != null))
                    {
                        this.result.AppendLine("</span>");
                    }
                    //If the baseline has changed then insert a line break
                    if ((this.lastBaseLine != null) && curBaseline[Vector.I2] != lastBaseLine[Vector.I2])
                    {
                        this.result.AppendLine("<br />");
                    }
                    //Create an HTML tag with appropriate styles

                    this.result.AppendFormat("<span style=\"font-family:{0};font-size:{1}\font-color:{2}>", curFont, curFontSize, curColor);
                }

                //Append the current text
                this.result.Append(renderInfo.GetText());

                //Set currently used properties
                this.lastBaseLine = curBaseline;
                this.lastFontSize = curFontSize;
                this.lastFont     = curFont;
            }
Пример #34
0
 /**
  * Constructs a filter
  * @param filterRect the rectangle to filter text against.
  */
 public RegionTextRenderFilter(iTextSharp.text.Rectangle filterRect)
 {
     this.filterRect = new RectangleJ(filterRect);
 }
Пример #35
0
 /// <summary>
 /// Construye una nueva instancia de la clase iTextSharp.text.Rectangle
 /// a partir de un rectangulo de itext.
 /// </summary>
 /// <param name="iTextRectangle"></param>
 public PdfFontTextRectangle(iTextSharp.text.Rectangle iTextRectangle) : base(iTextRectangle)
 {
 }
Пример #36
0
        public static void Image2Pdf(string imageFile, string pdfFile, string reportPageSize, bool reportPageRotate, string mimeType, int?imgWidth, int?imgHeight)
        {
            if (string.IsNullOrEmpty(imageFile))
            {
                throw new ArgumentNullException("imageFile");
            }
            if (!System.IO.File.Exists(imageFile))
            {
                throw new Exception("文件不存在:" + imageFile);
            }

            var dir = Path.GetDirectoryName(pdfFile);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            iTextSharp.text.Document      document = null;
            iTextSharp.text.pdf.PdfWriter writer   = null;
            try
            {
                iTextSharp.text.Rectangle pageSize = iTextSharp.text.PageSize.A4;
                switch (reportPageSize)
                {
                case "A4":
                    pageSize = iTextSharp.text.PageSize.A4;
                    break;

                case "A5":
                    pageSize = iTextSharp.text.PageSize.A5;
                    break;

                case "B5":
                    pageSize = iTextSharp.text.PageSize.B5;
                    break;

                default:
                    pageSize = iTextSharp.text.PageSize.A4;
                    break;
                }
                var rectPageSize = new iTextSharp.text.Rectangle(pageSize);
                if (reportPageRotate == true)
                {
                    rectPageSize = rectPageSize.Rotate();
                }
                document = new iTextSharp.text.Document(rectPageSize, 25, 25, 25, 25);
                writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(pdfFile, FileMode.Create));
                document.Open();

                Image sourceImg = null;
                if (imgWidth != null || imgHeight != null)
                {
                    var fileStream = new FileStream(imageFile, FileMode.Open, FileAccess.Read);
                    var ms         = ImageScale2Stream(fileStream, imgWidth, imgHeight, mimeType);
                    sourceImg = System.Drawing.Image.FromStream(ms);
                }
                else
                {
                    sourceImg = System.Drawing.Image.FromFile(imageFile);
                }

                var pdfImage = iTextSharp.text.Image.GetInstance(sourceImg, System.Drawing.Imaging.ImageFormat.Png);
                pdfImage.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                pdfImage.ScaleToFit(document.Right, document.Top - document.TopMargin);

                document.Add(pdfImage);
                sourceImg.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
Пример #37
0
 public static iTextSharp.text.Rectangle GetDocumentWithBackroundColor(iTextSharp.text.Rectangle pageSize, iTextSharp.text.BaseColor backgroundColor)
 {
     pageSize.BackgroundColor = backgroundColor;
     return(pageSize);
 }
Пример #38
0
        public static void SaveImages(List<ParsedImage> images, string outputFile)
        {
            var doc = new iTextSharp.text.Document();
            try
            {
                var writer = PdfWriter.GetInstance(doc, new FileStream(outputFile, FileMode.Create));
                writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
                writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
                doc.Open();

                foreach (var parsedImage in images)
                {
                    var image = iTextSharp.text.Image.GetInstance(parsedImage.Image, parsedImage.Format);
                    var width = parsedImage.Width;
                    var height = parsedImage.Height;
                    if ((parsedImage.PerformedRotation == RotateFlipType.Rotate90FlipNone) ||
                        (parsedImage.PerformedRotation == RotateFlipType.Rotate270FlipNone))
                    {
                        var temp = width;
                        width = height;
                        height = temp;
                    }

                    var size = new iTextSharp.text.Rectangle(width, height);
                    image.ScaleAbsolute(width, height);
                    image.CompressionLevel = PdfStream.BEST_COMPRESSION;
                    doc.SetPageSize(size);
                    doc.NewPage();
                    image.SetAbsolutePosition(0, 0);
                    doc.Add(image);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                doc.Close();
            }
        }
Пример #39
0
 private Page(string pagesize, DSCore.Color color)
 {
     Rectangle = new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.GetRectangle(pagesize));
     Color     = color;
 }
 public RectAndText(iTextSharp.text.Rectangle rect, String text) {
     this.Rect = rect;
     this.Text = text;
 }
 /// <summary>
 /// Construye una nueva instancia de la clase iTextSharp.text.Rectangle
 /// a partir de un rectangulo de itext.
 /// </summary>
 /// <param name="itextRectangle"></param>
 public PdfTextBaseRectangle(iTextSharp.text.Rectangle itextRectangle)
 {
     iTextRectangle = itextRectangle;
     SetPointsFromRectangle();
 }