當前位置: 首頁>>代碼示例>>C#>>正文


C# PdfReader.Close方法代碼示例

本文整理匯總了C#中iTextSharp.text.pdf.PdfReader.Close方法的典型用法代碼示例。如果您正苦於以下問題:C# PdfReader.Close方法的具體用法?C# PdfReader.Close怎麽用?C# PdfReader.Close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在iTextSharp.text.pdf.PdfReader的用法示例。


在下文中一共展示了PdfReader.Close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: button2_Click

        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);
            }
        
           }
            
        }
開發者ID:officeravi,項目名稱:MiniProject,代碼行數:32,代碼來源:Form1.cs

示例2: Write

 // ---------------------------------------------------------------------------    
 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);
     }
 }
開發者ID:kuujinbo,項目名稱:iTextInAction2Ed,代碼行數:30,代碼來源:FillDataSheet.cs

示例3: WritePDF

        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();
                }
            }
        }
開發者ID:sidfarkus,項目名稱:highlands_school_reports,代碼行數:29,代碼來源:PDFWriter.cs

示例4: TestConstructionForType0WithoutToUnicodeMap

        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();
            }
        }
開發者ID:Niladri24dutta,項目名稱:itextsharp,代碼行數:26,代碼來源:DocumentFontTest.cs

示例5: GetFormFields

 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;
 }
開發者ID:NadavNaeh,項目名稱:Experimental,代碼行數:7,代碼來源:PdfWriterHelper.cs

示例6: ExtractPage

        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;
            }
        }
開發者ID:somanet,項目名稱:iTextTools,代碼行數:34,代碼來源:PdfExtractor.cs

示例7: TextWithSymbolEncoding

        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);
            }
        }
開發者ID:newlysoft,項目名稱:itextsharp,代碼行數:25,代碼來源:SymbolTest.cs

示例8: SaveTest

        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;
        }
開發者ID:Zawulon,項目名稱:jseverywhere,代碼行數:28,代碼來源:pdflib.cs

示例9: Post

        /// <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);
            }
        }
開發者ID:penance316,項目名稱:CompressPdfWebApi,代碼行數:40,代碼來源:PdfController.cs

示例10: AddFile

        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();
        }
開發者ID:jadesye,項目名稱:pdfbinder,代碼行數:30,代碼來源:Binder.cs

示例11: ExtractText

		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);
		}
開發者ID:w01f,項目名稱:VolgaTeam.SalesLibrary,代碼行數:25,代碼來源:PdfHelper.cs

示例12: Combine

        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);
        }
開發者ID:rickreis,項目名稱:combine-files-pdf-win-forms,代碼行數:31,代碼來源:CombineFilesExportToPDF.cs

示例13: RenameFieldsIn

 // ---------------------------------------------------------------------------    
 /**
  * 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();
     }
 }
開發者ID:kuujinbo,項目名稱:iTextInAction2Ed,代碼行數:34,代碼來源:ConcatenateForms2.cs

示例14: llenarFormulario

        //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();
        }
開發者ID:hagi07,項目名稱:Checador,代碼行數:28,代碼來源:Class1.cs

示例15: IsScannedPdf

        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();
            }
        }
開發者ID:sbxlmdsl,項目名稱:MateCat-Win-Converter,代碼行數:28,代碼來源:PdfAnalyzer.cs


注:本文中的iTextSharp.text.pdf.PdfReader.Close方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。