Close() public méthode

public Close ( ) : void
Résultat void
        /// <summary>
        /// Extract a single page from PDF file.
        /// </summary>
        /// <param name="sourceFile">The source file.</param>
        /// <param name="outputFile">The output file.</param>
        /// <param name="pageNumber">The specific page number.</param>
        public static void ExtractPage(string sourceFile, string outputFile, int pageNumber)
        {
            try
            {
                PdfReader reader = new PdfReader(sourceFile);
                if (pageNumber > reader.NumberOfPages)
                {
                    Console.WriteLine("This page number is out of reach.");
                    return;
                }

                Document document = new Document();
                PdfCopy pdfCopy = new PdfCopy(document, new FileStream(outputFile, FileMode.Create));
                document.Open();

                PdfImportedPage importedPage = pdfCopy.GetImportedPage(reader, pageNumber);
                pdfCopy.AddPage(importedPage);

                document.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #2
3
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            string filepath;
            dlg.Filter = "PDF Files(*.PDF)|*.PDF|All Files(*.*)|*.*";
            if(dlg.ShowDialog()==DialogResult.OK)
            {
                filepath = dlg.FileName.ToString();
            
            string strtext = string.Empty;
            try
            {
                PdfReader reader = new PdfReader(filepath);
                for(int page=1;page<=reader.NumberOfPages;page++)
                {
                    ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
                    String s = PdfTextExtractor.GetTextFromPage(reader, page, its);
                    s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                    strtext = strtext + s;
                    richTextBox1.Text = strtext;

                }
                reader.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        
           }
            
        }
Exemple #3
0
        public virtual void TextWithSymbolEncoding() {
            BaseFont f = BaseFont.CreateFont(BaseFont.SYMBOL, BaseFont.SYMBOL, false);
            FileStream fs = new FileStream("fonts/SymbolFontTest/textWithSymbolEncoding.pdf", FileMode.Create);
            Document doc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(doc, fs);
            Paragraph p;
            writer.CompressionLevel = 0;
            doc.Open();

            String origText = "ΑΒΓΗ€\u2022\u2663\u22c5";
            p = new Paragraph(new Chunk(origText, new Font(f, 16)));
            doc.Add(p);
            doc.Close();

            PdfReader reader = new PdfReader("fonts/SymbolFontTest/textWithSymbolEncoding.pdf");
            String text = PdfTextExtractor.GetTextFromPage(reader, 1, new SimpleTextExtractionStrategy());
            reader.Close();
            Assert.AreEqual(origText, text);

            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent("fonts/SymbolFontTest/textWithSymbolEncoding.pdf", TEST_RESOURCES_PATH + "cmp_textWithSymbolEncoding.pdf", "fonts/SymbolFontTest/", "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
Exemple #4
0
        public void ExtractPage(string sourcePdfPath, string outputPdfPath,
            int pageNumber, string password = "")
        {
            PdfReader reader = null;
            Document document = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;

            try
            {
                // Intialize a new PdfReader instance with the contents of the source Pdf file:
                reader = new PdfReader(sourcePdfPath, Encoding.UTF8.GetBytes(password));

                // Capture the correct size and orientation for the page:
                document = new Document(reader.GetPageSizeWithRotation(pageNumber));

                // Initialize an instance of the PdfCopyClass with the source
                // document and an output file stream:
                pdfCopyProvider = new PdfCopy(document,
                    new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

                document.Open();

                // Extract the desired page number:
                importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber);
                pdfCopyProvider.AddPage(importedPage);
                document.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public bool WatermarkPDF_SW(string SourcePdfPath, string OutputPdfPath, string WatermarkImageUrl, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg)
        {
            try
            {
                PdfReader reader = new PdfReader(SourcePdfPath);
                PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create));
                int n = reader.NumberOfPages;
                int i = 0;
                PdfContentByte under;
                WatermarkWidth = WatermarkWidth / n;
                //����ط�Ҫע�⣬�Ǹ���ҳ������̬����ͼƬ��ַ���м�ҳ�ͼ��ؼ�ҳ��ͼƬ
                string WatermarkPath = Server.MapPath(Request.ApplicationPath + "/HTProject/Pages/Images/��ͬ��������" + n + "/");
                string WatermarkPath2 = "";
                while (i < n)
                {
                    i++;
                    WatermarkPath2 = WatermarkPath + i + ".gif";
                    iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath2);
                    im.SetAbsolutePosition(positionX, positionY);
                    im.ScaleAbsolute(WatermarkWidth, WatermarkHeight);

                    under = stamp.GetUnderContent(i);
                    under.AddImage(im, true);
                }
                stamp.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }
            msg = "��ˮӡ�ɹ���";
            return true;
        }
Exemple #6
0
        public static void CropPdf()
        {
            var xll    = 200;
            var yll    = 170;
            var w      = 800;
            var h      = 800;
            var reader = new iTextSharp.text.pdf.PdfReader(@"C:\Projects\31g\trunk\temp\pdf\20140208110036_20.pdf");
            var n      = reader.NumberOfPages;

            iTextSharp.text.pdf.PdfDictionary pageDict;

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

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

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

            stamper.Close();
            reader.Close();
        }
        /// <summary>
        /// Compress a pdf
        /// </summary>
        /// <param name="base64Pdf">A small model to hold a base64 encoded pdf object { "content" : "somebase64" }</param>
        /// <returns>{ "content" : "smallerBase64" }</returns>
        public IHttpActionResult Post(Base64Pdf base64Pdf)
        {
            try
            {
                if (base64Pdf.data == null)
                    return BadRequest("Check supplied pdf model");

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

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

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

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

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

                return Json(new Base64Pdf { data = compressedBase64 });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
Exemple #8
0
        private string SaveTest(string pdfTemplate, string pdfXmldata, string result)
        {
            string src = @"tmpl\PIT-36_2012.pdf";
            string data = @"tmpl\PIT-36.xml";
            string res = @"tmpl\PIT-36_2012_result.pdf";

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

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

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

                stamper.Close();
                pdfReader.Close();
            }
            return res;
        }
Exemple #9
0
        public void AddFile(string fileName)
        {
            var reader = new PdfReader(fileName);

            for (var i = 1; i <= reader.NumberOfPages; i++)
            {
                var size = reader.GetPageSizeWithRotation(i);
                _document.SetPageSize(size);
                _document.NewPage();

                var page = _writer.GetImportedPage(reader, i);
                var rotation = reader.GetPageRotation(i);

                switch (rotation)
                {
                    case 90:
                        _writer.DirectContent.AddTemplate(page, 0, -1, 1, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                        break;
                    // TODO case 180
                    case 270:
                        _writer.DirectContent.AddTemplate(page, 0, 1, -1, 0, reader.GetPageSizeWithRotation(i).Width, 0);
                        break;
                    default:
                        _writer.DirectContent.AddTemplate(page, 0, 0);
                        break;
                }
            }

            reader.Close();
        }
		public static void ExtractText(string sourceFilePath, string destinationPath)
		{
			var text = new StringBuilder();
			var pdfReader = new PdfReader(sourceFilePath);
			for (int page = 1; page <= pdfReader.NumberOfPages; page++)
			{
				ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
				var currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
				currentText = Encoding.UTF8.GetString(
					Encoding.Convert(
						Encoding.Default, 
						Encoding.UTF8, 
						Encoding.Default.GetBytes(currentText))
					);
				text.Append(currentText);
			}
			pdfReader.Close();

			var temp = text.ToString();
			var regexp = new Regex(@"[ ]{2,}", RegexOptions.None);
			temp = regexp.Replace(temp, @" ");
			temp = Regex.Replace(temp, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);

			File.WriteAllText(destinationPath, temp);
		}
        public void Combine(string saveFileName, IEnumerable<string> files)
        {
            byte[] mergedPdf = null;
            using (MemoryStream ms = new MemoryStream())
            {
                using (Document document = new Document())
                {
                    using (PdfCopy copy = new PdfCopy(document, ms))
                    {
                        document.Open();

                        foreach (var item in files.OrderBy(x=> x))
                        {
                            PdfReader reader = new PdfReader(item);

                            // loop over the pages in that document
                            int n = reader.NumberOfPages;
                            for (int page = 0; page < n; )
                            {
                                copy.AddPage(copy.GetImportedPage(reader, ++page));
                            }

                            reader.Close();
                        }                        
                    }
                }
                mergedPdf = ms.ToArray();
            }

            File.WriteAllBytes(String.Concat(saveFileName, ".pdf"), mergedPdf);
        }
 public static IDictionary<String, String> GetFormFields(String pdfPath)
 {
     var reader = new PdfReader(pdfPath);
     var fields = reader.AcroFields.Fields.ToDictionary(entry => entry.Key, entry => String.Empty);
     reader.Close();
     return fields;
 }
        virtual public void TestConstructionForType0WithoutToUnicodeMap()
        {
            int pageNum = 2;
            PdfName fontIdName = new PdfName("TT9");

            string testFile = TestResourceUtils.GetResourceAsTempFile(TEST_RESOURCES_PATH, "type0FontWithoutToUnicodeMap.pdf");
            RandomAccessFileOrArray f = new RandomAccessFileOrArray(testFile);
            PdfReader reader = new PdfReader(f, null);

            try
            {
                PdfDictionary fontsDic = reader.GetPageN(pageNum).GetAsDict(PdfName.RESOURCES).GetAsDict(PdfName.FONT);
                PdfDictionary fontDicDirect = fontsDic.GetAsDict(fontIdName);
                PRIndirectReference fontDicIndirect = (PRIndirectReference)fontsDic.Get(fontIdName);

                Assert.AreEqual(PdfName.TYPE0, fontDicDirect.GetAsName(PdfName.SUBTYPE));
                Assert.AreEqual("/Identity-H", fontDicDirect.GetAsName(PdfName.ENCODING).ToString());
                Assert.IsNull(fontDicDirect.Get(PdfName.TOUNICODE), "This font should not have a ToUnicode map");

                new DocumentFont(fontDicIndirect); // this used to throw an NPE
            }
            finally
            {
                reader.Close();
            }
        }
        // samples taken from
        // http://www.c-sharpcorner.com/uploadfile/scottlysle/pdfgenerator_cs06162007023347am/pdfgenerator_cs.aspx
        // http://blog.codecentric.de/en/2010/08/pdf-generation-with-itext/
        public string SetFields(string PathSource, string PathTarget, System.Object myFields)
        {
            try
            {
                GeneXus.Utils.GXProperties Fields = (GeneXus.Utils.GXProperties)myFields;
                // create a new PDF reader based on the PDF template document
                iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(PathSource);

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

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

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

                // close the pdf
                pdfStamper.Close();
                pdfReader.Close();
                return("");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
        // http://stackoverflow.com/questions/13618847/itextsharp-combining-two-pdf-documents-into-one

        public string ConcatFiles(List <string> files, string targetPath)
        {
            try
            {
                using (var ms = new System.IO.FileStream(GetFullPath(targetPath), System.IO.FileMode.Create))
                {
                    using (Document document = new Document())
                    {
                        using (PdfCopy copy = new PdfCopy(document, ms))
                        {
                            document.Open();
                            int n;
                            foreach (string sourceFile in files)
                            {
                                //PdfReader.unethicalreading = true; // http://stackoverflow.com/questions/17666577/opening-password-protected-pdf-file-with-itextsharp
                                //byte[] password = System.Text.ASCIIEncoding.ASCII.GetBytes("Secretinfo");
                                iTextSharp.text.pdf.PdfReader reader2 = new iTextSharp.text.pdf.PdfReader(GetFullPath(sourceFile) /*, password*/);
                                n = reader2.NumberOfPages;
                                for (int page = 0; page < n;)
                                {
                                    copy.AddPage(copy.GetImportedPage(reader2, ++page));
                                }
                                // close doc
                                reader2.Close();
                            }
                        }
                    }
                    return("");
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Exemple #16
0
 public void ClassMapConflict()
 {
     InitializeDocument("-cmc");
     PdfReader reader1 = new PdfReader(SOURCE11);
     try
     {
         copy.AddPage(copy.GetImportedPage(reader1, 76, true));
     }
     catch (BadPdfFormatException)
     {
     }
     reader1.Close();
     PdfReader reader2 = new PdfReader(SOURCE12);
     bool exceptionThrown = false;
     try
     {
         copy.AddPage(copy.GetImportedPage(reader2, 76, true));
     }
     catch (BadPdfFormatException)
     {
         exceptionThrown = true;
     }
     reader2.Close();
     if (!exceptionThrown)
         Assert.Fail("BadPdfFormatException expected!");
 }
Exemple #17
0
        //Permite cargar en un PDF información en los formularios preestablecidos.
        public void llenarFormulario(string archivoOrigen, string archivoFinal, string dato)
        {
            //Establece el archivo de entrada y de salida.
            string pdfTemplate = archivoOrigen;
            string newFile = archivoFinal;

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

            AcroFields pdfFormFields = pdfStamper.AcroFields;

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

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

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

            // Cierra el PDF
            pdfStamper.Close();
            pdfReader.Close();
        }
Exemple #18
0
        public static void Test_GetPdfText_05(String file)
        {
            string outputFile = zpath.PathSetFileNameWithExtension(file, Path.GetFileNameWithoutExtension(file) + "_blocks.txt");

            Trace.WriteLine("export pdf file \"{0}\" to \"{1}\"", file, outputFile);
            FileStream   fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.Read);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);

            sw.WriteLine("export pdf text blocks of \"{0}\"", file);
            sw.WriteLine();
            //_tr.WriteLine("read pdf file \"{0}\"", file);
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(file);
            // Error	8	'LocationTextExtractionStrategy' is an ambiguous reference between 'iTextSharp.text.pdf.parser.LocationTextExtractionStrategy' and 'Test_iTextSharp.LocationTextExtractionStrategy'	C:\pib\dropbox\pbeuz\Dropbox\dev\project\Source\Source_01\Source\Test\Test_iTextSharp\Test_iTextSharp_f.cs	649	13	Source_01
            iTextSharp.text.pdf.parser.LocationTextExtractionStrategy strategy = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                sw.WriteLine("================ page {0} ================", page);
                //GetTextFromPage(reader, page, strategy);
                Test_iTextSharp.PdfTools.ProcessContentPage(reader, page, strategy);
                PrintTextBlocks(sw, strategy.textBlocks);
                sw.WriteLine();
            }
            //string s = strategy.GetResultantText();
            //_tr.WriteLine("LocationTextExtractionStrategy()");
            reader.Close();
            //List<TextChunk> locationalResult = strategy.locationalResult;
            //string s = GetResultantText(locationalResult);
            //_tr.WriteLine(s);
            //PrintResultantText(locationalResult);
            sw.Close();
        }
 /// <summary>
 /// Fills out and flattens a form with the name, company and country.
 /// </summary>
 /// <param name="src"> the path to the original form </param>
 /// <param name="dest"> the path to the filled out form </param>
 public void ManipulatePdf(String src, String dest)
 {
     PdfReader reader = new PdfReader(src);
     PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)); // create?
     int n = reader.NumberOfPages;
     Rectangle pagesize;
     for (int i = 1; i <= n; i++)
     {
         PdfContentByte under = stamper.GetUnderContent(i);
         pagesize = reader.GetPageSize(i);
         float x = (pagesize.Left + pagesize.Right)/2;
         float y = (pagesize.Bottom + pagesize.Top)/2;
         PdfGState gs = new PdfGState();
         gs.FillOpacity = 0.3f;
         under.SaveState();
         under.SetGState(gs);
         under.SetRGBColorFill(200, 200, 0);
         ColumnText.ShowTextAligned(under, Element.ALIGN_CENTER,
             new Phrase("Watermark", new Font(Font.FontFamily.HELVETICA, 120)),
             x, y, 45);
         under.RestoreState();
     }
     stamper.Close();
     reader.Close();
 }
Exemple #20
0
        public void TestExtraXObjects()
        {
#if DRAWING
            PdfReader sourceR = new PdfReader(CreateImagePdf());
            try
            {
                int sourceXRefCount = sourceR.XrefSize;

                Document document = new Document();
                MemoryStream outStream = new MemoryStream();
                PdfCopy copy = new PdfCopy(document, outStream);
                document.Open();
                PdfImportedPage importedPage = copy.GetImportedPage(sourceR, 1);
                copy.AddPage(importedPage);
                document.Close();

                PdfReader targetR = new PdfReader(outStream.ToArray());
                int destinationXRefCount = targetR.XrefSize;

                //        TestResourceUtils.saveBytesToFile(createImagePdf(), new File("./source.pdf"));
                //        TestResourceUtils.saveBytesToFile(out.toByteArray(), new File("./result.pdf"));

                Assert.AreEqual(sourceXRefCount, destinationXRefCount);
            }
            finally
            {
                sourceR.Close();
            }
#endif// DRAWING
        }
 public void Sign(String src, String dest,
                  ICollection<X509Certificate> chain, X509Certificate2 pk,
                  String digestAlgorithm, CryptoStandard subfilter,
                  String reason, String location,
                  ICollection<ICrlClient> crlList,
                  IOcspClient ocspClient,
                  ITSAClient tsaClient,
                  int estimatedSize) {
     // Creating the reader and the stamper
     PdfReader reader = null;
     PdfStamper stamper = null;
     FileStream os = null;
     try {
         reader = new PdfReader(src);
         os = new FileStream(dest, FileMode.Create);
         stamper = PdfStamper.CreateSignature(reader, os, '\0');
         // Creating the appearance
         PdfSignatureAppearance appearance = stamper.SignatureAppearance;
         appearance.Reason = reason;
         appearance.Location = location;
         appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
         // Creating the signature
         IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
         MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize,
                                    subfilter);
     }
     finally {
         if (reader != null)
             reader.Close();
         if (stamper != null)
             stamper.Close();
         if (os != null)
             os.Close();
     }
 }
        public static void WritePDF(string outFilename, Dictionary<string, string> keys)
        {
            using (var existingFileStream = new FileStream(DefaultTemplatePath, FileMode.Open))
            using (var newFileStream = new FileStream(outFilename, FileMode.Create))
            {
                var pdfReader = new PdfReader(existingFileStream);
                var stamper = new PdfStamper(pdfReader, newFileStream);

                try
                {
                    var form = stamper.AcroFields;
                    var fieldKeys = form.Fields.Keys;
                    //File.WriteAllLines(@"fields.txt", fieldKeys.OfType<string>().ToArray());
                    foreach (string fieldKey in fieldKeys)
                    {
                        if (keys.ContainsKey(fieldKey))
                        {
                            form.SetField(fieldKey, keys[fieldKey]);
                        }
                    }
                    stamper.FormFlattening = true;
                }
                finally
                {
                    stamper.Close();
                    pdfReader.Close();
                }
            }
        }
 // ---------------------------------------------------------------------------    
 public virtual void Write(Stream stream)
 {
     using (ZipFile zip = new ZipFile())
     {
         // Get the movies
         IEnumerable<Movie> movies = PojoFactory.GetMovies();
         string datasheet = Path.Combine(Utility.ResourcePdf, DATASHEET);
         string className = this.ToString();
         // Fill out the data sheet form with data
         foreach (Movie movie in movies)
         {
             if (movie.Year < 2007) continue;
             PdfReader reader = new PdfReader(datasheet);
             string dest = string.Format(RESULT, movie.Imdb);
             using (MemoryStream ms = new MemoryStream())
             {
                 using (PdfStamper stamper = new PdfStamper(reader, ms))
                 {
                     Fill(stamper.AcroFields, movie);
                     if (movie.Year == 2007) stamper.FormFlattening = true;
                 }
                 reader.Close();
                 zip.AddEntry(dest, ms.ToArray());
             }
         }
         zip.AddFile(datasheet, "");
         zip.Save(stream);
     }
 }
 /// <summary>
 /// Sign
 /// </summary>
 /// <param name="input">The input.</param>
 /// <param name="output">The output.</param>
 /// <param name="certificate">The certificate.</param>
 public override void Sign(Stream input, Stream output, X509Certificate2 certificate)
 {
     CheckInputOutputAndCertificate(input, output, certificate);
     PdfReader reader = null;
     try
     {
         reader = new PdfReader(input);
         using (var stamper = PdfStamper.CreateSignature(reader, output, '\0', null, true))
         {
             var cp = new Org.BouncyCastle.X509.X509CertificateParser();
             var chain = new[] { cp.ReadCertificate(certificate.RawData) };
             var sig = stamper.SignatureAppearance;
             SetSigPosition(sig, reader.AcroFields.GetSignatureNames().Count);
             SetSigText(sig, chain);
             SetSigCryptoFromX509(sig, certificate, chain);
         }
     }
     finally
     {
         if (reader != null)
         {
             reader.Close();
         }
     }
 }
Exemple #25
0
        // pdfファイルのパスワードを解除し、解除済みの一時ファイルのパスを返す。
        // 一時ファイルは使用した後に消去すること。
        public string DetachPassword(string path, string password)
        {
            // pathで渡されたファイルが存在するか?
            if (!File.Exists(path))
            {
                throw new FileNotFoundException();
            }

            var reader = new iTextSharp.text.pdf.PdfReader(path, Encoding.UTF8.GetBytes(password));
            string tmp = Path.GetTempFileName();
            using (FileStream fs = new FileStream(tmp, FileMode.Create))
            {
                iTextSharp.text.pdf.PdfCopyFields copy = new iTextSharp.text.pdf.PdfCopyFields(fs);
                copy.AddDocument(reader);
                copy.Close();
            }
            reader.Close();

            //一時ファイル名を元の名前にリネーム
            string renamepath = Path.GetDirectoryName(tmp) + "\\" + Path.GetFileName(path);
            File.Copy(tmp, renamepath, true);
            File.Delete(tmp);

            return renamepath;
        }
 public bool WatermarkPDF_SN(string SourcePdfPath, string OutputPdfPath, string WatermarkPath, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg)
 {
     try
     {
         PdfReader reader = new PdfReader(SourcePdfPath);
         PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create));
         int n = reader.NumberOfPages;
         int i = 0;
         PdfContentByte under;
         iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath);
         im.SetAbsolutePosition(positionX, positionY);
         im.ScaleAbsolute(WatermarkWidth, WatermarkHeight);
         while (i < n)
         {
             i++;
             under = stamp.GetUnderContent(i);
             under.AddImage(im, true);
         }
         stamp.Close();
         reader.Close();
     }
     catch (Exception ex)
     {
         msg = ex.Message;
         return false;
     }
     msg = "��ˮӡ�ɹ���";
     return true;
 }
        /// <summary>
        /// 根据pdf模板写入数据生成新的pdf
        /// </summary>
        /// <param name="saveFile">保存的新pdf路径</param>
        /// <param name="sourceFile">原pdf路径</param>
        public static void AddNewPdf(string saveFile, string sourceFile)
        {
            //写入新的pdf地址
            //sourceFile = @"C:\Users\Administrator\Desktop\ABC\temp.pdf";
            //sourceFile = @"C:\Users\Administrator\Desktop\temp123.pdf";
            iTextSharp.text.pdf.PdfDocument document = new iTextSharp.text.pdf.PdfDocument();
            //读取的源pdf文件
            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(sourceFile);
            PdfStamper pdfStamper    = new PdfStamper(pdfReader, new FileStream(saveFile, FileMode.OpenOrCreate));
            AcroFields pdfFormFields = pdfStamper.AcroFields;

            pdfStamper.FormFlattening = true;
            //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            //BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            pdfFormFields.AddSubstitutionFont(simheiBase);
            Dictionary <string, string> para = new Dictionary <string, string>();

            para.Add($"Numbering", "12369999995");
            for (int i = 1; i < 38; i++)
            {
                para.Add($"Numbering{i}", "12365");
            }
            foreach (KeyValuePair <string, string> parameter in para)
            {
                pdfStamper.AcroFields.SetField(parameter.Key, parameter.Value);
            }
            //pdfStamper.AcroFields.SetField("Names", "李朝强");
            //pdfStamper.AcroFields.SetField("chk", "yes", true);
            pdfStamper.Close();
            pdfReader.Close();
        }
Exemple #28
0
        public void ConvertToImage(string _rutaPDF, int width, int height)
        {
            iTextSharp.text.pdf.PdfReader reader = null;
            int currentPage = 1;
            int pageCount   = 0;

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            reader = new iTextSharp.text.pdf.PdfReader(_rutaPDF);
            reader.RemoveUnusedObjects();
            pageCount = reader.NumberOfPages;
            string ext = System.IO.Path.GetExtension(_rutaPDF);

            for (int i = 1; i <= 1; i++)
            {
                iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(_rutaPDF);
                string outfile = _rutaPDF.Replace((System.IO.Path.GetFileName(_rutaPDF)), (System.IO.Path.GetFileName(_rutaPDF).Replace(".pdf", "") + "_" + i.ToString()) + ext);
                reader1.RemoveUnusedObjects();
                iTextSharp.text.Document    doc    = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create));
                doc.Open();
                for (int j = 1; j <= 1; j++)
                {
                    iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage);
                    pdfCpy.SetFullCompression();
                    pdfCpy.AddPage(page);
                    currentPage += 1;
                }
                doc.Close();
                pdfCpy.Close();
                reader1.Close();
                reader.Close();
            }
        }
        public static bool IsScannedPdf(string pdfFilePath)
        {
            // Start analyzing the PDF
            PdfReader reader = new PdfReader(pdfFilePath);
            PdfDictionary resources;

            try
            {
                // Go through all the pages
                for (int p = 1; p <= reader.NumberOfPages; p++)
                {
                    // Find the embedded resources
                    PdfDictionary dic = reader.GetPageN(p);
                    resources = dic.GetAsDict(PdfName.RESOURCES);
                    if (resources != null)
                    {
                        // If we have any embedded font, it's not scanned
                        if (resources.GetAsDict(PdfName.FONT) != null)
                            return false;
                    }
                }
                return true;
            }
            finally
            {
                reader.Close();
            }
        }
 // ---------------------------------------------------------------------------    
 /**
  * Renames the fields in an interactive form.
  * @param datasheet the path to the original form
  * @param i a number that needs to be appended to the field names
  * @return a byte[] containing an altered PDF file
  */
 private static byte[] RenameFieldsIn(string datasheet, int i)
 {
     List<string> form_keys = new List<string>();
     using (var ms = new MemoryStream())
     {
         PdfReader reader = new PdfReader(datasheet);
         // Create the stamper
         using (PdfStamper stamper = new PdfStamper(reader, ms))
         {
             // Get the fields
             AcroFields form = stamper.AcroFields;
             // so we aren't hit with 'Collection was modified' exception
             foreach (string k in stamper.AcroFields.Fields.Keys)
             {
                 form_keys.Add(k);
             }
             // Loop over the fields
             foreach (string key in form_keys)
             {
                 // rename the fields
                 form.RenameField(key, string.Format("{0}_{1}", key, i));
             }
         }
         reader.Close();
         return ms.ToArray();
     }
 }
