internal PdfReaderInstance(PdfReader reader, PdfWriter writer) { this.reader = reader; this.writer = writer; file = reader.SafeFile; myXref = new int[reader.XrefSize]; }
/** * Gets a byte array that can be used as a /JBIG2Globals, * or null if not applicable to the given jbig2. * @param ra an random access file or array * @return a byte array */ public static byte[] GetGlobalSegment(RandomAccessFileOrArray ra ) { try { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.Read(); return sr.GetGlobal(true); } catch { return null; } }
/// <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 GetInstance(Uri url) { Stream istr = null; try { WebRequest w = WebRequest.Create(url); istr = w.GetResponse().GetResponseStream(); int c1 = istr.ReadByte(); int c2 = istr.ReadByte(); int c3 = istr.ReadByte(); int c4 = istr.ReadByte(); // jbig2 int c5 = istr.ReadByte(); int c6 = istr.ReadByte(); int c7 = istr.ReadByte(); int c8 = istr.ReadByte(); istr.Close(); istr = null; if (c1 == 'G' && c2 == 'I' && c3 == 'F') { GifImage gif = new GifImage(url); Image img = gif.GetImage(1); return img; } if (c1 == 0xFF && c2 == 0xD8) { return new Jpeg(url); } if (c1 == 0x00 && c2 == 0x00 && c3 == 0x00 && c4 == 0x0c) { return new Jpeg2000(url); } if (c1 == 0xff && c2 == 0x4f && c3 == 0xff && c4 == 0x51) { return new Jpeg2000(url); } if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1] && c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) { Image img = PngImage.GetImage(url); return img; } if (c1 == 0xD7 && c2 == 0xCD) { Image img = new ImgWMF(url); return img; } if (c1 == 'B' && c2 == 'M') { Image img = BmpImage.GetImage(url); return img; } if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42) || (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) { RandomAccessFileOrArray ra = null; try { if (url.IsFile) { String file = url.LocalPath; ra = new RandomAccessFileOrArray(file); } else ra = new RandomAccessFileOrArray(url); Image img = TiffImage.GetTiffImage(ra, 1); img.url = url; return img; } finally { if (ra != null) ra.Close(); } } if ( c1 == 0x97 && c2 == 'J' && c3 == 'B' && c4 == '2' && c5 == '\r' && c6 == '\n' && c7 == 0x1a && c8 == '\n' ) { RandomAccessFileOrArray ra = null; try { if (url.IsFile) { String file = url.LocalPath; ra = new RandomAccessFileOrArray(file); } else ra = new RandomAccessFileOrArray(url); Image img = JBIG2Image.GetJbig2Image(ra, 1); img.url = url; return img; } finally { if (ra != null) ra.Close(); } } throw new IOException(url.ToString() + " is not a recognized imageformat."); } finally { if (istr != null) { istr.Close(); } } }
public PRTokeniser(RandomAccessFileOrArray file) { this.file = file; }
public PRTokeniser(string filename) { file = new RandomAccessFileOrArray(filename); }
/** * Converts a PFM file into an AFM file. * @param inp the PFM file * @param outp the AFM file * @throws IOException on error */ public static void Convert(RandomAccessFileOrArray inp, Stream outp) { Pfm2afm p = new Pfm2afm(inp, outp); p.Openpfm(); p.Putheader(); p.Putchartab(); p.Putkerntab(); p.Puttrailer(); p.outp.Flush(); }
internal EnumerateTTC(byte[] ttcArray) { fileName = "Byte array TTC"; rf = new RandomAccessFileOrArray(ttcArray); FindNames(); }
internal EnumerateTTC(byte[] ttcArray) { fileName = "Byte array TTC"; rf = new RandomAccessFileOrArray(ttcArray); FindNames(); }
private float ReadFloat(RandomAccessFileOrArray stream) { if (isBigEndian) { return stream.ReadFloat(); } else { return stream.ReadFloatLE(); } }
public JBIG2SegmentReader(RandomAccessFileOrArray ra ) { this.ra = ra; }
/** * returns an Image representing the given page. * @param ra the file or array containing the image * @param page the page number of the image * @return an Image object */ public static Image GetJbig2Image(RandomAccessFileOrArray ra, int page) { if (page < 1) throw new ArgumentException("The page number must be >= 1."); JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.Read(); JBIG2SegmentReader.JBIG2Page p = sr.GetPage(page); Image img = new ImgJBIG2(p.pageBitmapWidth, p.pageBitmapHeight, p.GetData(true), sr.GetGlobal(true)); return img; }
/*** * Gets the number of pages in a JBIG2 image. * @param ra a random acces file array containing a JBIG2 image * @return the number of pages */ public static int GetNumberOfPages(RandomAccessFileOrArray ra) { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.Read(); return sr.NumberOfPages(); }
/** Creates a new instance of Pfm2afm */ private Pfm2afm(RandomAccessFileOrArray inp, Stream outp) { this.inp = inp; encoding = Encoding.GetEncoding(1252); this.outp = new StreamWriter(outp, encoding); }
public RandomAccessFileOrArray(RandomAccessFileOrArray file) { filename = file.filename; arrayIn = file.arrayIn; startOffset = file.startOffset; }
/** * Constructs a TIFFDirectory by reading a SeekableStream. * The ifd_offset parameter specifies the stream offset from which * to begin reading; this mechanism is sometimes used to store * private IFDs within a TIFF file that are not part of the normal * sequence of IFDs. * * @param stream a SeekableStream to read from. * @param ifd_offset the long byte offset of the directory. * @param directory the index of the directory to read beyond the * one at the current stream offset; zero indicates the IFD * at the current offset. */ public TIFFDirectory(RandomAccessFileOrArray stream, long ifd_offset, int directory) { long global_save_offset = stream.FilePointer; stream.Seek(0L); int endian = stream.ReadUnsignedShort(); if (!IsValidEndianTag(endian)) { throw new ArgumentException("Bad endianness tag (not 0x4949 or 0x4d4d)."); } isBigEndian = (endian == 0x4d4d); // Seek to the first IFD. stream.Seek(ifd_offset); // Seek to desired IFD if necessary. int dirNum = 0; while (dirNum < directory) { // Get the number of fields in the current IFD. int numEntries = ReadUnsignedShort(stream); // Skip to the next IFD offset value field. stream.Seek(ifd_offset + 12*numEntries); // Read the offset to the next IFD beyond this one. ifd_offset = ReadUnsignedInt(stream); // Seek to the next IFD. stream.Seek(ifd_offset); // Increment the directory. dirNum++; } Initialize(stream); stream.Seek(global_save_offset); }
/** 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.IsOpenedWithFullPermissions) throw new BadPasswordException("PdfReader not opened with owner password"); 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; }
private void Initialize(RandomAccessFileOrArray stream) { long nextTagOffset = 0L; long maxOffset = (long) stream.Length; int i, j; IFDOffset = stream.FilePointer; numEntries = ReadUnsignedShort(stream); fields = new TIFFField[numEntries]; for (i = 0; (i < numEntries) && (nextTagOffset < maxOffset); i++) { int tag = ReadUnsignedShort(stream); int type = ReadUnsignedShort(stream); int count = (int)(ReadUnsignedInt(stream)); bool processTag = true; // The place to return to to read the next tag nextTagOffset = stream.FilePointer + 4; try { // If the tag data can't fit in 4 bytes, the next 4 bytes // contain the starting offset of the data if (count*sizeOfType[type] > 4) { long valueOffset = ReadUnsignedInt(stream); // bounds check offset for EOF if (valueOffset < maxOffset) { stream.Seek(valueOffset); } else { // bad offset pointer .. skip tag processTag = false; } } } catch (ArgumentOutOfRangeException) { // if the data type is unknown we should skip this TIFF Field processTag = false; } if (processTag) { fieldIndex[tag] = i; Object obj = null; switch (type) { case TIFFField.TIFF_BYTE: case TIFFField.TIFF_SBYTE: case TIFFField.TIFF_UNDEFINED: case TIFFField.TIFF_ASCII: byte[] bvalues = new byte[count]; stream.ReadFully(bvalues, 0, count); if (type == TIFFField.TIFF_ASCII) { // Can be multiple strings int index = 0, prevIndex = 0; ArrayList v = new ArrayList(); while (index < count) { while ((index < count) && (bvalues[index++] != 0)); // When we encountered zero, means one string has ended char[] cht = new char[index - prevIndex]; Array.Copy(bvalues, prevIndex, cht, 0, index - prevIndex); v.Add(new String(cht)); prevIndex = index; } count = v.Count; String[] strings = new String[count]; for (int c = 0 ; c < count; c++) { strings[c] = (String)v[c]; } obj = strings; } else { obj = bvalues; } break; case TIFFField.TIFF_SHORT: char[] cvalues = new char[count]; for (j = 0; j < count; j++) { cvalues[j] = (char)(ReadUnsignedShort(stream)); } obj = cvalues; break; case TIFFField.TIFF_LONG: long[] lvalues = new long[count]; for (j = 0; j < count; j++) { lvalues[j] = ReadUnsignedInt(stream); } obj = lvalues; break; case TIFFField.TIFF_RATIONAL: long[][] llvalues = new long[count][]; for (j = 0; j < count; j++) { long v0 = ReadUnsignedInt(stream); long v1 = ReadUnsignedInt(stream); llvalues[j] = new long[]{v0, v1}; } obj = llvalues; break; case TIFFField.TIFF_SSHORT: short[] svalues = new short[count]; for (j = 0; j < count; j++) { svalues[j] = ReadShort(stream); } obj = svalues; break; case TIFFField.TIFF_SLONG: int[] ivalues = new int[count]; for (j = 0; j < count; j++) { ivalues[j] = ReadInt(stream); } obj = ivalues; break; case TIFFField.TIFF_SRATIONAL: int[,] iivalues = new int[count,2]; for (j = 0; j < count; j++) { iivalues[j,0] = ReadInt(stream); iivalues[j,1] = ReadInt(stream); } obj = iivalues; break; case TIFFField.TIFF_FLOAT: float[] fvalues = new float[count]; for (j = 0; j < count; j++) { fvalues[j] = ReadFloat(stream); } obj = fvalues; break; case TIFFField.TIFF_DOUBLE: double[] dvalues = new double[count]; for (j = 0; j < count; j++) { dvalues[j] = ReadDouble(stream); } obj = dvalues; break; default: break; } fields[i] = new TIFFField(tag, type, count, obj); } stream.Seek(nextTagOffset); } // Read the offset of the next IFD. try { nextIFDOffset = ReadUnsignedInt(stream); } catch { // broken tiffs may not have this pointer nextIFDOffset = 0; } }
/** 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("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(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(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(); } catch { // empty on purpose } } } } else { throw new DocumentException(afmFile + " is not an AFM or PFM font file."); } EncodingScheme = EncodingScheme.Trim(); if (EncodingScheme.Equals("AdobeStandardEncoding") || EncodingScheme.Equals("StandardEncoding")) { fontSpecific = false; } if (!encoding.StartsWith("#")) { PdfEncodings.ConvertToBytes(" ", enc); // check if the encoding exists } CreateEncoding(); }
private long ReadUnsignedInt(RandomAccessFileOrArray stream) { if (isBigEndian) { return stream.ReadUnsignedInt(); } else { return stream.ReadUnsignedIntLE(); } }
/** Reads the font metrics * @param rf the AFM file * @throws DocumentException the AFM file is invalid * @throws IOException the AFM file could not be read */ public void Process(RandomAccessFileOrArray rf) { string line; bool isMetrics = false; while ((line = rf.ReadLine()) != null) { StringTokenizer tok = new StringTokenizer(line, " ,\n\r\t\f"); if (!tok.HasMoreTokens()) { continue; } string ident = tok.NextToken(); if (ident.Equals("FontName")) { FontName = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("FullName")) { FullName = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("FamilyName")) { FamilyName = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("Weight")) { Weight = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("ItalicAngle")) { ItalicAngle = float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("IsFixedPitch")) { IsFixedPitch = tok.NextToken().Equals("true"); } else if (ident.Equals("CharacterSet")) { CharacterSet = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("FontBBox")) { llx = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); lly = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); urx = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); ury = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("UnderlinePosition")) { UnderlinePosition = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("UnderlineThickness")) { UnderlineThickness = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("EncodingScheme")) { EncodingScheme = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("CapHeight")) { CapHeight = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("XHeight")) { XHeight = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("Ascender")) { Ascender = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("Descender")) { Descender = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("StdHW")) { StdHW = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("StdVW")) { StdVW = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("StartCharMetrics")) { isMetrics = true; break; } } if (!isMetrics) { throw new DocumentException("Missing StartCharMetrics in " + 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(), 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("Missing EndCharMetrics in " + fileName); } if (!CharMetrics.ContainsKey("nonbreakingspace")) { Object[] space = (Object[])CharMetrics["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("Missing EndFontMetrics in " + 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(), NumberFormatInfo.InvariantInfo); Object[] relates = (Object[])KernPairs[first]; 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("Missing EndKernPairs in " + fileName); } rf.Close(); }
internal EnumerateTTC(String ttcFile) { fileName = ttcFile; rf = new RandomAccessFileOrArray(ttcFile); FindNames(); }
/** If the embedded flag is <CODE>false</CODE> or if the font is * one of the 14 built in types, it returns <CODE>null</CODE>, * otherwise the font is read and output in a PdfStream object. * @return the PdfStream containing the font or <CODE>null</CODE> * @throws DocumentException if there is an error reading the font */ public override PdfStream GetFullFontStream() { if (builtinFont || !embedded) { return(null); } RandomAccessFileOrArray rf = null; try { string filePfb = fileName.Substring(0, fileName.Length - 3) + "pfb"; if (pfb == null) { rf = new RandomAccessFileOrArray(filePfb, true); } else { rf = new RandomAccessFileOrArray(pfb); } int fileLength = rf.Length; byte[] st = new byte[fileLength - 18]; int[] lengths = new int[3]; int bytePtr = 0; for (int k = 0; k < 3; ++k) { if (rf.Read() != 0x80) { throw new DocumentException("Start marker missing in " + filePfb); } if (rf.Read() != PFB_TYPES[k]) { throw new DocumentException("Incorrect segment type in " + filePfb); } int size = rf.Read(); size += rf.Read() << 8; size += rf.Read() << 16; size += rf.Read() << 24; lengths[k] = size; while (size != 0) { int got = rf.Read(st, bytePtr, size); if (got < 0) { throw new DocumentException("Premature end in " + filePfb); } bytePtr += got; size -= got; } } return(new StreamFont(st, lengths, compressionLevel)); } finally { if (rf != null) { try { rf.Close(); } catch { // empty on purpose } } } }
private short xheight; /* X height */ #endregion Fields #region Constructors /** Creates a new instance of Pfm2afm */ private Pfm2afm(RandomAccessFileOrArray inp, Stream outp) { this.inp = inp; encoding = Encoding.GetEncoding(1252); this.outp = new StreamWriter(outp, encoding); }
protected void CloseIt() { for (int k = 0; k < readers.Count; ++k) { ((PdfReader)readers[k]).RemoveFields(); } for (int r = 0; r < readers.Count; ++r) { PdfReader reader = (PdfReader)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 = (PdfReader)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 (DictionaryEntry entry in readers2intrefs) { PdfReader reader = (PdfReader)entry.Key; try { file = reader.SafeFile; file.ReOpen(); IntHashtable t = (IntHashtable)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(); reader.Close(); } catch { // empty on purpose } } } pdf.Close(); }
internal RevisionStream(RandomAccessFileOrArray raf, int length) { this.raf = raf; this.length = length; }
public RandomAccessFileOrArray(RandomAccessFileOrArray file) { filename = file.filename; arrayIn = file.arrayIn; startOffset = file.startOffset; }
public PRTokeniser(byte[] pdfIn) { file = new RandomAccessFileOrArray(pdfIn); }
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 {} } }
/// <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."); }
/** Reads the font data. * @param ttfAfm the font as a <CODE>byte</CODE> array, possibly <CODE>null</CODE> * @throws DocumentException the font is invalid * @throws IOException the font file could not be read */ internal void Process(byte[] ttfAfm, bool preload) { tables = new Hashtable(); try { if (ttfAfm == null) rf = new RandomAccessFileOrArray(fileName, preload); else rf = new RandomAccessFileOrArray(ttfAfm); if (ttcIndex.Length > 0) { int dirIdx = int.Parse(ttcIndex); if (dirIdx < 0) throw new DocumentException("The font index for " + fileName + " must be positive."); string mainTag = ReadStandardString(4); if (!mainTag.Equals("ttcf")) throw new DocumentException(fileName + " is not a valid TTC file."); rf.SkipBytes(4); int dirCount = rf.ReadInt(); if (dirIdx >= dirCount) throw new DocumentException("The font index for " + fileName + " must be between 0 and " + (dirCount - 1) + ". It was " + dirIdx + "."); rf.SkipBytes(dirIdx * 4); directoryOffset = rf.ReadInt(); } rf.Seek(directoryOffset); int ttId = rf.ReadInt(); if (ttId != 0x00010000 && ttId != 0x4F54544F) throw new DocumentException(fileName + " is not a valid TTF or OTF file."); int num_tables = rf.ReadUnsignedShort(); rf.SkipBytes(6); for (int k = 0; k < num_tables; ++k) { string tag = ReadStandardString(4); rf.SkipBytes(4); int[] table_location = new int[2]; table_location[0] = rf.ReadInt(); table_location[1] = rf.ReadInt(); tables[tag] = table_location; } CheckCff(); fontName = BaseFont; fullName = GetNames(4); //full name familyName = GetNames(1); //family name allNameEntries = GetAllNames(); if (!justNames) { FillTables(); ReadGlyphWidths(); ReadCMaps(); ReadKerning(); ReadBbox(); GlyphWidths = null; } } finally { if (rf != null) { rf.Close(); if (!embedded) rf = null; } } }
/** * Constructs a TIFFDirectory from a SeekableStream. * The directory parameter specifies which directory to read from * the linked list present in the stream; directory 0 is normally * read but it is possible to store multiple images in a single * TIFF file by maintaing multiple directories. * * @param stream a SeekableStream to read from. * @param directory the index of the directory to read. */ public TIFFDirectory(RandomAccessFileOrArray stream, int directory) { long global_save_offset = stream.FilePointer; long ifd_offset; // Read the TIFF header stream.Seek(0L); int endian = stream.ReadUnsignedShort(); if (!IsValidEndianTag(endian)) { throw new ArgumentException("Bad endianness tag (not 0x4949 or 0x4d4d)."); } isBigEndian = (endian == 0x4d4d); int magic = ReadUnsignedShort(stream); if (magic != 42) { throw new ArgumentException("Bad magic number, should be 42."); } // Get the initial ifd offset as an unsigned int (using a long) ifd_offset = ReadUnsignedInt(stream); for (int i = 0; i < directory; i++) { if (ifd_offset == 0L) { throw new ArgumentException("Directory number too large."); } stream.Seek(ifd_offset); int entries = ReadUnsignedShort(stream); stream.Skip(12*entries); ifd_offset = ReadUnsignedInt(stream); } stream.Seek(ifd_offset); Initialize(stream); stream.Seek(global_save_offset); }
/** * 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; }
// Utilities /** * Returns the number of image directories (subimages) stored in a * given TIFF file, represented by a <code>SeekableStream</code>. */ public static int GetNumDirectories(RandomAccessFileOrArray stream) { long pointer = stream.FilePointer; // Save stream pointer stream.Seek(0L); int endian = stream.ReadUnsignedShort(); if (!IsValidEndianTag(endian)) { throw new ArgumentException("Bad endianness tag (not 0x4949 or 0x4d4d)."); } bool isBigEndian = (endian == 0x4d4d); int magic = ReadUnsignedShort(stream, isBigEndian); if (magic != 42) { throw new ArgumentException("Bad magic number, should be 42."); } stream.Seek(4L); long offset = ReadUnsignedInt(stream, isBigEndian); int numDirectories = 0; while (offset != 0L) { ++numDirectories; // EOFException means IFD was probably not properly terminated. try { stream.Seek(offset); int entries = ReadUnsignedShort(stream, isBigEndian); stream.Skip(12*entries); offset = ReadUnsignedInt(stream, isBigEndian); } catch (EndOfStreamException) { //numDirectories--; break; } } stream.Seek(pointer); // Reset stream pointer return numDirectories; }
/** 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("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(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(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(); } catch { // empty on purpose } } } } else throw new DocumentException(afmFile + " is not an AFM or PFM font file."); EncodingScheme = EncodingScheme.Trim(); if (EncodingScheme.Equals("AdobeStandardEncoding") || EncodingScheme.Equals("StandardEncoding")) { fontSpecific = false; } if (!encoding.StartsWith("#")) PdfEncodings.ConvertToBytes(" ", enc); // check if the encoding exists CreateEncoding(); }
private double ReadDouble(RandomAccessFileOrArray stream) { if (isBigEndian) { return stream.ReadDouble(); } else { return stream.ReadDoubleLE(); } }
/** If the embedded flag is <CODE>false</CODE> or if the font is * one of the 14 built in types, it returns <CODE>null</CODE>, * otherwise the font is read and output in a PdfStream object. * @return the PdfStream containing the font or <CODE>null</CODE> * @throws DocumentException if there is an error reading the font */ public override PdfStream GetFullFontStream() { if (builtinFont || !embedded) return null; RandomAccessFileOrArray rf = null; try { string filePfb = fileName.Substring(0, fileName.Length - 3) + "pfb"; if (pfb == null) rf = new RandomAccessFileOrArray(filePfb, true); else rf = new RandomAccessFileOrArray(pfb); int fileLength = rf.Length; byte[] st = new byte[fileLength - 18]; int[] lengths = new int[3]; int bytePtr = 0; for (int k = 0; k < 3; ++k) { if (rf.Read() != 0x80) throw new DocumentException("Start marker missing in " + filePfb); if (rf.Read() != PFB_TYPES[k]) throw new DocumentException("Incorrect segment type in " + filePfb); int size = rf.Read(); size += rf.Read() << 8; size += rf.Read() << 16; size += rf.Read() << 24; lengths[k] = size; while (size != 0) { int got = rf.Read(st, bytePtr, size); if (got < 0) throw new DocumentException("Premature end in " + filePfb); bytePtr += got; size -= got; } } return new StreamFont(st, lengths, compressionLevel); } finally { if (rf != null) { try { rf.Close(); } catch { // empty on purpose } } } }
private long ReadLong(RandomAccessFileOrArray stream) { if (isBigEndian) { return stream.ReadLong(); } else { return stream.ReadLongLE(); } }
/** Reads the font metrics * @param rf the AFM file * @throws DocumentException the AFM file is invalid * @throws IOException the AFM file could not be read */ public void Process(RandomAccessFileOrArray rf) { string line; bool isMetrics = false; while ((line = rf.ReadLine()) != null) { StringTokenizer tok = new StringTokenizer(line, " ,\n\r\t\f"); if (!tok.HasMoreTokens()) continue; string ident = tok.NextToken(); if (ident.Equals("FontName")) FontName = tok.NextToken("\u00ff").Substring(1); else if (ident.Equals("FullName")) FullName = tok.NextToken("\u00ff").Substring(1); else if (ident.Equals("FamilyName")) FamilyName = tok.NextToken("\u00ff").Substring(1); else if (ident.Equals("Weight")) Weight = tok.NextToken("\u00ff").Substring(1); else if (ident.Equals("ItalicAngle")) ItalicAngle = float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); else if (ident.Equals("IsFixedPitch")) IsFixedPitch = tok.NextToken().Equals("true"); else if (ident.Equals("CharacterSet")) CharacterSet = tok.NextToken("\u00ff").Substring(1); else if (ident.Equals("FontBBox")) { llx = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); lly = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); urx = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); ury = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); } else if (ident.Equals("UnderlinePosition")) UnderlinePosition = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); else if (ident.Equals("UnderlineThickness")) UnderlineThickness = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); else if (ident.Equals("EncodingScheme")) EncodingScheme = tok.NextToken("\u00ff").Substring(1); else if (ident.Equals("CapHeight")) CapHeight = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); else if (ident.Equals("XHeight")) XHeight = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); else if (ident.Equals("Ascender")) Ascender = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); else if (ident.Equals("Descender")) Descender = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); else if (ident.Equals("StdHW")) StdHW = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); else if (ident.Equals("StdVW")) StdVW = (int)float.Parse(tok.NextToken(), NumberFormatInfo.InvariantInfo); else if (ident.Equals("StartCharMetrics")) { isMetrics = true; break; } } if (!isMetrics) throw new DocumentException("Missing StartCharMetrics in " + 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(), 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("Missing EndCharMetrics in " + fileName); if (!CharMetrics.ContainsKey("nonbreakingspace")) { Object[] space = (Object[])CharMetrics["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("Missing EndFontMetrics in " + 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(), NumberFormatInfo.InvariantInfo); Object[] relates = (Object[])KernPairs[first]; 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("Missing EndKernPairs in " + fileName); rf.Close(); }
private int ReadUnsignedShort(RandomAccessFileOrArray stream) { if (isBigEndian) { return stream.ReadUnsignedShort(); } else { return stream.ReadUnsignedShortLE(); } }
internal EnumerateTTC(String ttcFile) { fileName = ttcFile; rf = new RandomAccessFileOrArray(ttcFile); FindNames(); }