本文整理匯總了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);
}
}
}
示例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);
}
}
示例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();
}
}
}
示例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();
}
}
示例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;
}
示例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;
}
}
示例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);
}
}
示例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;
}
示例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);
}
}
示例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();
}
示例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);
}
示例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);
}
示例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();
}
}
示例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();
}
示例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();
}
}