Exemple #31
0
        public static void ReplaceCoverPDF(string InFile, string InCover, string OutFile)
        {
            if (CoverFunction == 0)
            {
                List <string> Files = new List <string>
                {
                    InFile,
                    InCover
                };
                Files.Sort();
                MergePDF(Files, OutFile);
                return;
            }

            LogHelper.Log("Replace the cover to the original file", LogType.Successful);

            FileStream stream = null;
            Document   doc    = null;
            PdfCopy    pdf    = null;

            try
            {
                stream = new FileStream(OutFile, FileMode.Create);
                doc    = new Document();
                pdf    = new PdfCopy(doc, stream);

                doc.Open();

                //Aggiungo la cover
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(InCover);
                int coverPage = reader.NumberOfPages;

                LogHelper.Log($"Add the cover: {InCover} of {coverPage} pages");
                pdf.AddDocument(reader);
                reader.Close();

                //Aggiungo il resto del documento
                reader = new iTextSharp.text.pdf.PdfReader(InFile);
                int count = reader.NumberOfPages;
                coverPage++;
                List <int> pages = Enumerable.Range(coverPage, count - coverPage + 1).ToList();

                LogHelper.Log($"Add the file: {InFile} from Page: {coverPage}");
                pdf.AddDocument(reader, pages);

                reader.Close();

                AddBookmarks(InFile, pdf);
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString(), LogType.Error);
            }
            finally
            {
                pdf?.Dispose();
                doc?.Dispose();
                stream?.Dispose();
            }
        }
