本文整理匯總了C#中iTextSharp.text.pdf.PdfReader.Dispose方法的典型用法代碼示例。如果您正苦於以下問題:C# PdfReader.Dispose方法的具體用法?C# PdfReader.Dispose怎麽用?C# PdfReader.Dispose使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類iTextSharp.text.pdf.PdfReader
的用法示例。
在下文中一共展示了PdfReader.Dispose方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: ExtractImages
//-------------------------------------------------------------------------
private bool ExtractImages(String PDFSourcePath, Audit sourceAudit, out Exception exception)
{
//List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();
exception = null;
iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
iTextSharp.text.pdf.PdfObject PDFObj = null;
iTextSharp.text.pdf.PdfStream PDFStremObj = null;
int pageNumber = 0;
bool ok = false;
try
{
RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(PDFSourcePath);
PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);
for (int i = 0; i < PDFReaderObj.XrefSize; 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();
pageNumber++;
if (pageNumber > PDFReaderObj.NumberOfPages)
return false;
}
catch (Exception)
{
}
}
}
}
pageNumber = 0;
PageCount = PDFReaderObj.NumberOfPages;
for (int i = 0; i < PDFReaderObj.XrefSize; 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();
pageNumber++;
//using (Bitmap bmp = new Bitmap(ImgPDF))
//{
// SaveFrameFiles(PDFSourcePath, sourceAudit, bmp, pageNumber, PageCount);
try
{
SaveFrameFiles(PDFSourcePath, sourceAudit, (Bitmap)ImgPDF, pageNumber, PageCount);
}
catch (Exception)
{
ImgPDF.Dispose();
continue;
}
ImgPDF.Dispose();
ok = true;
//}
}
catch (Exception)
{ }
}
}
}
return ok;
}
catch (Exception)// ex
{
//log.LogMessage(PDFSourcePath + " Page" + pageNumber.ToString() + " ", ex);
return false;
}
finally
{
PDFReaderObj.Close();
PDFReaderObj.Dispose();
}
}
示例2: collectDataforDay
/**
* Put all data from given day into given table
*/
public static void collectDataforDay(DateTime dateTime, SQLiteConnection m_dbConnection)
{
string zeroMonth = dateTime.Month < 10 ? "0" : "";
string zeroDay = dateTime.Day < 10 ? "0" : "";
string date = zeroMonth + dateTime.Month + "/" + zeroDay + dateTime.Day + "/" + dateTime.Year;
PdfReader reader;
try
{
reader = new PdfReader("http://www.equibase.com/premium/eqbPDFChartPlus.cfm?RACE=A&BorP=P&TID=SAR&CTRY=USA&DT=" + date + "&DAY=D&STYLE=EQB");
}
catch (Exception e)
{
Console.WriteLine("CAPTCHA TIME");
Console.ReadKey();
Console.ReadKey();
reader = new PdfReader("http://www.equibase.com/premium/eqbPDFChartPlus.cfm?RACE=A&BorP=P&TID=SAR&CTRY=USA&DT=" + date + "&DAY=D&STYLE=EQB");
}
StringBuilder builder = new StringBuilder();
for (int x = 1; x <= reader.NumberOfPages; x++)
{
PdfDictionary page = reader.GetPageN(x);
IRenderListener listener = new SBTextRenderer(builder);
PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);
PdfDictionary pageDic = reader.GetPageN(x);
PdfDictionary resourcesDic = pageDic.GetAsDict(PdfName.RESOURCES);
processor.ProcessContent(ContentByteUtils.GetContentBytesForPage(reader, x), resourcesDic);
}
if (pages.Count != 0)
{
DataHandler handler = new DataHandler(dateTime, pages, m_dbConnection);
Thread thread = new Thread(new ThreadStart(handler.extractPdfData));
thread.Start();
thread.Join();
reader.Dispose();
pages.Clear();
}
else
{
// If there were no races on this particular day, simply skip it! :D
Console.WriteLine("Invalid Date: " + date);
}
}
示例3: processFolderList
/**
* Internal function used to process folders in the dictionary. These values
* usually come from the property file. It retrieves the number of files contained, whether or not
* the folder contains a new file.
*/
private List<FolderInfo> processFolderList(Dictionary<string, string> folderList)
{
List<FolderInfo> toReturn = new List<FolderInfo>();
Dictionary<String, String> keywords = null;
JavaScriptSerializer j = new JavaScriptSerializer();
SpiderWeb.Models.FolderInfo tempInfo;
string dirName;
PdfReader pdfReader = null;
BufferedStream randomAccess = null;
foreach (KeyValuePair<string, string> entry in folderList)
{
dirName = entry.Value;
FileInfo tempFile = new FileInfo(dirName);
tempInfo = new SpiderWeb.Models.FolderInfo();
tempInfo.folderName = dirName.Substring(dirName.LastIndexOf("\\") + 1);
tempInfo.folderPath = dirName;
dirName = tempFile.FullName;
if (!Directory.Exists(dirName) && (dirName.ToUpper().StartsWith(this.data["DRR_DRIVE"] + ":") || dirName.StartsWith("\\\\")))
{
Directory.CreateDirectory(dirName);
}
if (Directory.Exists(dirName))
{
string[] allFiles = Directory.GetFiles(dirName, "*pdf");
tempInfo.fileCount = allFiles.Length;
tempInfo.hasNewFile = false;
string openDirectory, currentDirectory;
foreach (string fileName in allFiles)
{
try
{
randomAccess = new BufferedStream(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), 12288);
pdfReader = new PdfReader(randomAccess, null);
if (pdfReader.Info.ContainsKey("Keywords"))
{
keywords = j.Deserialize<Dictionary<String, String>>(getValue(pdfReader.Info, "Keywords"));
//keywords = getKeywords(output);
/*if (pdfDocument.Metadata != null && pdfDocument.Metadata["Keywords"] != null && pdfDocument.Metadata["Keywords"].ToString().Length > 0)
{
keywords = j.Deserialize<Dictionary<String, String>>((string)pdfDocument.Metadata["Keywords"]);*/
openDirectory = getValue(keywords, IndividualRFileInfo.OPEN_DIRECTORY);
currentDirectory = getValue(keywords, IndividualRFileInfo.CURRENT_DIRECTORY);
if (openDirectory != currentDirectory || openDirectory.Length == 0)
{
tempInfo.hasNewFile = true;
break;
}
}
else
{
tempInfo.hasNewFile = true;
break;
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
finally
{
randomAccess.Close();
pdfReader.Close();
pdfReader.Dispose();
pdfReader = null;
}
}
// allFolders[dirName] = tempInfo;
}
dirName = dirName.Substring(dirName.LastIndexOf("\\") + 1);
tempInfo.alias = entry.Key;
toReturn.Add(tempInfo);
}
return toReturn;
}
示例4: GetFileChartInformation
/**
* Returns meta data information from the pdf file
*/
public Dictionary<string, string> GetFileChartInformation(string path)
{
BufferedStream randomAccess = null;
PdfReader pdfReader = null;
Dictionary<String, String> keywords = new Dictionary<String, String>();
JavaScriptSerializer j = new JavaScriptSerializer();
try
{
//if (File.Exists(path))
// {
randomAccess = new BufferedStream(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
pdfReader = new PdfReader(randomAccess, null);
keywords = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(getValue(pdfReader.Info, "Keywords"));
//}
}
catch (Exception e)
{
ExceptionUtility.LogException(e, "");
}
finally
{
if (randomAccess != null)
{
randomAccess.Close();
}
if (pdfReader != null)
{
pdfReader.Close();
pdfReader.Dispose();
pdfReader = null;
}
}
return keywords;
}
示例5: setMetaData
public void setMetaData(string path, Dictionary<String, String> values)
{
Hashtable toReturn = new Hashtable();
BufferedStream randomAccess = null;
PdfReader pdfReader = null;
Dictionary<String, String> keywords = new Dictionary<String, String>();
JavaScriptSerializer j = new JavaScriptSerializer();
try
{
randomAccess = new BufferedStream(this.WaitForFile(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete), 12288);
pdfReader = new PdfReader(randomAccess, null);
keywords = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(getValue(pdfReader.Info, "Keywords"));
if (keywords == null)
{
keywords = new Dictionary<String, String>();
}
MemoryStream mem = new MemoryStream();
if (pdfReader != null)
{
using (BufferedStream ms = new BufferedStream(mem, 12288))
{
using (PdfStamper stamper = new PdfStamper(pdfReader, ms))
{
Dictionary<String, String> info = pdfReader.Info;
foreach (KeyValuePair<string, string> entry in values)
{
if (keywords.ContainsKey(entry.Key))
{
keywords[entry.Key] = entry.Value;
if (entry.Key != IndividualRFileInfo.CURRENT_DIRECTORY)
{
FileInfo fInfo = new FileInfo(path);
if (keywords.ContainsKey(IndividualRFileInfo.CURRENT_DIRECTORY))
{
keywords[IndividualRFileInfo.CURRENT_DIRECTORY] = fInfo.Directory.Name;
}
else
{
keywords.Add(IndividualRFileInfo.CURRENT_DIRECTORY, fInfo.Directory.Name);
}
}
}
else
{
keywords.Add(entry.Key, entry.Value);
}
}
string allStr = j.Serialize(keywords);
info["Keywords"] = allStr;
stamper.MoreInfo = info;
stamper.Close();
}
//File.Delete(path);
File.WriteAllBytes(path, mem.ToArray());
ms.Close();
ms.Dispose();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
finally
{
if (randomAccess != null)
{
randomAccess.Close();
}
if (pdfReader != null)
{
pdfReader.Close();
pdfReader.Dispose();
}
}
}
示例6: PreSign
/// <summary>
/// Prepare the data needed for digital signature. Unfortunately
/// CAPICOM's client-side implementation both hashes **AND** signs
/// passed in data instead of signing data already hashed, so the
/// **entire** PDF content bytes are needed.
/// </summary>
/// <param name="pdfIn">PDF file contents</param>
/// <returns>
/// Base64 encoded PDF content bytes client will sign.
/// </returns>
public string PreSign(byte[] pdfIn)
{
byte[] pdfRawContent = null;
bool isOdd = true;
var timeStamp = DateTime.Now;
var pdfSignature = new PdfSignature(
PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED
);
pdfSignature.Date = new PdfDate(timeStamp);
var exclusionSizes = new Dictionary<PdfName, int>();
exclusionSizes.Add(PdfName.CONTENTS, EXCLUSION_BUFFER * 2 + 2);
PdfReader reader = null;
int? signedFields = null;
try
{
var cert = new WebCertificateReader().GetSigningCertificate();
do
{
++DataReadCount;
reader = new PdfReader(pdfIn);
_acroFieldsWorker = new AcroFieldsReader(reader.AcroFields);
signedFields = signedFields ?? _acroFieldsWorker.SignedFields();
_memoryStream = new MemoryStream();
var stamper = signedFields == 0
? PdfStamper.CreateSignature(reader, _memoryStream, '\0')
: PdfStamper.CreateSignature(reader, _memoryStream, '\0', null, true)
;
_signatureAppearance = stamper.SignatureAppearance;
InitSignatureField(stamper);
pdfSignature.Reason = Reason;
_signatureAppearance.Certificate = cert;
_signatureAppearance.SignDate = timeStamp;
_signatureAppearance.CryptoDictionary = pdfSignature;
_signatureAppearance.PreClose(exclusionSizes);
using (Stream sapStream = _signatureAppearance.GetRangeStream())
{
using (var ms = new MemoryStream())
{
sapStream.CopyTo(ms);
pdfRawContent = ms.ToArray();
}
// pdfRawContent = StreamHandler.ReadAllBytes(sapStream);
// fix CAPICOM's broken implemetation: signature
// invalid if sapStream.Length is **ODD**
if ((pdfRawContent.Length % 2) == 0)
{
isOdd = false;
}
else
{
Reason += "\0";
}
DataSize = sapStream.Length;
}
// sanity check
if (DataReadCount > 2) throw new InvalidOperationException("DataReadCount");
} while (isOdd);
}
catch { throw; }
finally
{
HttpContext.Current.Session[InstanceLookupKey] = this;
if (reader != null) { reader.Dispose(); }
}
return Convert.ToBase64String(pdfRawContent);
}
示例7: AnalyzeFile
//.........這裏部分代碼省略.........
if (kvr.Key == "Page" || kvr.Key == "page")
page_number = Convert.ToInt32(Regex.Match(kvr.Value.ToString(), "[0-9]+").Value);
}
bookMarkReferences.Add(new BookMarkReference(bookmarks[i].Values.ToArray().GetValue(0).ToString(), page_number));
this.AddTreeNode(radTreeView1, bookmarks[i].Values.ToArray().GetValue(0).ToString() + " (Page: " + page_number.ToString() + ")");
this.SetStatusText(string.Format("Analyzing, {0}...", bookmarks[i].Values.ToArray().GetValue(0).ToString()));
this.SetProgressBarValue(ref progressStatus, i);
Thread.Sleep(500);
i++;
}
bookMarkReferences.Sort(sortPagesProvider);
SetButtonEnabled(ref btnSourcePDF, true);
SetButtonEnabled(ref btnDestinationPDF, true);
SetPictureVisible(ref imgOK, true);
SetGroupBoxEnabled(ref radGroupBox1, true);
this.SetStatusText("Done.");
this.SetProgressBar(ref progressStatus, false, 100);
this.SetProgressPanelVisible(false);
} else {
analyzeFailed = true;
SetButtonEnabled(ref btnSourcePDF, true);
SetButtonEnabled(ref btnDestinationPDF, true);
SetPictureVisible(ref imgError, true);
SetGroupBoxEnabled(ref radGroupBox1, true);
this.SetStatusText("No Bookmarks Found!");
this.SetProgressBar(ref progressStatus, false, 100);
this.SetProgressPanelVisible(false);
}
} else if (radRadioButton2.IsChecked) {
String[] pages = txtPageNumbers.Text.Trim().Replace(" ", "").Split(',');
Int32 pageCount = pdfDocument.NumberOfPages;
if (pages.Length > 0) {
this.SetProgressBar(ref progressStatus, true, pages.Length);
try {
for (int i = 0; i < pages.Length; i++)
{
this.SetStatusText(string.Format("Analyzing, {0}...", pages[i]));
this.SetProgressBarValue(ref progressStatus, i+1);
if (pages[i].Trim() != "") {
if (pages[i].Contains("-")) {
if (pages[i].Split('-')[1].Trim() != "") {
Int32 lastnum = Convert.ToInt32(pages[i].Split('-')[1]);
if (lastnum > pageCount) {
analyzeFailed = true;
this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - Invalid");
} else {
this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - \u2713");
}
}
} else {
if (Convert.ToInt32(pages[i]) > pageCount) {
analyzeFailed = true;
this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - Invalid");
} else {
this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - \u2713");
}
}
}
}
this.SetStatusText("Done.");
SetButtonEnabled(ref btnSourcePDF, true);
SetButtonEnabled(ref btnDestinationPDF, true);
SetPictureVisible(ref imgOK, true);
SetGroupBoxEnabled(ref radGroupBox1, true);
this.SetProgressBar(ref progressStatus, false, 100);
this.SetProgressPanelVisible(false);
} catch (Exception ex) {
MessageBox.Show("There was a problem analyzing your document. Please check your entries and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.SetStatusText("Failed.");
SetButtonEnabled(ref btnSourcePDF, true);
SetButtonEnabled(ref btnDestinationPDF, true);
SetPictureVisible(ref imgError, true);
SetGroupBoxEnabled(ref radGroupBox1, true);
this.SetProgressBar(ref progressStatus, false, 100);
this.SetProgressPanelVisible(false);
}
}
} else {
analyzeFailed = true;
this.SetStatusText("No pages documented.");
SetButtonEnabled(ref btnSourcePDF, true);
SetButtonEnabled(ref btnDestinationPDF, true);
SetPictureVisible(ref imgError, true);
SetGroupBoxEnabled(ref radGroupBox1, true);
this.SetProgressBar(ref progressStatus, false, 100);
this.SetProgressPanelVisible(false);
}
pdfDocument.Close();
pdfDocument.Dispose();
}
示例8: ExportToMultiplePDF
void ExportToMultiplePDF(int index)
{
int finishedReports = 0;
PdfStamper stamper = null;
PdfReader reader = null;
//Go through each student in the list
foreach (var student in StudentList)
{
string savePath = System.IO.Path.Combine(System.IO.Path.GetFullPath(textSavePath.Text),
string.Format("{0}.pdf",
index == 0
? student.Name.Replace(' ', '_')
: student.NameReversed));
//Create FileStream for the template pdf
var templateStream = new FileStream(System.IO.Path.GetFullPath(textTempLocation.Text), FileMode.Open);
//Create FileStream for new student report pdf
var studentStream = new FileStream(savePath, FileMode.Create);
//Open existing pdf
reader = new PdfReader(templateStream);
//Create stamper to set the contents of the fields
stamper = new PdfStamper(reader, studentStream);
var form = stamper.AcroFields;
//Setting the text of the template to the stored info
form.SetField("Street", student.Address);
form.SetField("CityZipState", student.CityZipState);
form.SetField("ClassName", student.ClassName);
form.SetField("Comments", student.Comments);
form.SetField("Grade", student.Grade.ToString());
form.SetField("Critique", student.Critique);
form.SetField("HighSchool", student.HighSchool);
form.SetField("Session", student.Session);
form.SetField("Absences", student.SemesterTotalAbs.ToString());
form.SetField("Tardies", student.SemesterTotalTdy.ToString());
form.SetField("NetAbsences", student.SemesterNetAbs.ToString());
form.SetField("StuNameReversed", student.NameReversed);
form.SetField("Date", DateTime.Now.ToShortDateString());
//Flatten the fields that we do not want editable
stamper.FormFlattening = true;
stamper.PartialFormFlattening("StuNameReversed");
stamper.PartialFormFlattening("Street");
stamper.PartialFormFlattening("CityZipState");
stamper.PartialFormFlattening("HighSchool");
stamper.PartialFormFlattening("ClassName");
stamper.PartialFormFlattening("Session");
stamper.PartialFormFlattening("Absences");
stamper.PartialFormFlattening("Tardies");
stamper.PartialFormFlattening("NetAbsences");
stamper.PartialFormFlattening("Grade");
stamper.PartialFormFlattening("Critique");
stamper.Dispose();
reader.Dispose();
//reports progress to update status text on the bottom
bgProgressThread.ReportProgress(++finishedReports);
}
}