本文整理匯總了C#中iTextSharp.text.pdf.RandomAccessFileOrArray.Close方法的典型用法代碼示例。如果您正苦於以下問題:C# RandomAccessFileOrArray.Close方法的具體用法?C# RandomAccessFileOrArray.Close怎麽用?C# RandomAccessFileOrArray.Close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類iTextSharp.text.pdf.RandomAccessFileOrArray
的用法示例。
在下文中一共展示了RandomAccessFileOrArray.Close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: ExtractImagesFromPDF
public static void ExtractImagesFromPDF(string sourcePdf, string outputPath)
{
// NOTE: This will only get the first image it finds per page.
PdfReader pdf = new PdfReader(sourcePdf);
RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);
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.
if (!Directory.Exists(outputPath))
Directory.CreateDirectory(outputPath);
string path = Path.Combine(outputPath, 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 = GetImageEncoder("JPEG");
img.Save(path, jpegEncoder, parms);
}
}
}
}
}
catch
{
throw;
}
finally
{
pdf.Close();
raf.Close();
}
}
示例2: PdfStamperImp
/** Creates new PdfStamperImp.
* @param reader the read PDF
* @param os the output destination
* @param pdfVersion the new pdf version or '\0' to keep the same version as the original
* document
* @param append
* @throws DocumentException on error
* @throws IOException
*/
internal PdfStamperImp(PdfReader reader, Stream os, char pdfVersion, bool append)
: base(new PdfDocument(), os)
{
if (reader.Tampered)
throw new DocumentException("The original document was reused. Read it again from file.");
reader.Tampered = true;
this.reader = reader;
file = reader.SafeFile;
this.append = append;
if (append) {
if (reader.IsRebuilt())
throw new DocumentException("Append mode requires a document without errors even if recovery was possible.");
if (reader.IsEncrypted())
crypto = new PdfEncryption(reader.Decrypt);
pdf_version.SetAppendmode(true);
file.ReOpen();
byte[] buf = new byte[8192];
int n;
while ((n = file.Read(buf)) > 0)
this.os.Write(buf, 0, n);
file.Close();
prevxref = reader.LastXref;
reader.Appendable = true;
}
else {
if (pdfVersion == 0)
base.PdfVersion = reader.PdfVersion;
else
base.PdfVersion = pdfVersion;
}
base.Open();
pdf.AddWriter(this);
if (append) {
body.Refnum = reader.XrefSize;
marked = new IntHashtable();
if (reader.IsNewXrefType())
fullCompression = true;
if (reader.IsHybridXref())
fullCompression = false;
}
initialXrefSize = reader.XrefSize;
}
示例3: CloseIt
protected void CloseIt() {
for (int k = 0; k < readers.Count; ++k) {
readers[k].RemoveFields();
}
for (int r = 0; r < readers.Count; ++r) {
PdfReader reader = readers[r];
for (int page = 1; page <= reader.NumberOfPages; ++page) {
pageRefs.Add(GetNewReference(reader.GetPageOrigRef(page)));
pageDics.Add(reader.GetPageN(page));
}
}
MergeFields();
CreateAcroForms();
for (int r = 0; r < readers.Count; ++r) {
PdfReader reader = readers[r];
for (int page = 1; page <= reader.NumberOfPages; ++page) {
PdfDictionary dic = reader.GetPageN(page);
PdfIndirectReference pageRef = GetNewReference(reader.GetPageOrigRef(page));
PdfIndirectReference parent = root.AddPageRef(pageRef);
dic.Put(PdfName.PARENT, parent);
Propagate(dic, pageRef, false);
}
}
foreach (KeyValuePair<PdfReader, IntHashtable> entry in readers2intrefs) {
PdfReader reader = entry.Key;
try {
file = reader.SafeFile;
file.ReOpen();
IntHashtable t = entry.Value;
int[] keys = t.ToOrderedKeys();
for (int k = 0; k < keys.Length; ++k) {
PRIndirectReference refi = new PRIndirectReference(reader, keys[k]);
AddToBody(PdfReader.GetPdfObjectRelease(refi), t[keys[k]]);
}
}
finally {
try {
file.Close();
// TODO: Removed - the user should be responsible for closing all PdfReaders. But, this could cause a lot of memory leaks in code out there that hasn't been properly closing things - maybe add a finalizer to PdfReader that calls PdfReader#close() ??
//reader.Close();
}
catch {
// empty on purpose
}
}
}
pdf.Close();
}
示例4: ReadCffFont
/**
* If this font file is using the Compact Font File Format, then this method
* will return the raw bytes needed for the font stream. If this method is
* ever made public: make sure to add a test if (cff == true).
* @return a byte array
* @since 2.1.3
*/
protected internal byte[] ReadCffFont()
{
RandomAccessFileOrArray rf2 = new RandomAccessFileOrArray(rf);
byte[] b = new byte[cffLength];
try {
rf2.ReOpen();
rf2.Seek(cffOffset);
rf2.ReadFully(b);
}
finally {
try {
rf2.Close();
}
catch {
// empty on purpose
}
}
return b;
}
示例5: GetFullFont
protected byte[] GetFullFont()
{
RandomAccessFileOrArray rf2 = null;
try {
rf2 = new RandomAccessFileOrArray(rf);
rf2.ReOpen();
byte[] b = new byte[rf2.Length];
rf2.ReadFully(b);
return b;
}
finally {
try {if (rf2 != null) rf2.Close();} catch {}
}
}
示例6: GetInstance
/// <summary>
/// Gets an instance of an Image.
/// </summary>
/// <param name="img">a byte array</param>
/// <returns>an object of type Gif, Jpeg or Png</returns>
public static Image GetInstance(byte[] imgb, bool handleIncorrectImage) {
int c1 = imgb[0];
int c2 = imgb[1];
int c3 = imgb[2];
int c4 = imgb[3];
if (c1 == 'G' && c2 == 'I' && c3 == 'F') {
GifImage gif = new GifImage(imgb);
return gif.GetImage(1);
}
if (c1 == 0xFF && c2 == 0xD8) {
return new Jpeg(imgb);
}
if (c1 == 0x00 && c2 == 0x00 && c3 == 0x00 && c4 == 0x0c) {
return new Jpeg2000(imgb);
}
if (c1 == 0xff && c2 == 0x4f && c3 == 0xff && c4 == 0x51) {
return new Jpeg2000(imgb);
}
if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
return PngImage.GetImage(imgb);
}
if (c1 == 0xD7 && c2 == 0xCD) {
return new ImgWMF(imgb);
}
if (c1 == 'B' && c2 == 'M') {
return BmpImage.GetImage(imgb);
}
if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
|| (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) {
RandomAccessFileOrArray ra = null;
try {
ra = new RandomAccessFileOrArray(imgb);
Image img = TiffImage.GetTiffImage(ra, handleIncorrectImage, 1);
if (img.OriginalData == null)
img.OriginalData = imgb;
return img;
} finally {
if (ra != null)
ra.Close();
}
}
throw new IOException(MessageLocalization.GetComposedMessage("the.byte.array.is.not.a.recognized.imageformat"));
}
示例7: ParseImages
/// <summary>Parses images from pdf document.</summary>
/// <param name="filePath">The pdf-file full path.</param>
/// <returns>Collection of images and streams that are associated with them.</returns>
public static List<ParsedImage> ParseImages(string filePath)
{
var imgList = new List<ParsedImage>();
var raf = new RandomAccessFileOrArray(filePath);
var reader = new PdfReader(raf, null);
try
{
for (var pageNumber = 1; pageNumber <= reader.NumberOfPages; pageNumber++)
{
var pg = reader.GetPageN(pageNumber);
var size = reader.GetPageSize(pageNumber);
var res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
var xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
if (xobj == null)
{
continue;
}
foreach (var name in xobj.Keys)
{
var obj = xobj.Get(name);
if (!obj.IsIndirect())
{
continue;
}
var tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
var type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
if (!PdfName.IMAGE.Equals(type))
{
continue;
}
var refIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(CultureInfo.InvariantCulture));
var pdfObj = reader.GetPdfObject(refIndex);
var pdfStrem = (PdfStream)pdfObj;
var bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
if (bytes == null)
{
continue;
}
var memStream = new MemoryStream(bytes) { Position = 0 };
var img = Image.FromStream(memStream);
imgList.Add(new ParsedImage
{
Image = img,
ImageStream = memStream,
Format = img.RawFormat,
Width = size.Width,
Height = size.Height,
PerformedRotation = RotateFlipType.RotateNoneFlipNone
});
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
finally
{
reader.Close();
raf.Close();
}
return imgList;
}
示例8: GetInstance
/// <summary>
/// Gets an instance of an Image.
/// </summary>
/// <param name="img">a byte array</param>
/// <returns>an object of type Gif, Jpeg or Png</returns>
public static Image GetInstance(byte[] imgb)
{
int c1 = imgb[0];
int c2 = imgb[1];
int c3 = imgb[2];
int c4 = imgb[3];
if (c1 == 'G' && c2 == 'I' && c3 == 'F') {
GifImage gif = new GifImage(imgb);
return gif.GetImage(1);
}
if (c1 == 0xFF && c2 == 0xD8) {
return new Jpeg(imgb);
}
if (c1 == 0x00 && c2 == 0x00 && c3 == 0x00 && c4 == 0x0c) {
return new Jpeg2000(imgb);
}
if (c1 == 0xff && c2 == 0x4f && c3 == 0xff && c4 == 0x51) {
return new Jpeg2000(imgb);
}
if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
return PngImage.GetImage(imgb);
}
if (c1 == 0xD7 && c2 == 0xCD) {
return new ImgWMF(imgb);
}
if (c1 == 'B' && c2 == 'M') {
return BmpImage.GetImage(imgb);
}
if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
|| (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) {
RandomAccessFileOrArray ra = null;
try {
ra = new RandomAccessFileOrArray(imgb);
Image img = TiffImage.GetTiffImage(ra, 1);
if (img.OriginalData == null)
img.OriginalData = imgb;
return img;
} finally {
if (ra != null)
ra.Close();
}
}
throw new IOException("The byte array is not a recognized imageformat.");
}
示例9: PdfStamperImp
/** Creates new PdfStamperImp.
* @param reader the read PDF
* @param os the output destination
* @param pdfVersion the new pdf version or '\0' to keep the same version as the original
* document
* @param append
* @throws DocumentException on error
* @throws IOException
*/
protected internal PdfStamperImp(PdfReader reader, Stream os, char pdfVersion, bool append)
: base(new PdfDocument(), os)
{
if (!reader.IsOpenedWithFullPermissions)
throw new BadPasswordException(MessageLocalization.GetComposedMessage("pdfreader.not.opened.with.owner.password"));
if (reader.Tampered)
throw new DocumentException(MessageLocalization.GetComposedMessage("the.original.document.was.reused.read.it.again.from.file"));
reader.Tampered = true;
this.reader = reader;
file = reader.SafeFile;
this.append = append;
if (append) {
if (reader.IsRebuilt())
throw new DocumentException(MessageLocalization.GetComposedMessage("append.mode.requires.a.document.without.errors.even.if.recovery.was.possible"));
if (reader.IsEncrypted())
crypto = new PdfEncryption(reader.Decrypt);
pdf_version.SetAppendmode(true);
file.ReOpen();
byte[] buf = new byte[8192];
int n;
while ((n = file.Read(buf)) > 0)
this.os.Write(buf, 0, n);
file.Close();
prevxref = reader.LastXref;
reader.Appendable = true;
}
else {
if (pdfVersion == 0)
base.PdfVersion = reader.PdfVersion;
else
base.PdfVersion = pdfVersion;
}
base.Open();
pdf.AddWriter(this);
if (append) {
body.Refnum = reader.XrefSize;
marked = new IntHashtable();
if (reader.IsNewXrefType())
fullCompression = true;
if (reader.IsHybridXref())
fullCompression = false;
}
initialXrefSize = reader.XrefSize;
}
示例10: Process
//.........這裏部分代碼省略.........
StdVW = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo);
else if (ident.Equals("StartCharMetrics")) {
isMetrics = true;
break;
}
}
if (!isMetrics)
throw new DocumentException(MessageLocalization.GetComposedMessage("missing.startcharmetrics.in.1", fileName));
while ((line = rf.ReadLine()) != null) {
StringTokenizer tok = new StringTokenizer(line);
if (!tok.HasMoreTokens())
continue;
string ident = tok.NextToken();
if (ident.Equals("EndCharMetrics")) {
isMetrics = false;
break;
}
int C = -1;
int WX = 250;
string N = "";
int[] B = null;
tok = new StringTokenizer(line, ";");
while (tok.HasMoreTokens())
{
StringTokenizer tokc = new StringTokenizer(tok.NextToken());
if (!tokc.HasMoreTokens())
continue;
ident = tokc.NextToken();
if (ident.Equals("C"))
C = int.Parse(tokc.NextToken());
else if (ident.Equals("WX"))
WX = (int)float.Parse(tokc.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo);
else if (ident.Equals("N"))
N = tokc.NextToken();
else if (ident.Equals("B")) {
B = new int[]{int.Parse(tokc.NextToken()),
int.Parse(tokc.NextToken()),
int.Parse(tokc.NextToken()),
int.Parse(tokc.NextToken())};
}
}
Object[] metrics = new Object[]{C, WX, N, B};
if (C >= 0)
CharMetrics[C] = metrics;
CharMetrics[N] = metrics;
}
if (isMetrics)
throw new DocumentException(MessageLocalization.GetComposedMessage("missing.endcharmetrics.in.1", fileName));
if (!CharMetrics.ContainsKey("nonbreakingspace")) {
Object[] space;
CharMetrics.TryGetValue("space", out space);
if (space != null)
CharMetrics["nonbreakingspace"] = space;
}
while ((line = rf.ReadLine()) != null) {
StringTokenizer tok = new StringTokenizer(line);
if (!tok.HasMoreTokens())
continue;
string ident = tok.NextToken();
if (ident.Equals("EndFontMetrics"))
return;
if (ident.Equals("StartKernPairs")) {
isMetrics = true;
break;
}
}
if (!isMetrics)
throw new DocumentException(MessageLocalization.GetComposedMessage("missing.endfontmetrics.in.1", fileName));
while ((line = rf.ReadLine()) != null) {
StringTokenizer tok = new StringTokenizer(line);
if (!tok.HasMoreTokens())
continue;
string ident = tok.NextToken();
if (ident.Equals("KPX")) {
string first = tok.NextToken();
string second = tok.NextToken();
int width = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo);
Object[] relates;
KernPairs.TryGetValue(first, out relates);
if (relates == null)
KernPairs[first] = new Object[]{second, width};
else {
int n = relates.Length;
Object[] relates2 = new Object[n + 2];
Array.Copy(relates, 0, relates2, 0, n);
relates2[n] = second;
relates2[n + 1] = width;
KernPairs[first] = relates2;
}
}
else if (ident.Equals("EndKernPairs")) {
isMetrics = false;
break;
}
}
if (isMetrics)
throw new DocumentException(MessageLocalization.GetComposedMessage("missing.endkernpairs.in.1", fileName));
rf.Close();
}
示例11: Type1Font
/** Creates a new Type1 font.
* @param ttfAfm the AFM file if the input is made with a <CODE>byte</CODE> array
* @param pfb the PFB file if the input is made with a <CODE>byte</CODE> array
* @param afmFile the name of one of the 14 built-in fonts or the location of an AFM file. The file must end in '.afm'
* @param enc the encoding to be applied to this font
* @param emb true if the font is to be embedded in the PDF
* @throws DocumentException the AFM file is invalid
* @throws IOException the AFM file could not be read
*/
internal Type1Font(string afmFile, string enc, bool emb, byte[] ttfAfm, byte[] pfb, bool forceRead) {
if (emb && ttfAfm != null && pfb == null)
throw new DocumentException(MessageLocalization.GetComposedMessage("two.byte.arrays.are.needed.if.the.type1.font.is.embedded"));
if (emb && ttfAfm != null)
this.pfb = pfb;
encoding = enc;
embedded = emb;
fileName = afmFile;
FontType = FONT_TYPE_T1;
RandomAccessFileOrArray rf = null;
Stream istr = null;
if (BuiltinFonts14.ContainsKey(afmFile)) {
embedded = false;
builtinFont = true;
byte[] buf = new byte[1024];
try {
istr = StreamUtil.GetResourceStream(RESOURCE_PATH + afmFile + ".afm");
if (istr == null) {
string msg = MessageLocalization.GetComposedMessage("1.not.found.as.resource", afmFile);
Console.Error.WriteLine(msg);
throw new DocumentException(msg);
}
MemoryStream ostr = new MemoryStream();
while (true) {
int size = istr.Read(buf, 0, buf.Length);
if (size == 0)
break;
ostr.Write(buf, 0, size);
}
buf = ostr.ToArray();
}
finally {
if (istr != null) {
try {
istr.Close();
}
catch {
// empty on purpose
}
}
}
try {
rf = new RandomAccessFileOrArray(buf);
Process(rf);
}
finally {
if (rf != null) {
try {
rf.Close();
}
catch {
// empty on purpose
}
}
}
}
else if (afmFile.ToLower(System.Globalization.CultureInfo.InvariantCulture).EndsWith(".afm")) {
try {
if (ttfAfm == null)
rf = new RandomAccessFileOrArray(afmFile, forceRead);
else
rf = new RandomAccessFileOrArray(ttfAfm);
Process(rf);
}
finally {
if (rf != null) {
try {
rf.Close();
}
catch {
// empty on purpose
}
}
}
}
else if (afmFile.ToLower(System.Globalization.CultureInfo.InvariantCulture).EndsWith(".pfm")) {
try {
MemoryStream ba = new MemoryStream();
if (ttfAfm == null)
rf = new RandomAccessFileOrArray(afmFile, forceRead);
else
rf = new RandomAccessFileOrArray(ttfAfm);
Pfm2afm.Convert(rf, ba);
rf.Close();
rf = new RandomAccessFileOrArray(ba.ToArray());
Process(rf);
}
finally {
if (rf != null) {
try {
rf.Close();
//.........這裏部分代碼省略.........
示例12: WriteFont
/** Outputs to the writer the font dictionaries and streams.
* @param writer the writer for this document
* @param ref the font indirect reference
* @param parms several parameters that depend on the font type
* @throws IOException on error
* @throws DocumentException error in generating the object
*/
internal override void WriteFont(PdfWriter writer, PdfIndirectReference piref, Object[] parms)
{
Hashtable longTag = (Hashtable)parms[0];
AddRangeUni(longTag, true, subset);
ArrayList tmp = new ArrayList();
foreach (object o in longTag.Values) {
tmp.Add(o);
}
Object[] metrics = tmp.ToArray();
Array.Sort(metrics, this);
PdfIndirectReference ind_font = null;
PdfObject pobj = null;
PdfIndirectObject obj = null;
// sivan: cff
if (cff) {
RandomAccessFileOrArray rf2 = new RandomAccessFileOrArray(rf);
byte[] b = new byte[cffLength];
try {
rf2.ReOpen();
rf2.Seek(cffOffset);
rf2.ReadFully(b);
} finally {
try {
rf2.Close();
} catch {
// empty on purpose
}
}
if (subset || subsetRanges != null) {
CFFFontSubset cffs = new CFFFontSubset(new RandomAccessFileOrArray(b),longTag);
b = cffs.Process( (cffs.GetNames())[0] );
}
pobj = new StreamFont(b, "CIDFontType0C");
obj = writer.AddToBody(pobj);
ind_font = obj.IndirectReference;
} else {
byte[] b;
if (subset || directoryOffset != 0) {
TrueTypeFontSubSet sb = new TrueTypeFontSubSet(fileName, new RandomAccessFileOrArray(rf), longTag, directoryOffset, false, false);
b = sb.Process();
}
else {
b = GetFullFont();
}
int[] lengths = new int[]{b.Length};
pobj = new StreamFont(b, lengths);
obj = writer.AddToBody(pobj);
ind_font = obj.IndirectReference;
}
String subsetPrefix = "";
if (subset)
subsetPrefix = CreateSubsetPrefix();
PdfDictionary dic = GetFontDescriptor(ind_font, subsetPrefix);
obj = writer.AddToBody(dic);
ind_font = obj.IndirectReference;
pobj = GetCIDFontType2(ind_font, subsetPrefix, metrics);
obj = writer.AddToBody(pobj);
ind_font = obj.IndirectReference;
pobj = GetToUnicode(metrics);
PdfIndirectReference toUnicodeRef = null;
if (pobj != null) {
obj = writer.AddToBody(pobj);
toUnicodeRef = obj.IndirectReference;
}
pobj = GetFontBaseType(ind_font, subsetPrefix, toUnicodeRef);
writer.AddToBody(pobj, piref);
}
示例13: GetLocalInstance
/// <summary>
/// Gets an instance of an Image.
/// </summary>
/// <param name="url">an URL</param>
/// <returns>an object of type Gif, Jpeg or Png</returns>
public static Image GetLocalInstance(string sFileName)
{
Stream istr = null;
try
{
#if !NETCF
WebRequest w = WebRequest.Create(url);
istr = w.GetResponse().GetResponseStream();
#else
istr = new FileStream(sFileName, FileMode.Open);
#endif
//istr = w.GetResponse().GetResponseStream();
int c1 = istr.ReadByte();
int c2 = istr.ReadByte();
int c3 = istr.ReadByte();
int c4 = istr.ReadByte();
istr.Close();
istr = null;
if (c1 == 'G' && c2 == 'I' && c3 == 'F')
{
GifImage gif = new GifImage(sFileName);
Image img = gif.GetImage(1);
return img;
}
if (c1 == 0xFF && c2 == 0xD8)
{
return new Jpeg(sFileName);
}
if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3])
{
Image img = PngImage.GetImage(sFileName);
return img;
}
if (c1 == 0xD7 && c2 == 0xCD)
{
Image img = new ImgWMF(sFileName);
return img;
}
if (c1 == 'B' && c2 == 'M')
{
Image img = BmpImage.GetImage(sFileName);
return img;
}
if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
|| (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0))
{
RandomAccessFileOrArray ra = null;
try
{
ra = new RandomAccessFileOrArray(sFileName);
Image img = TiffImage.GetTiffImage(ra, 1);
img.url = new Uri(sFileName);
return img;
}
finally
{
if (ra != null)
ra.Close();
}
}
throw new IOException(sFileName.ToString()
+ " is not a recognized imageformat.");
}
finally
{
if (istr != null)
{
istr.Close();
}
}
}
示例14: GetInstance
/// <summary>
/// Gets an instance of an Image.
/// </summary>
/// <param name="img">a byte array</param>
/// <returns>an object of type Gif, Jpeg or Png</returns>
public static Image GetInstance(byte[] imgb, bool recoverFromImageError) {
RandomAccessSourceFactory randomAccessSourceFactory = new RandomAccessSourceFactory();
int c1 = imgb[0];
int c2 = imgb[1];
int c3 = imgb[2];
int c4 = imgb[3];
if (c1 == 'G' && c2 == 'I' && c3 == 'F') {
GifImage gif = new GifImage(imgb);
return gif.GetImage(1);
}
if (c1 == 0xFF && c2 == 0xD8) {
return new Jpeg(imgb);
}
if (c1 == 0x00 && c2 == 0x00 && c3 == 0x00 && c4 == 0x0c) {
return new Jpeg2000(imgb);
}
if (c1 == 0xff && c2 == 0x4f && c3 == 0xff && c4 == 0x51) {
return new Jpeg2000(imgb);
}
if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
return PngImage.GetImage(imgb);
}
if (c1 == 0xD7 && c2 == 0xCD) {
return new ImgWMF(imgb);
}
if (c1 == 'B' && c2 == 'M') {
return BmpImage.GetImage(imgb);
}
if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
|| (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) {
RandomAccessFileOrArray ra = null;
try {
ra = new RandomAccessFileOrArray(randomAccessSourceFactory.CreateSource(imgb));
Image img = TiffImage.GetTiffImage(ra, 1);
if (img.OriginalData == null)
img.OriginalData = imgb;
return img;
} catch ( Exception e ) {
if ( recoverFromImageError ) {
// reruns the getTiffImage() with several error recovering workarounds in place
// not guaranteed to work with every TIFF
Image img = TiffImage.GetTiffImage(ra, recoverFromImageError, 1);
if (img.OriginalData == null)
img.OriginalData = imgb;
return img;
}
throw e;
} finally {
if (ra != null)
ra.Close();
}
}
if (c1 == 0x97 && c2 == 'J' && c3 == 'B' && c4 == '2') {
int c5 = imgb[4];
int c6 = imgb[5];
int c7 = imgb[6];
int c8 = imgb[7];
if (c5 == '\r' && c6 == '\n' && c7 == 0x1a && c8 == '\n') {
// a jbig2 file with a file header. the header is the only way we know here.
// embedded jbig2s don't have a header, have to create them by explicit use of Jbig2Image?
// nkerr, 2008-12-05 see also the getInstance(URL)
RandomAccessFileOrArray ra = null;
try {
ra = new RandomAccessFileOrArray(randomAccessSourceFactory.CreateSource(imgb));
Image img = JBIG2Image.GetJbig2Image(ra, 1);
if (img.OriginalData == null)
img.OriginalData = imgb;
return img;
}
finally {
if (ra != null)
ra.Close();
}
}
}
throw new IOException(MessageLocalization.GetComposedMessage("the.byte.array.is.not.a.recognized.imageformat"));
}
示例15: Type1Font
/** Creates a new Type1 font.
* @param ttfAfm the AFM file if the input is made with a <CODE>byte</CODE> array
* @param pfb the PFB file if the input is made with a <CODE>byte</CODE> array
* @param afmFile the name of one of the 14 built-in fonts or the location of an AFM file. The file must end in '.afm'
* @param enc the encoding to be applied to this font
* @param emb true if the font is to be embedded in the PDF
* @throws DocumentException the AFM file is invalid
* @throws IOException the AFM file could not be read
*/
internal Type1Font(string afmFile, string enc, bool emb, byte[] ttfAfm, byte[] pfb)
{
if (emb && ttfAfm != null && pfb == null)
throw new DocumentException("Two byte arrays are needed if the Type1 font is embedded.");
if (emb && ttfAfm != null)
this.pfb = pfb;
encoding = enc;
embedded = emb;
fileName = afmFile;
FontType = FONT_TYPE_T1;
RandomAccessFileOrArray rf = null;
Stream istr = null;
if (BuiltinFonts14.ContainsKey(afmFile)) {
embedded = false;
builtinFont = true;
byte[] buf = new byte[1024];
try {
istr = GetResourceStream(RESOURCE_PATH + afmFile + ".afm");
if (istr == null) {
Console.Error.WriteLine(afmFile + " not found as resource.");
throw new DocumentException(afmFile + " not found as resource.");
}
MemoryStream ostr = new MemoryStream();
while (true) {
int size = istr.Read(buf, 0, buf.Length);
if (size == 0)
break;
ostr.Write(buf, 0, size);
}
buf = ostr.ToArray();
}
finally {
if (istr != null) {
try {
istr.Close();
}
catch {
// empty on purpose
}
}
}
try {
rf = new RandomAccessFileOrArray(buf);
Process(rf);
}
finally {
if (rf != null) {
try {
rf.Close();
}
catch {
// empty on purpose
}
}
}
}
else if (afmFile.ToLower().EndsWith(".afm")) {
try {
if (ttfAfm == null)
rf = new RandomAccessFileOrArray(afmFile);
else
rf = new RandomAccessFileOrArray(ttfAfm);
Process(rf);
}
finally {
if (rf != null) {
try {
rf.Close();
}
catch {
// empty on purpose
}
}
}
}
else if (afmFile.ToLower().EndsWith(".pfm")) {
try {
MemoryStream ba = new MemoryStream();
if (ttfAfm == null)
rf = new RandomAccessFileOrArray(afmFile);
else
rf = new RandomAccessFileOrArray(ttfAfm);
Pfm2afm.Convert(rf, ba);
rf.Close();
rf = new RandomAccessFileOrArray(ba.ToArray());
Process(rf);
}
finally {
if (rf != null) {
try {
rf.Close();
//.........這裏部分代碼省略.........