Exemple #32
0
        public static void Test_GetPdfText_04(string file)
        {
            string outputFile = zpath.PathSetFileNameWithExtension(file, Path.GetFileNameWithoutExtension(file) + "_text.txt");

            _tr.WriteLine("export pdf file \"{0}\" to \"{1}\"", file, outputFile);
            FileStream   fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.Read);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);

            sw.WriteLine("export pdf text of \"{0}\"", file);
            sw.WriteLine();
            iTextSharp.text.pdf.PdfReader  reader   = new iTextSharp.text.pdf.PdfReader(file);
            LocationTextExtractionStrategy strategy = new LocationTextExtractionStrategy();

            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                sw.WriteLine("================ page {0} ================", page);
                //string s = GetTextFromPage(reader, 1, strategy);
                //GetTextFromPage(reader, page, strategy);
                Test_iTextSharp.PdfTools.ProcessContentPage(reader, page, strategy);
                string s = strategy.GetResultantText();
                sw.Write(s);
                sw.WriteLine();
            }
            //_tr.WriteLine("LocationTextExtractionStrategy()");
            //_tr.WriteLine(s);
            reader.Close();
            sw.Close();
        }
        public static PdfExtractionResult PDF_ExportImage(string filename, string dirForExtractions, int divider, bool checkResult, bool joinImages)
        {
            var details = new PdfExtractionResult();

            DataAccess.Instance.g_curProgress = 0;
            evnt_UpdateCurBar();

            var imagesList = new Dictionary<PageImageIndex, Image>();          

            // Ask itextsharp to extract image
            var pdfReader = new PdfReader(filename);
            var pdfParser = new PdfReaderContentParser(pdfReader);
            var pdfListener = new PDFImageListener(dirForExtractions);

            double tem0 = divider;
            double pgc = pdfReader.NumberOfPages;
            double CurOneStep = (double)(tem0 / pgc);

            details.Pages = (int)pgc;

            for (int i = 1; i <= pgc; i++)
            {
                pdfListener.PageIndex = i;
                // itextsharp send response to listener
                pdfParser.ProcessContent(i, pdfListener);

                DataAccess.Instance.g_curProgress += CurOneStep;
                evnt_UpdateCurBar();
            }

            imagesList = pdfListener.ImagesList; 
            details.ImagesBeforeMerge = pdfListener.ImagesList.Count;
            details.ImagesAfterMerge = details.ImagesBeforeMerge;

            if (checkResult && pdfReader.NumberOfPages != details.ImagesBeforeMerge)
            {
                if (joinImages)
                {
                    ImageJoiner cp = new ImageJoiner();
                    imagesList = cp.Merge(pdfListener.ImagesList, dirForExtractions);
                }

                details.ImagesAfterMerge = imagesList.Count;

                if(pdfReader.NumberOfPages != imagesList.Count)
                {                    
                    //Directory.Delete(dirForExtractions, true);
                    //throw new Exception(string.Format("Error extracting {0} : {1} images for {2} pages", Path.GetFileName(filename), pdfListener.ImagesList.Count, pdfReader.NumberOfPages));
                }
            }

            if (pdfReader != null)
                pdfReader.Close();

            // Write images to disk (because of memory problem write directly to file now)
            //WriteImages(dirForExtractions, imagesList);

            return details;
        }
 public static string ReadJsonFromPdf(string filename) {
     var reader = new PdfReader(filename);
     object jsonText = reader.Info["HADocsOpenData"];
     reader.Close();
     if (jsonText == null)
         return null; //data was not found in PDF
     return jsonText.ToString();
 }
        public static void ExtractImagesFromPDF(string password, string key, string docPath, string pagePath, PageCollection pages)
        {
            Page page = null;
            // NOTE:  This will only get the first image it finds per page.
            PdfReader pdf = new PdfReader(Utility.Security.AES.DecryptFile(key, docPath));
            //RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(p);

            try
            {
                for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
                {
                    PdfDictionary pg = pdf.GetPageN(pageNumber);

                    // recursively search pages, forms and groups for images.
                    PdfObject obj = FindImageInPDFDictionary(pg);
                    if (obj != null)
                    {

                        int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                        PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
                        PdfStream pdfStrem = (PdfStream)pdfObj;
                        byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                        if ((bytes != null))
                        {
                            using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                            {
                                memStream.Position = 0;
                                System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
                                // must save the file while stream is open.

                                page = new Page();
                                page.Order = pages.Count;
                                page.Save();
                                page.Token = Utility.Security.AES.GetToken(page.Id, password);
                                //string path = System.IO.Path.Combine(page.Filename, String.Format(@"{0}.jpg", pageNumber));
                                System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
                                parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                System.Drawing.Imaging.ImageCodecInfo jpegEncoder = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.FormatDescription == "JPEG");
                                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                                img.Save(ms, jpegEncoder, parms);
                                System.IO.File.WriteAllBytes(System.IO.Path.Combine(pagePath, page.Filename), SoftFluent.Samples.GED.Utility.Security.AES.EncryptStream(page.Token, ms.ToArray()).ToArray());
                                ms.Close();
                                pages.Add(page);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                pdf.Close();
                //raf.Close();
            }
        }
        /// <summary>
        ///  Extract Image from PDF file and Store in Image Object
        /// </summary>
        /// <param name="pdfPath">Specify PDF Source Path</param>
        /// <returns>elenco dei path relativi alle immagini estratte</returns>
        public static List<string> ExtractImages(String pdfPath)
        {
            var pathTokens = pdfPath.Split(new char[] { '\\' });
            var session = pathTokens[pathTokens.Length - 2];
            var basePath = Path.GetDirectoryName(pdfPath);
            var filename = Path.GetFileNameWithoutExtension(pdfPath);

            List<string> urls = new List<string>();

               RandomAccessFileOrArray RAFObj = null;
            PdfReader PDFReaderObj = null;
            PdfObject PDFObj = null;
            PdfStream PDFStreamObj = null;

            //try
            //{
            RAFObj = new RandomAccessFileOrArray(pdfPath);//(PDFSourcePath);
            PDFReaderObj = new PdfReader(RAFObj, null);

            var info = PDFReaderObj.Info;
            var j = 0;
            for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
            {
                PDFObj = PDFReaderObj.GetPdfObject(i);

                if ((PDFObj != null) && PDFObj.IsStream())
                {
                    PdfDictionary pd = (PdfDictionary)PDFObj;

                    PDFStreamObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                    iTextSharp.text.pdf.PdfObject subtype = PDFStreamObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);

                    if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                    {
                        filename = filename + "_" + (++j).ToString();
                        byte[] bytes = PdfReader.GetStreamBytesRaw((iTextSharp.text.pdf.PRStream)PDFStreamObj);

                        Tiff tiff = Tiff.Open(Path.Combine(basePath, filename + ".tif"), "w");
                        tiff.SetField(TiffTag.IMAGEWIDTH, UInt32.Parse(pd.Get(PdfName.WIDTH).ToString()));
                        tiff.SetField(TiffTag.IMAGELENGTH, UInt32.Parse(pd.Get(PdfName.HEIGHT).ToString()));
                        tiff.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4);
                        tiff.SetField(TiffTag.BITSPERSAMPLE, UInt32.Parse(pd.Get(PdfName.BITSPERCOMPONENT).ToString()));
                        tiff.SetField(TiffTag.SAMPLESPERPIXEL, 1);
                        tiff.WriteRawStrip(0, bytes, bytes.Length);
                        tiff.Close();

                        var bmp = tiffToBitmap(Path.Combine(basePath, filename + ".tif"));
                        if (bmp != null)
                        {
                            bmp.Save(Path.Combine(basePath, filename + ".bmp"));
                            urls.Add( session + "/" + filename + ".bmp");
                        }
                    }
                }
            }
            PDFReaderObj.Close();
            return urls;
        }
Exemple #37
0
 /// <summary>
 /// Concatenates two or more PDF files into one file.
 /// </summary>
 /// <param name="inputFiles">A string array containing the names of the pdf files to concatenate</param>
 /// <param name="outputFile">Name of the concatenated file.</param>
 public void ConcatenatePDFFiles(String[] inputFiles, String outputFile)
 {
     if (inputFiles != null && inputFiles.Length > 0)
     {
         if (!String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile))
         {
             var concatDocument = new iTextSharpText.Document();
             var outputCopy     = new iTextSharpPDF.PdfCopy(concatDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite));
             concatDocument.Open();
             try
             {
                 for (int loop = 0; loop <= inputFiles.GetUpperBound(0); loop++)
                 {
                     var inputDocument = new iTextSharpPDF.PdfReader(inputFiles[loop]);
                     for (int pageLoop = 1; pageLoop <= inputDocument.NumberOfPages; pageLoop++)
                     {
                         concatDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(pageLoop));
                         outputCopy.AddPage(outputCopy.GetImportedPage(inputDocument, pageLoop));
                     }
                     inputDocument.Close();
                     outputCopy.FreeReader(inputDocument);
                     inputDocument = null;
                 }
                 concatDocument.Close();
                 outputCopy.Close();
             }
             catch
             {
                 if (concatDocument != null && concatDocument.IsOpen())
                 {
                     concatDocument.Close();
                 }
                 if (outputCopy != null)
                 {
                     outputCopy.Close();
                 }
                 if (File.Exists(outputFile))
                 {
                     try
                     {
                         File.Delete(outputFile);
                     }
                     catch { }
                 }
                 throw;
             }
         }
         else
         {
             throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString);
         }
     }
     else
     {
         throw new ArgumentNullException("inputFiles", exceptionArgumentNullOrEmptyString);
     }
 }
        protected void AddDataTableToPDF()
        {
            string taskid = HttpContext.Current.Session["Name"].ToString();

            HttpContext.Current.Session.Timeout = 60;
            String pathin  = System.Web.HttpContext.Current.Server.MapPath("~/storepdf/" + taskid + ".pdf");
            String pathout = System.Web.HttpContext.Current.Server.MapPath("~/editorpdf/" + taskid + ".pdf");

            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(pathin);
            PdfStamper stamper  = new PdfStamper(reader, new FileStream(pathout, FileMode.Create));
            int        n        = reader.NumberOfPages;
            string     imageURL = System.Web.HttpContext.Current.Server.MapPath(".") + "/img/caslab.jpg";

            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageURL);
            img.SetAbsolutePosition(60f, 790f);

            for (var i = 1; i <= n; i++)
            {
                PdfContentByte over = null;


                over = stamper.GetOverContent(i);
                BaseFont bf_times = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
                over.SetFontAndSize(bf_times, 10);
                over.AddImage(img);
                over.BeginText();
                over.ShowTextAligned(PdfContentByte.ALIGN_CENTER, taskid, 500, 800, 0);
                over.EndText();
                over.BeginText();
                string pagenumber = "Page  " + i + "  of  " + n + "";
                over.ShowTextAligned(1, pagenumber, 500, 790, 0);
                over.EndText();
                over.BeginText();
                string headerline = "_______________________________________________________________________________________";
                // put the alignment and coordinates here
                over.ShowTextAligned(1, headerline, 295, 780, 0);
                over.EndText();

                over.BeginText();
                string footerline = "________________________________________________________________________________________";
                // put the alignment and coordinates here
                over.ShowTextAligned(1, footerline, 295, 60, 0);
                over.EndText();

                over.BeginText();
                string footer = "This document and all the information contained here are confidential and exclusive  property of CASLAB.";
                over.ShowTextAligned(PdfContentByte.ALIGN_CENTER, footer, 300, 40, 0);
                over.EndText();

                over.BeginText();
                string footer1 = "and maynot be reproduced,disclosed,or made public in any manner prior to express written authorization by CASLAB.";
                over.ShowTextAligned(PdfContentByte.ALIGN_CENTER, footer1, 300, 30, 0);
                over.EndText();
            }
            stamper.Close();
            reader.Close();
        }
 public virtual void RemoveOcgLayer() {
     PdfReader reader = new PdfReader(INPUT);
     OCGRemover ocgRemover = new OCGRemover();
     ocgRemover.RemoveLayers(reader, "Do you see me?");
     PdfDictionary catalog = reader.Catalog;
     Assert.IsNull(catalog.Get(PdfName.OCPROPERTIES));
     Assert.AreNotSame(PdfName.USEOC, catalog.Get(PdfName.PAGEMODE));
     reader.Close();
 }
