本文整理匯總了C#中iTextSharp.text.pdf.PdfReader.GetPdfObject方法的典型用法代碼示例。如果您正苦於以下問題:C# PdfReader.GetPdfObject方法的具體用法?C# PdfReader.GetPdfObject怎麽用?C# PdfReader.GetPdfObject使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類iTextSharp.text.pdf.PdfReader
的用法示例。
在下文中一共展示了PdfReader.GetPdfObject方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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: ManipulatePdf
// ---------------------------------------------------------------------------
/**
* Manipulates a PDF file src
* @param src the original PDF
*/
public byte[] ManipulatePdf(byte[] src) {
PdfReader reader = new PdfReader(src);
PdfObject obj;
PdfDictionary action;
for (int i = 1; i < reader.XrefSize; i++) {
obj = reader.GetPdfObject(i);
if (obj is PdfDictionary) {
action = ((PdfDictionary)obj).GetAsDict(PdfName.A);
if (action == null) continue;
if (PdfName.LAUNCH.Equals(action.GetAsName(PdfName.S))) {
action.Remove(PdfName.F);
action.Remove(PdfName.WIN);
action.Put(PdfName.S, PdfName.JAVASCRIPT);
action.Put(PdfName.JS, new PdfString(
"app.alert('Launch Application Action removed by iText');\r"
));
}
}
}
using (MemoryStream ms = new MemoryStream()) {
using (PdfStamper stamper = new PdfStamper(reader, ms)) {
}
return ms.ToArray();
}
}
示例3: ExtractImages
/// <summary>
/// Extract Image from PDF file and Store in Image Object
/// </summary>
/// <param name="pdfPath">Specify PDF Source Path</param>
/// <returns>elenco dei path relativi alle immagini estratte</returns>
public static List<string> ExtractImages(String pdfPath)
{
var pathTokens = pdfPath.Split(new char[] { '\\' });
var session = pathTokens[pathTokens.Length - 2];
var basePath = Path.GetDirectoryName(pdfPath);
var filename = Path.GetFileNameWithoutExtension(pdfPath);
List<string> urls = new List<string>();
RandomAccessFileOrArray RAFObj = null;
PdfReader PDFReaderObj = null;
PdfObject PDFObj = null;
PdfStream PDFStreamObj = null;
//try
//{
RAFObj = new RandomAccessFileOrArray(pdfPath);//(PDFSourcePath);
PDFReaderObj = new PdfReader(RAFObj, null);
var info = PDFReaderObj.Info;
var j = 0;
for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
{
PDFObj = PDFReaderObj.GetPdfObject(i);
if ((PDFObj != null) && PDFObj.IsStream())
{
PdfDictionary pd = (PdfDictionary)PDFObj;
PDFStreamObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
iTextSharp.text.pdf.PdfObject subtype = PDFStreamObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);
if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
{
filename = filename + "_" + (++j).ToString();
byte[] bytes = PdfReader.GetStreamBytesRaw((iTextSharp.text.pdf.PRStream)PDFStreamObj);
Tiff tiff = Tiff.Open(Path.Combine(basePath, filename + ".tif"), "w");
tiff.SetField(TiffTag.IMAGEWIDTH, UInt32.Parse(pd.Get(PdfName.WIDTH).ToString()));
tiff.SetField(TiffTag.IMAGELENGTH, UInt32.Parse(pd.Get(PdfName.HEIGHT).ToString()));
tiff.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4);
tiff.SetField(TiffTag.BITSPERSAMPLE, UInt32.Parse(pd.Get(PdfName.BITSPERCOMPONENT).ToString()));
tiff.SetField(TiffTag.SAMPLESPERPIXEL, 1);
tiff.WriteRawStrip(0, bytes, bytes.Length);
tiff.Close();
var bmp = tiffToBitmap(Path.Combine(basePath, filename + ".tif"));
if (bmp != null)
{
bmp.Save(Path.Combine(basePath, filename + ".bmp"));
urls.Add( session + "/" + filename + ".bmp");
}
}
}
}
PDFReaderObj.Close();
return urls;
}
示例4: ExtractImagesFromPDF
public static void ExtractImagesFromPDF(string password, string key, string docPath, string pagePath, PageCollection pages)
{
Page page = null;
// NOTE: This will only get the first image it finds per page.
PdfReader pdf = new PdfReader(Utility.Security.AES.DecryptFile(key, docPath));
//RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(p);
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.
page = new Page();
page.Order = pages.Count;
page.Save();
page.Token = Utility.Security.AES.GetToken(page.Id, password);
//string path = System.IO.Path.Combine(page.Filename, 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 = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.FormatDescription == "JPEG");
System.IO.MemoryStream ms = new System.IO.MemoryStream();
img.Save(ms, jpegEncoder, parms);
System.IO.File.WriteAllBytes(System.IO.Path.Combine(pagePath, page.Filename), SoftFluent.Samples.GED.Utility.Security.AES.EncryptStream(page.Token, ms.ToArray()).ToArray());
ms.Close();
pages.Add(page);
}
}
}
}
}
catch
{
throw;
}
finally
{
pdf.Close();
//raf.Close();
}
}
示例5: GetImages
public List<System.Drawing.Image> GetImages(string path)
{
FileStream fs = File.OpenRead(path);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, (int)fs.Length);
//List<double> match = new List<double>();
List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();
//iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
PdfReader PDFReaderObj = null;
PdfObject PDFObj = null;
PdfStream PDFStremObj = null;
PdfDictionary dic;
//RAFObj = new RandomAccessFileOrArray(data);
PDFReaderObj = new PdfReader(path);
for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
{
PDFObj = PDFReaderObj.GetPdfObject(i);
string filter;
if ((PDFObj != null) && PDFObj.IsStream())
{
PDFStremObj = (PdfStream)PDFObj;
PdfObject subtype = PDFStremObj.Get(PdfName.SUBTYPE);
if ((subtype != null) && subtype.ToString() == PdfName.IMAGE.ToString())
{
byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)PDFStremObj);
if ((bytes != null))
{
dic = (PdfDictionary)PDFObj;
MemoryStream ms = new System.IO.MemoryStream(bytes);
filter = dic.Get(PdfName.FILTER).ToString();
if (filter.Equals("/DCTDecode"))
{
ms.Position = 0;
System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(ms);
ImgList.Add(ImgPDF);
}
}
}
}
}
PDFReaderObj.Close();
return ImgList;
}
示例6: 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();
}
}
示例7: ManipulatePdf
// ---------------------------------------------------------------------------
/**
* Manipulates a PDF file src with the byte array as result
*/
public byte[] ManipulatePdf(byte[] pdf)
{
PdfName key = new PdfName("ITXT_SpecialId");
PdfName value = new PdfName("123456789");
// Read the file
PdfReader reader = new PdfReader(pdf);
int n = reader.XrefSize;
PdfObject pdfObject;
PRStream prStream;
// Look for image and manipulate image prStream
for (int i = 0; i < n; i++) {
pdfObject = reader.GetPdfObject(i);
if (pdfObject == null || !pdfObject.IsStream()) continue;
prStream = (PRStream) pdfObject;
byte[] imageBytes;
if (value.Equals(prStream.Get(key))) {
PdfImageObject image = new PdfImageObject(prStream);
using (System.Drawing.Image original = image.GetDrawingImage()) {
if (original == null) continue;
int width = (int)(original.Width * FACTOR);
int height = (int)(original.Height * FACTOR);
using (System.Drawing.Image thumb = new Bitmap(width, height) ) {
using ( Graphics graphic = Graphics.FromImage(thumb) ) {
graphic.DrawImage(original, 0, 0, width, height);
using (MemoryStream ms = new MemoryStream()) {
thumb.Save(ms, ImageFormat.Jpeg);
imageBytes = ms.ToArray();
}
}
}
prStream.Clear();
prStream.SetData(imageBytes, false, PRStream.NO_COMPRESSION);
prStream.Put(PdfName.TYPE, PdfName.XOBJECT);
prStream.Put(PdfName.SUBTYPE, PdfName.IMAGE);
prStream.Put(key, value);
prStream.Put(PdfName.FILTER, PdfName.DCTDECODE);
prStream.Put(PdfName.WIDTH, new PdfNumber(width));
prStream.Put(PdfName.HEIGHT, new PdfNumber(height));
prStream.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
prStream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
}
}
}
// Save altered PDF
using (MemoryStream ms = new MemoryStream()) {
using (PdfStamper stamper = new PdfStamper(reader, ms)) {
}
return ms.ToArray();
}
}
示例8: ManipulatePdf
/**
* Removes the embedded font
*/
public void ManipulatePdf(String src, String dest)
{
CreatePdf(src);
// we create a reader instance
PdfReader reader = new PdfReader(src);
// we loop over all objects
PdfObject obj;
for (int i = 1; i < reader.XrefSize; i++)
{
obj = reader.GetPdfObject(i);
// we skip all objects that aren't a dictionary
if (obj == null || !obj.IsDictionary())
continue;
// we process all dictionaries
UnembedTTF((PdfDictionary) obj);
}
// removing unused objects will remove unused font file streams
reader.RemoveUnusedObjects();
// we persist the altered document
Stream os = new FileStream(dest, FileMode.Create);
PdfStamper stamper = new PdfStamper(reader, os);
stamper.Close();
}
示例9: ManipulatePdf
// ---------------------------------------------------------------------------
/**
* Manipulates a PDF file src with the file dest as result
* @param src the original PDF
*/
public byte[] ManipulatePdf(byte[] src) {
// the font file
byte[] fontfile = null;
using (FileStream fs = new FileStream(
FONT, FileMode.Open, FileAccess.Read))
{
fontfile = new byte[fs.Length];
fs.Read(fontfile, 0, (int) fs.Length);
}
// create a new stream for the font file
PdfStream stream = new PdfStream(fontfile);
stream.FlateCompress();
stream.Put(PdfName.LENGTH1, new PdfNumber(fontfile.Length));
// create a reader object
PdfReader reader = new PdfReader(src);
int n = reader.XrefSize;
PdfDictionary font;
using (MemoryStream ms = new MemoryStream()) {
using (PdfStamper stamper = new PdfStamper(reader, ms)) {
PdfName fontname = new PdfName(FONTNAME);
for (int i = 0; i < n; i++) {
PdfObject objectPdf = reader.GetPdfObject(i);
if (objectPdf == null || !objectPdf.IsDictionary()) {
continue;
}
font = (PdfDictionary)objectPdf;
if (PdfName.FONTDESCRIPTOR.Equals(font.Get(PdfName.TYPE))
&& fontname.Equals(font.Get(PdfName.FONTNAME)))
{
PdfIndirectObject objref = stamper.Writer.AddToBody(stream);
font.Put(PdfName.FONTFILE2, objref.IndirectReference);
}
}
}
return ms.ToArray();
}
}
示例10: 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;
}
示例11: ExtractImageFromPdf1
//
// Event handler for extract images button
//
private void ExtractImageFromPdf1(string sourcePDF)
{
MemoryStream memStream;
byte[] bytes;
// Imagecount is used to allow a unique key to be generated for each image - the key will be the imagecount itsself
int imagecount = 0;
//
// Now we can start by loading the PDF document into our IText control
//
try
{
PdfReader rd = new PdfReader(sourcePDF);
for (int i = 0; i < rd.XrefSize; i++)
{
PdfObject pdfObj = rd.GetPdfObject(i);
if (pdfObj != null)
{
if (pdfObj.IsStream() == true)
{
PdfStream stream = (PdfStream)pdfObj;
PdfObject subtype = stream.Get(PdfName.SUBTYPE);
if (subtype != null)
{
if (subtype.ToString() == PdfName.IMAGE.ToString())
{
// Now we need to get the image stream
bytes = PdfReader.GetStreamBytesRaw((PRStream)stream);
if (bytes != null)
{
PdfDictionary dic = (PdfDictionary)pdfObj;
//
// Get the information about this image
//
String filter = dic.Get(PdfName.FILTER).ToString();
String width = dic.Get(PdfName.WIDTH).ToString();
String height = dic.Get(PdfName.HEIGHT).ToString();
String bpp = dic.Get(PdfName.BITSPERCOMPONENT).ToString();
String colorspace = dic.Get(PdfName.COLORSPACE).ToString();
try
{
BinaryWriter bw = null;
FileStream fs = null;
switch (filter)
{
case "/DCTDecode":
memStream = new MemoryStream(bytes);
memStream.Position = 0;
// Create the image from the stream
System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
// Save the image
img.Save(imagecount + ".jpg", ImageFormat.Jpeg);
break;
case "/JBIG2Decode":
// STANDARD HEADER NO PAGES, SEQUENTIAL ORDER
byte[] JBIGHeader = new byte[] { 0x97, 0x4a, 0x42, 0x32, 0x0d, 0x0a, 0x1a, 0x0a, 0x3 };
fs = new FileStream(imagecount + ".jb2", FileMode.Create, FileAccess.ReadWrite);
bw = new BinaryWriter(fs);
bw.Write(JBIGHeader);
bw.Write(bytes);
bw.Close();
break;
case "/FlateDecode":
PixelFormat pf = PixelFormat.Format24bppRgb;
string fileext = ".png";
ImageFormat imgformat = ImageFormat.Png;
int actualw = Int32.Parse(width);
int actualh = Int32.Parse(height);
switch (Int32.Parse(bpp))
{
case 1:
pf = PixelFormat.Format1bppIndexed;
imgformat = ImageFormat.Gif;
fileext = ".gif";
break;
case 8:
//.........這裏部分代碼省略.........
示例12: GenerateFromTemplate
public static Stream GenerateFromTemplate(DocumentTemplate dt, DiscoDataContext Database, IAttachmentTarget Data, User CreatorUser, DateTime TimeStamp, DocumentState State, bool FlattenFields = false)
{
// Validate Data
switch (dt.Scope)
{
case DocumentTemplate.DocumentTemplateScopes.Device:
if (!(Data is Device))
throw new ArgumentException("This AttachmentType is configured for Devices only", "Data");
break;
case DocumentTemplate.DocumentTemplateScopes.Job:
if (!(Data is Job))
throw new ArgumentException("This AttachmentType is configured for Jobs only", "Data");
break;
case DocumentTemplate.DocumentTemplateScopes.User:
if (!(Data is User))
throw new ArgumentException("This AttachmentType is configured for Users only", "Data");
break;
default:
throw new InvalidOperationException("Invalid AttachmentType Scope");
}
Database.Configuration.LazyLoadingEnabled = true;
// Override FlattenFields if Document Template instructs.
if (dt.FlattenForm)
FlattenFields = true;
ConcurrentDictionary<string, Expression> expressionCache = dt.PdfExpressionsFromCache(Database);
string templateFilename = dt.RepositoryFilename(Database);
PdfReader pdfReader = new PdfReader(templateFilename);
MemoryStream pdfGeneratedStream = new MemoryStream();
PdfStamper pdfStamper = new PdfStamper(pdfReader, pdfGeneratedStream);
pdfStamper.FormFlattening = FlattenFields;
pdfStamper.Writer.CloseStream = false;
IDictionary expressionVariables = Expression.StandardVariables(dt, Database, CreatorUser, TimeStamp, State);
foreach (string pdfFieldKey in pdfStamper.AcroFields.Fields.Keys)
{
if (pdfFieldKey.Equals("DiscoAttachmentId", StringComparison.OrdinalIgnoreCase))
{
AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey];
string fieldValue = dt.CreateUniqueIdentifier(Database, Data, CreatorUser, TimeStamp, 0).ToJson();
if (FlattenFields)
pdfStamper.AcroFields.SetField(pdfFieldKey, String.Empty);
else
pdfStamper.AcroFields.SetField(pdfFieldKey, fieldValue);
IList<AcroFields.FieldPosition> pdfFieldPositions = pdfStamper.AcroFields.GetFieldPositions(pdfFieldKey);
for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++)
{
AcroFields.FieldPosition pdfFieldPosition = pdfFieldPositions[pdfFieldOrdinal];
// Create Binary Unique Identifier
var pageUniqueId = dt.CreateUniqueIdentifier(Database, Data, CreatorUser, TimeStamp, pdfFieldPosition.page);
var pageUniqueIdBytes = pageUniqueId.ToQRCodeBytes();
// Encode to QRCode byte array
var pageUniqueIdWidth = (int)pdfFieldPosition.position.Width;
var pageUniqueIdHeight = (int)pdfFieldPosition.position.Height;
var pageUniqueIdEncoded = QRCodeBinaryEncoder.Encode(pageUniqueIdBytes, pageUniqueIdWidth, pageUniqueIdHeight);
// Encode byte array to Image
var pageUniqueIdImageData = CCITTG4Encoder.Compress(pageUniqueIdEncoded, pageUniqueIdWidth, pageUniqueIdHeight);
var pageUniqueIdImage = iTextSharp.text.Image.GetInstance(pageUniqueIdWidth, pageUniqueIdHeight, false, 256, 1, pageUniqueIdImageData, null);
// Add to the pdf page
pageUniqueIdImage.SetAbsolutePosition(pdfFieldPosition.position.Left, pdfFieldPosition.position.Bottom);
pdfStamper.GetOverContent(pdfFieldPosition.page).AddImage(pageUniqueIdImage);
}
// Hide Fields
PdfDictionary field = fields.GetValue(0);
if ((PdfName)field.Get(PdfName.TYPE) == PdfName.ANNOT)
{
field.Put(PdfName.F, new PdfNumber(6));
}
else
{
PdfArray fieldKids = (PdfArray)field.Get(PdfName.KIDS);
foreach (PdfIndirectReference fieldKidRef in fieldKids)
{
((PdfDictionary)pdfReader.GetPdfObject(fieldKidRef.Number)).Put(PdfName.F, new PdfNumber(6));
}
}
}
else
{
Expression fieldExpression = null;
if (expressionCache.TryGetValue(pdfFieldKey, out fieldExpression))
{
if (fieldExpression.IsDynamic)
{
Tuple<string, bool, object> fieldExpressionResult = fieldExpression.Evaluate(Data, expressionVariables);
if (fieldExpressionResult.Item3 != null)
{
IImageExpressionResult imageResult = (fieldExpressionResult.Item3 as IImageExpressionResult);
//.........這裏部分代碼省略.........
示例13: ExtractImages
/// <summary>
/// Extracts the images from the given PDF file and save it into the given images folder
/// </summary>
/// <param name="sourcePdfFile"></param>
/// <param name="imagesFolderPath"></param>
public List<string> ExtractImages(string sourcePdfFile, string imagesFolderPath)
{
List<string> RetVal = new List<string>();
string ImageFileName = string.Empty;
RandomAccessFileOrArray raf = null;
PdfReader reader = null;
PdfObject pdfObj = null;
PdfStream pdfStream = null;
int ImageNo = 1;
try
{
raf = new RandomAccessFileOrArray(sourcePdfFile);
reader = new PdfReader(raf, null);
for (int i = 0; i < reader.XrefSize; i++)
{
pdfObj = reader.GetPdfObject(i);
if (pdfObj != null && pdfObj.IsStream())
{
pdfStream = (PdfStream)(pdfObj);
PdfObject subtype = pdfStream.Get(PdfName.SUBTYPE);
if (subtype != null && subtype.ToString() == PdfName.IMAGE.ToString())
{
Byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)(pdfStream));
if (bytes != null)
{
try
{
using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
{
memStream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
ImageFileName = imagesFolderPath + "\\" + Path.GetFileNameWithoutExtension(sourcePdfFile) + "_" + ImageNo + ".png";
img.Save(ImageFileName);
RetVal.Add(imagesFolderPath + "\\" + Path.GetFileNameWithoutExtension(sourcePdfFile) + "_" + ImageNo + ".png");
ImageNo++;
}
}
catch (Exception ex)
{
//'Most likely the image is in an unsupported format
//'Do nothing
//'You can add your own code to handle this exception if you want to
}
}
}
}
}
reader.Close();
}
catch (Exception ex)
{
//ExceptionFacade.ThrowException(ex);
}
return RetVal;
}
示例14: ExtractImagesFromPDF
private static List<string> ExtractImagesFromPDF(string filename)
{
List<string> files = new List<string>();
try
{
PdfReader pdf = new PdfReader(filename);
for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
{
List<System.Drawing.Image> imgs = new List<System.Drawing.Image>();
PdfDictionary pg = pdf.GetPageN(pageNumber);
PdfDictionary res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
PdfDictionary xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
if (xobj != null)
{
foreach (PdfName name in xobj.Keys)
{
PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
PdfName type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
if (PdfName.IMAGE.Equals(type))
{
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 (MemoryStream memStream = new MemoryStream(bytes))
{
memStream.Position = 0;
imgs.Add(System.Drawing.Image.FromStream(memStream));
}
}
}
}
}
}
Bitmap FinalImage;
if (imgs.Count == 1)
{
FinalImage = new Bitmap(imgs[0]);
}
else
{
FinalImage = new Bitmap(MergeImages(imgs));
}
string path = Path.Combine(o.OutputDirectory, String.Format(@"{0}-{1}.jpg", Path.GetFileNameWithoutExtension(filename), pageNumber.ToString().PadLeft(pdf.NumberOfPages.ToString().Length, '0')));
FinalImage.Save(path, ImageFormat.Jpeg);
FinalImage.Dispose();
files.Add(path);
}
pdf.Close();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
_error = true;
}
return files;
}