Exemple #40
0
        private void CreateOutput(string PDFInput)
        {
            try
            {
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(@PDFInput);
                FileStream fs    = new FileStream(@PDFInput.Replace("Input", "Output"), FileMode.Create, FileAccess.Write);
                PdfStamper stamp = new PdfStamper(reader, fs);
                //Loop from here

                //MessageBox.Show(dataGridView1.RowCount.ToString());
                for (int i = 0; i < dataGridView1.RowCount - 1; i++)
                {
                    string comptype = dataGridView1.Rows[i].Cells[3].Value.ToString();

                    string complocation = dataGridView1.Rows[i].Cells[1].Value.ToString();

                    float llx = float.Parse(complocation.Split(' ')[0]);
                    float lly = float.Parse(complocation.Split(' ')[1]);
                    float urx = float.Parse(complocation.Split(' ')[2]);
                    float ury = float.Parse(complocation.Split(' ')[3]);


                    if (comptype == "TE")
                    {
                        int          x  = Int32.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString());
                        PdfFormField ff = PdfFormField.CreateTextField(stamp.Writer, false, false, 50);
                        ff.SetWidget(new iTextSharp.text.Rectangle(llx, lly, urx, ury), PdfAnnotation.HIGHLIGHT_INVERT);
                        ff.SetFieldFlags(PdfAnnotation.FLAGS_PRINT);
                        ff.FieldName = dataGridView1.Rows[i].Cells[0].Value.ToString();
                        stamp.AddAnnotation(ff, x);
                    }
                    else if (comptype == "CB")
                    {
                        int             x     = Int32.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString());
                        RadioCheckField fCell = new RadioCheckField(stamp.Writer, new iTextSharp.text.Rectangle(llx, lly, urx, ury), dataGridView1.Rows[i].Cells[0].Value.ToString(), "Yes");
                        fCell.CheckType = RadioCheckField.TYPE_CROSS;
                        PdfFormField footerCheck = null;
                        footerCheck = fCell.CheckField;
                        stamp.AddAnnotation(footerCheck, x);
                    }
                    else
                    {
                    }
                }
                //Loop Ends here

                stamp.Close();
                fs.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #41
0
        public static void CreatePDFFromHTMLFile(string HtmlStream, string Destinationpath, string FileNamePDF)
        {
            try
            {
                object TargetFile       = FileNamePDF;
                string ModifiedFileName = string.Empty;
                string FinalFileName    = string.Empty;


                ExportHtmltoPdf.HtmlToPdfBuilder builder = new ExportHtmltoPdf.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
                ExportHtmltoPdf.HtmlPdfPage      first   = builder.AddPage();
                first.AppendHtml(HtmlStream);
                byte[] file = builder.RenderPdf();
                File.WriteAllBytes(TargetFile.ToString(), file);

                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
                ModifiedFileName = TargetFile.ToString();
                ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");
                iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);

                reader.Close();

                if (File.Exists(TargetFile.ToString()))
                {
                    File.Delete(TargetFile.ToString());
                }
                FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
                File.Copy(ModifiedFileName, FinalFileName);
                if (File.Exists(ModifiedFileName))
                {
                    File.Delete(ModifiedFileName);
                }

                // string path = Request.PhysicalApplicationPath + "\\files\\" + "ConvertHTMLToPDF.pdf";

                WebClient client = new WebClient();
                Byte[]    buffer = client.DownloadData(Destinationpath);


                if (buffer != null)
                {
                    HttpContext.Current.Response.ContentType = "application/pdf";
                    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileNamePDF);
                    HttpContext.Current.Response.TransmitFile(Destinationpath);
                    HttpContext.Current.Response.End();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #42
0
        public static void RotatePdf()
        {
            var reader   = new iTextSharp.text.pdf.PdfReader(@"C:\Projects\31g\trunk\temp\pdf\Europe_565BCE.pdf");
            var pageDict = reader.GetPageN(1);

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

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

            stamper.Close();
            reader.Close();
        }
Exemple #43
0
        private static void MergePDF(List <string> FileName, int ActiveId)
        {
            try
            {
                //string[] fileArray = new string[2];
                //fileArray[0] = File1;
                //fileArray[1] = File2;

                PdfReader reader = null;
                // PdfReader.unethicalreading = true;
                iTextSharp.text.Document sourceDocument = null;
                PdfCopy         pdfCopyProvider         = null;
                PdfImportedPage importedPage;
                // string outputPdfPath = @"D:\SyncData\DeltaMDocuments\SymplifiedSuits\" + ActiveId.ToString() + ".pdf";
                string outputPdfPath = @"C:\DeltaM\CRM\ClientsDocuments\SymplifiedSuits\" + ActiveId.ToString() + ".pdf";

                sourceDocument  = new iTextSharp.text.Document();
                pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

                //output file Open
                sourceDocument.Open();


                //files list wise Loop
                for (int f = 0; f < FileName.Count; f++)
                {
                    int pages = TotalPageCount(FileName[f]);
                    if (pages > 0)
                    {
                        reader = new PdfReader(FileName[f]);
                        if (pages < 2)
                        {
                            PdfReader.unethicalreading = true;
                        }
                        //Add pages in new file
                        for (int i = 1; i <= pages; i++)
                        {
                            importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                            pdfCopyProvider.AddPage(importedPage);
                        }

                        reader.Close();
                    }
                }
                //save the output file
                sourceDocument.Close();
            }
            catch (Exception ex)
            {
            }
        }
Exemple #44
0
        public static void Test_GetPdfText_03(String file)
        {
            _tr.WriteLine("read pdf file \"{0}\"", file);
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(file);
            //byte[] bytes = reader.GetPageContent(1);
            StringWriter output = new StringWriter();

            iTextSharp.text.pdf.parser.PdfContentReaderTool.ListContentStreamForPage(reader, 1, output);
            string s = output.ToString();

            _tr.WriteLine("ListContentStreamForPage()");
            _tr.WriteLine(s);
            reader.Close();
        }
Exemple #45
0
        private void StartThread()
        {
            List <String> filePaths = new List <string>();

            // create one-page pdfs first
            iTextSharp.text.pdf.PdfReader reader = null;
            int    currentPage = 1;
            int    pageCount   = 0;
            String filepath    = textBox_file.Text;

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            reader = new iTextSharp.text.pdf.PdfReader(filepath);
            reader.RemoveUnusedObjects();
            pageCount = reader.NumberOfPages;
            string ext = System.IO.Path.GetExtension(filepath);

            for (int i = 1; i <= pageCount; i++)
            {
                iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(filepath);
                string outfile = filepath.Replace((System.IO.Path.GetFileName(filepath)), (System.IO.Path.GetFileName(filepath).Replace(".pdf", "") + "_" + i.ToString()) + ext);
                reader1.RemoveUnusedObjects();
                iTextSharp.text.Document    doc    = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create));
                doc.Open();
                for (int j = 1; j <= 1; j++)
                {
                    iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage);
                    pdfCpy.AddPage(page);
                    currentPage += 1;
                }
                doc.Close();
                pdfCpy.Close();
                reader1.Close();
                reader.Close();

                filePaths.Add(outfile);
            }

            DecomposeData decompose = new DecomposeData
            {
                filePathsPdf = filePaths,
                folder       = textBox_destFolder.Text
            };

            backgroundWorker1.RunWorkerAsync(decompose);

            label_status.Text      = localization.GetValueForItem(LocalizedItem.TextSearchStarted).Replace("%i", filePaths.Count.ToString());
            label_status.ForeColor = Color.Blue;
        }
Exemple #46
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileOne"></param>
        /// <param name="fileTwo"></param>
        /// <param name="newFile"></param>
        public static void ConcatPdf(string fileOne, string fileTwo, string newFile)
        {
            //si le premier fichier en entrée est aussi le fichier de sortie on concatène ce dernier
            var append = fileOne.Equals(newFile);

            if (append)
            {
                //on construit le fichier sortie dans un autre emplacement
                string cardFolder = Path.Combine(ServiceCfg.OutputFolderPath, @"pages\");
                newFile = Path.Combine(cardFolder, Path.GetFileName(newFile));
            }
            //fusion des pdf
            using (FileStream stream = new FileStream(newFile, FileMode.Create))
            {
                Document  pdfDoc = new Document();
                PdfReader reader;
                PdfCopy   pdf = new PdfCopy(pdfDoc, stream);
                pdfDoc.Open();

                if (File.Exists(fileOne))
                {
                    reader = new PdfReader(fileOne);
                    pdf.AddDocument(reader);
                    reader.Close();
                }

                if (File.Exists(fileTwo))
                {
                    reader = new PdfReader(fileTwo);
                    pdf.AddDocument(reader);
                    reader.Close();
                }

                if (pdfDoc != null)
                {
                    pdf.Close();
                    pdfDoc.Close();
                    if (append)
                    {
                        if (File.Exists(fileOne))
                        {
                            File.Delete(fileOne);
                        }
                        //on déplace le fichier sortie obtenu à l'emplacement d'origine
                        File.Move(newFile, fileOne);
                    }
                }
            }
        }
        /// <summary>
        /// Splits the PDF file
        /// </summary>
        /// <param name="filepath">The file to split</param>
        private void Split(string filepath)
        {
            this.statut.Text = "Début de la division";
            this.statut.Refresh();
            this.document.Text = Path.GetFileName(filepath);
            this.document.Refresh();
            PdfReader reader      = null;
            int       currentPage = 1;
            int       pageCount   = 0;
            string    dirPath     = Path.GetDirectoryName(filepath);

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            reader = new iTextSharp.text.pdf.PdfReader(filepath);
            reader.RemoveUnusedObjects();
            pageCount = reader.NumberOfPages;
            string ext = System.IO.Path.GetExtension(filepath);

            for (int i = 1; i <= pageCount; i++)
            {
                this.statut.Text = "En cours de division " + i + " / " + pageCount;
                this.statut.Refresh();
                iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(filepath);
                string outfile = filepath.Replace(System.IO.Path.GetFileName(filepath), (System.IO.Path.GetFileName(filepath).Replace(FileExtension.PDF, string.Empty) + "_" + i.ToString()) + ext);
                outfile = outfile.Substring(0, dirPath.Length).Insert(dirPath.Length, string.Empty) + "\\" + Path.GetFileName(filepath).Replace(FileExtension.PDF, string.Empty) + "_" + i.ToString() + ext;
                reader1.RemoveUnusedObjects();
                iTextSharp.text.Document    doc    = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.OpenOrCreate));
                doc.Open();
                for (int j = 1; j <= 1; j++)
                {
                    iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage);
                    pdfCpy.AddPage(page);
                    currentPage += 1;
                }

                this.progressBar1.PerformStep();
                this.progressPages = this.progressPages + 1;
                this.label1.Text   = this.progressPages + " / " + this.nbpages;
                this.label1.Refresh();
                this.statut.Text = "Fin de la division " + i + " / " + pageCount;
                this.statut.Refresh();
                doc.Close();
                pdfCpy.Close();
                reader1.Close();
                reader.Close();
            }
        }
        protected void AddDataTableToPDF()
        {
            String pathin  = System.Web.HttpContext.Current.Server.MapPath("~/frontpagepdf/" + taskid.Text + ".pdf");
            String pathout = System.Web.HttpContext.Current.Server.MapPath("~/frontpageeditpdf/" + taskid.Text + ".pdf");

            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(pathin);
            PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create));
            int        n       = reader.NumberOfPages;

            for (var i = 1; i <= n; i++)
            {
                PdfPCell  cell  = null;
                PdfPTable table = null;
                DataTable dt    = GetDataTable();
                if (dt != null)
                {
                    Font font8 = FontFactory.GetFont("ARIAL", 12);
                    table = new PdfPTable(dt.Columns.Count);
                    cell  = new PdfPCell(new Phrase(new Chunk("DATE", font8)));
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase(new Chunk("Name", font8)));
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase(new Chunk("Reviewer", font8)));
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase(new Chunk("Approver", font8)));
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase(new Chunk("Status", font8)));
                    table.AddCell(cell);
                    for (int rows = 0; rows < dt.Rows.Count; rows++)
                    {
                        for (int column = 0; column < dt.Columns.Count; column++)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                            table.AddCell(cell);
                        }
                    }
                }

                ColumnText ct = new ColumnText(stamper.GetOverContent(i));
                ct.AddElement(table);
                iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(46, 250, 560, 36);
                ct.SetSimpleColumn(36, 36, PageSize.A4.Width - 45, PageSize.A4.Height - 220);
                ct.Go();
            }
            stamper.Close();
            reader.Close();
        }
Exemple #49
0
        private static List <System.Drawing.Image> ExtractImages(byte[] PDFSourcePath)
        {
            List <System.Drawing.Image> ImgList = new List <System.Drawing.Image>();

            iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
            iTextSharp.text.pdf.PdfObject PDFObj       = null;
            iTextSharp.text.pdf.PdfStream PDFStremObj  = null;

            try
            {
                PDFReaderObj = new iTextSharp.text.pdf.PdfReader(PDFSourcePath, null);

                for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
                {
                    PDFObj = PDFReaderObj.GetPdfObject(i);

                    if ((PDFObj != null) && PDFObj.IsStream())
                    {
                        PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                        iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);

                        if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                        {
                            try
                            {
                                iTextSharp.text.pdf.parser.PdfImageObject PdfImageObj =
                                    new iTextSharp.text.pdf.parser.PdfImageObject((iTextSharp.text.pdf.PRStream)PDFStremObj);

                                System.Drawing.Image ImgPDF = PdfImageObj.GetDrawingImage();


                                ImgList.Add(ImgPDF);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
                PDFReaderObj.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return(ImgList);
        }
Exemple #50
0
        }     //  end setGraphTitle

        private void AddWatermarkText(string sourceFile, string outputFile, string watermarkText, float watermarkFontSize, float watermarkFontOpacity, float watermarkRotation)
        {
            iTextSharp.text.pdf.PdfReader      reader       = null;
            iTextSharp.text.pdf.PdfStamper     stamper      = null;
            iTextSharp.text.pdf.PdfGState      gstate       = null;
            iTextSharp.text.pdf.PdfContentByte underContent = null;
            iTextSharp.text.Rectangle          rect         = null;

            int pageCount = 0;

            try
            {
                reader  = new iTextSharp.text.pdf.PdfReader(sourceFile);
                rect    = reader.GetPageSizeWithRotation(1);
                stamper = new PdfStamper(reader, new System.IO.FileStream(outputFile, System.IO.FileMode.CreateNew), '\0', true);

                iTextSharp.text.pdf.BaseFont watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER,
                                                                                                     iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
                gstate               = new iTextSharp.text.pdf.PdfGState();
                gstate.FillOpacity   = watermarkFontOpacity;
                gstate.StrokeOpacity = watermarkFontOpacity;
                pageCount            = reader.NumberOfPages;
                for (int i = 1; i <= pageCount; i++)
                {
                    underContent = stamper.GetUnderContent(i);
                    underContent.SaveState();
                    underContent.SetGState(gstate);
                    underContent.SetColorFill(iTextSharp.text.BaseColor.DARK_GRAY);
                    underContent.BeginText();
                    underContent.SetFontAndSize(watermarkFont, watermarkFontSize);
                    underContent.SetTextMatrix(30, 30);
                    underContent.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, watermarkRotation);
                    underContent.EndText();
                    underContent.RestoreState();
                }   //  end for i loop

                stamper.Close();
                reader.Close();
            }   //  end try
            catch (Exception ex)
            {
                throw ex;
            } //  end
            return;
        }     //  end AddWatermark
Exemple #51
0
        private static InsertResult InsertImpl(IInput context, Stream input, int page, PdfImage image, PointF imageOffset, PdfImageStyle style)
        {
            var outputStream = new MemoryStream();

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

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

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

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

                return(InsertResult.CreateSuccessResult(new InsertResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = new MemoryStream(outputStream.GetBuffer())
                }));
            }
            catch (Exception ex)
            {
                return(InsertResult.FromException(
                           ex,
                           new InsertResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }
        }
Exemple #52
0
        public static void BreakApart()
        {
            var reader = new iTextSharp.text.pdf.PdfReader(@"C:\Projects\31g\trunk\temp\20140208110036.pdf");

            for (var i = 1; i < reader.NumberOfPages; i++)
            {
                var document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(i));

                var pdfCopyProvider = new iTextSharp.text.pdf.PdfCopy(document,
                                                                      new System.IO.FileStream(string.Format(@"C:\Projects\31g\trunk\temp\pdf\20140208110036_{0}.pdf", i), System.IO.FileMode.Create));
                document.Open();
                var importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                pdfCopyProvider.AddPage(importedPage);
                document.Close();
            }

            reader.Close();
        }
        //Below code is used to add the watermark on to pdfs
        // the image you use as a watermark

        private static void AddLogo(String pdfLocation, String savePdf)
        {
            try
            {
                //get the image (watermark) from the location
                iTextSharp.text.Image pageIn = iTextSharp.text.Image.GetInstance("Z:\\Automation\\RequiredDraftingDocuments\\watermark.png");
                //set the settings of the watermark image (opacity, alignment, etc)
                pageIn.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
                pageIn.ScaleToFit(300, 300);
                pageIn.Alignment = iTextSharp.text.Image.UNDERLYING;
                pageIn.SetAbsolutePosition(150, 300);
                pageIn.RotationDegrees = 30; // rotates the image 30 degrees as required
                //read the exisitng pdf to add watermark
                System.Threading.Thread.Sleep(4000);
                iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(pdfLocation);
                string FileLocation = savePdf; //place where new pdf will be saved


                //Create a temporary pdf
                PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf", "[temp].pdf"), FileMode.Create));
                //create new graphics state and assign opacity
                PdfGState graphicsState = new PdfGState();
                graphicsState.FillOpacity   = 0.2f; //set the opacity of watermark
                graphicsState.StrokeOpacity = 0.2f;
                PdfContentByte waterPDF;
                for (int page = 1; page <= pdfReader.NumberOfPages; page++) //for each page in the pdf add the water mark
                {
                    waterPDF = stamp.GetOverContent(page);
                    waterPDF.SetGState(graphicsState);
                    waterPDF.AddImage(pageIn);
                }
                stamp.FormFlattening = true;
                stamp.Close();
                pdfReader.Close();
                // now delete the original file and rename the temp file to the original file
                File.Delete(FileLocation);                                           //delete the original file
                File.Move(FileLocation.Replace(".pdf", "[temp].pdf"), FileLocation); //rename the temporary created pdf with the original pdf file name
            }
            catch (Exception ex)
            {
                throw new Exception("Error found :" + ex.GetBaseException() + " \n" + ex);
            }
        }
Exemple #54
0
        /// <summary>
        /// Retrieves the following properties as <see cref="Dictionary&lt;String,String&gt;"/> key/value pairs:
        /// Page Count, Encrypted, Pdf Version, Rebuilt
        /// </summary>
        /// <param name="filename">The PDF file</param>
        /// <returns>A <see cref="Dictionary&lt;String, String&gt;"/> object</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <remarks></remarks>
        public Dictionary <String, String> RetrieveBasicProperties(String filename)
        {
            Dictionary <String, String> basicProperties = new Dictionary <string, string>();

            if (!String.IsNullOrEmpty(filename) && !String.IsNullOrWhiteSpace(filename))
            {
                var documentReader = new iTextSharpPDF.PdfReader(new iTextSharpPDF.RandomAccessFileOrArray(filename), null);
                basicProperties.Add("Page Count", documentReader.NumberOfPages.ToString());
                basicProperties.Add("Encrypted", documentReader.IsEncrypted().ToString());
                basicProperties.Add("Pdf Version", documentReader.PdfVersion.ToString());
                basicProperties.Add("Rebuilt", documentReader.IsRebuilt().ToString());
                documentReader.Close();
            }
            else
            {
                throw new ArgumentNullException("filename", exceptionArgumentNullOrEmptyString);
            }
            return(basicProperties);
        }
Exemple #55
0
        /// <summary>
        /// extrait le contenu texte d'un fichier PDF
        /// </summary>
        /// <param name="pdfpath">chemin complet pour le fichier</param>
        /// <returns>text en brut</returns>
        public static string GetPdfText(string pdfpath)
        {
            //on exploite iTextSharp

            //Creation du reader
            PdfReader reader = new PdfReader(pdfpath);

            //Creation du contenu en sortie
            StringWriter output = new StringWriter();

            //extraction du texte pour chaque page du document
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                output.WriteLine(PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy()));
            }

            reader.Close();
            return(output.ToString());
        }
        /// <summary> iTextSharp_PNG 无法正常进行展出操作
        ///
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="outputPath"></param>
        /// <returns></returns>
        List <PPTPage> SplitePDF(string filepath, string outputPath)
        {
            List <PPTPage> pages = new List <PPTPage>();

            iTextSharp.text.pdf.PdfReader reader = null;
            int currentPage = 1;
            int pageCount   = 0;

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            reader = new iTextSharp.text.pdf.PdfReader(filepath);
            reader.RemoveUnusedObjects();
            pageCount = reader.NumberOfPages;

            for (int i = 1; i <= pageCount;)
            {
                string outfile = System.IO.Path.Combine(outputPath, i + ".png");
                iTextSharp.text.Document    doc    = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create));
                doc.Open();
                for (int j = 1; j <= 1; j++)
                {
                    iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader, currentPage);
                    pdfCpy.SetFullCompression();
                    pdfCpy.AddPage(page);
                    currentPage += 1;
                }

                Console.WriteLine("PDF TO IMAGES - {0}/{1}", ++i, pageCount);
                pages.Add(new PPTPage()
                {
                    Cover = outfile
                });

                pdfCpy.Flush();
                doc.Close();
                pdfCpy.Close();
                reader.Close();
            }

            return(pages);
        }
        /// <summary>
        /// pdf文件添加图片
        /// </summary>
        /// <param name="oldPath">源PDF文件</param>
        /// <param name="newPath">新PDF文件</param>
        /// <param name="imPath">图片地址</param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public static void AddImg(string oldPath, string newPath, string imPath, float x, float y)
        {
            iTextSharp.text.pdf.PdfDocument doc = new iTextSharp.text.pdf.PdfDocument();


            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(oldPath);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newPath, FileMode.OpenOrCreate));
            //获取PDF指定页面内容
            var pdfContentByte = pdfStamper.GetOverContent(1);
            //添加图片
            Image image = Image.GetInstance(imPath);

            //设置图片大小
            image.ScaleToFit(100, 100);
            //设置图片位置
            image.SetAbsolutePosition(x, y);
            pdfContentByte.AddImage(image);
            pdfStamper.FormFlattening = true;
            pdfStamper.Close();
            pdfReader.Close();
        }
Exemple #58
0
 private static void fillFormFields(iTextSharp.text.pdf.PdfReader reader, FileStream fs, SqlDataReader dr)
 {
     using (var pdfStamper = new PdfStamper(reader, fs))
     {
         int i = 0;
         while (dr.Read())
         {
             i++;
             pdfStamper.AcroFields.SetField("Day" + i.ToString(), FormatField(dr["Day"].ToString(), "Day"));
             pdfStamper.AcroFields.SetField("Time" + i.ToString(), FormatField(dr["Time"].ToString(), "Time"));
             pdfStamper.AcroFields.SetField("Type" + i.ToString(), FormatField(dr["Type"].ToString(), "Type"));
             pdfStamper.AcroFields.SetField("Topic" + i.ToString(), FormatField(dr["Topic"].ToString(), "Topic"));
             pdfStamper.AcroFields.SetField("Group" + i.ToString(), FormatField(dr["aaGroup"].ToString(), "aaGroup"));
             pdfStamper.AcroFields.SetField("Location" + i.ToString(), FormatField(dr["Location"].ToString(), "Location"));
             pdfStamper.AcroFields.SetField("City" + i.ToString(), FormatField(dr["City"].ToString(), "City"));
         }
         pdfStamper.FormFlattening = true;
         pdfStamper.Close();
         reader.Close();
     }
 }
Exemple #59
0
        public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
        {
            try
            {
                object TargetFile       = FileName;
                string ModifiedFileName = string.Empty;
                string FinalFileName    = string.Empty;


                GeneratePDF.HtmlToPdfBuilder builder = new GeneratePDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A3);
                builder.AddStyle("td", "border:solid 1px #000000");
                GeneratePDF.HtmlPdfPage first = builder.AddPage();

                first.AppendHtml(HtmlStream);
                byte[] file = builder.RenderPdf();

                File.WriteAllBytes(TargetFile.ToString(), file);

                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
                ModifiedFileName = TargetFile.ToString();
                ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");

                iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
                reader.Close();
                if (File.Exists(TargetFile.ToString()))
                {
                    File.Delete(TargetFile.ToString());
                }
                FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
                File.Copy(ModifiedFileName, FinalFileName);
                if (File.Exists(ModifiedFileName))
                {
                    File.Delete(ModifiedFileName);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void SetProperties(string filename)
        {
            Filename = filename;
            FileInfo fi = new FileInfo(Filename);
            Size = Math.Round(Convert.ToDouble(fi.Length)/(1048576), 2);    //1048576=1024*1024
            Extension = fi.Extension;

            if (Extension == ".pdf")
            {
                DocumentType = "Portable Document Format(.pdf)";

                PdfReader pdfr = new PdfReader(Filename);
                StringBuilder pdfText = new StringBuilder();

                TotalPages = pdfr.NumberOfPages;

                //loop to read pdf page by page

                for (int page = 1; page <= pdfr.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                    string currentText = PdfTextExtractor.GetTextFromPage(pdfr, page, strategy);

                    currentText =
                        Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8,
                                                                      Encoding.Default.GetBytes(currentText)));

                    pdfText.Append(currentText);
                }

                pdfr.Close();

                string completetext=pdfText.ToString();
               // NoOfWords=completetext.Split(' ').Length;

                NoOfWords=Regex.Matches(completetext, @"[A-Za-z0-9]+").Count;

            }

            else if (Extension == ".odt")
            {
                DocumentType = "Open Document Format(.odt)";
                ComputeStatistics();

            }

            else if (Extension == ".docx")
            {
                DocumentType = "Microsoft Word Document(.docx)";
                ComputeStatistics();
            }

            else
            {
                DocumentType = "Word 97-2003 document(.doc)";
                ComputeStatistics();

            }
        }