Download link will download the file in system download path - filestream

Error Code with fileinnfo
FileInfo File = new FileInfo(Server.MapPath("/Content/ExcelFiles/SalesTarget.xlsx"));
if (File != null)
{
int Size = Convert.ToInt32(File.Length);
string FileName = File.FullName;
int Position = FileName.LastIndexOf("\\");
FileName = FileName.Substring(Position + 1);
string test = File.GetType().ToString();
string filepath = Server.MapPath("/Content/ExcelFiles/SalesTarget.xlsx");
string ContentType = MimeMapping.GetMimeMapping(Server.MapPath("/Content/ExcelFiles/SalesTarget.xlsx"));
byte[] FileData = new byte[Size];
char[] chars = Encoding.Unicode.GetChars(FileData);
StreamReader reader = new StreamReader(filepath);
reader.Read(chars, 0, Size); // Throwing error here
Response.ContentType = ContentType;
StringBuilder SB = new StringBuilder();
SB.Append("filename=");
SB.Append(FileName);
Response.AddHeader("Content-Disposition", SB.ToString());
Response.BinaryWrite(FileData);
Response.Flush();
Response.End();
//File..Read(FileData, 0, Size);
}
Running Code with Httppostedfile Class:
HttpPostedFileBase File = Request.Files["FileToLoad"];
if (File != null)
{
int Size = File.ContentLength;
if (Size <= 0)
{
ViewData["ERROR"] = "You uploaded an empty file,please browse a valid file to upload";
return View("../Shared/Error");
}
string FileName = File.FileName;
int Position = FileName.LastIndexOf("\\");
FileName = FileName.Substring(Position + 1);
string ContentType = File.ContentType;
byte[] FileData = new byte[Size];
File.InputStream.Read(FileData, 0, Size);
theModel.AddAFile(FileName, Size, ContentType, FileData);
}
I want to download existing file from directory instead of using httppostedfile, so I am getting error while reading file data.

Related

Flutter Zip & Unzip

Hello i want to ask how to zip and unzip become string in flutter :
Example :
final int BUFFER_SIZE = 40;
ByteArrayInputStream is = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
StringBuilder string = new StringBuilder();
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gis.read(data)) != -1) { string.append(new String(data, 0, bytesRead)); }
gis.close();
is.close();
return string.toString();
You can use archive plugin to zip and unzip files.
To unzip:
// Read the Zip file from disk.
final bytes = File('test.zip').readAsBytesSync();
// Decode the Zip file
final archive = ZipDecoder().decodeBytes(bytes);
// Extract the contents of the Zip archive to disk.
for (final file in archive) {
final filename = file.name;
if (file.isFile) {
final data = file.content as List<int>;
File('out/' + filename)
..createSync(recursive: true)
..writeAsBytesSync(data);
} else {
Directory('out/' + filename).create(recursive: true);
}
}
To create a zip file:
// Zip a directory to out.zip using the zipDirectory convenience method
var encoder = ZipFileEncoder();
encoder.zipDirectory(Directory('out'), filename: 'out.zip');

How to specify parameters in box-view API header?

I am using the following piece of C# code to upload, convert and download a .pptx file, via Box view API.
var boxViewID = "";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
String url_ = #"https://upload.view-api.box.com/1/documents";
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url_);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Headers.Add("Authorization:Token " + "MY_CODE"/*Configuration.BoxViewAPIKey*/);
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
wr.Timeout = 1000000;
wr.SendChunked = true;
DateTime start = DateTime.Now;
Exception exc = null;
Stream rs = wr.GetRequestStream();
try
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; non_svg=\"true\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate,"file", file, contentType);
Console.WriteLine(header);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[40960];
int bytesRead = 0;
int totalSent = 0;
int totalLength = (int)fileStream.Length;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
totalSent += bytesRead;
var percent = new decimal(100.0 * totalSent / totalLength);
if (progress != null)
{
progress("Box processing", percent);
}
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
}
catch(Exception ex)
{
exc = ex;
}
DateTime end = DateTime.Now;
int seconds = (int)(end - start).TotalSeconds;
if(seconds>=0)
{
if(exc!=null)
{
throw exc;
}
}
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
var res = reader2.ReadToEnd();
var docRes = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(res);
if (docRes["id"] != null)
boxViewID = docRes["id"];
}
catch (Exception ex)
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
return boxViewID;
Specifying "non_svg" parameter should create .png images for every slide in the presentation (instead of .svg + .html pairs). However, the API seems to ignore this part of the request and I am always getting svg files.
Any idea on what am I doing wrong? Thanks!
The non_svg option causes PNG representations to be generated for each page, but the SVG representation is still generated. The viewer will only load the PNG files if SVG is not supported in the browser (basically only IE 8). Try changing page-1.svg to page-1.png in the browser (e.g., https://view-api.box.com/1/sessions/465c5d45caf04752a6113b0e5df593a5/assets/page-1.png vs https://view-api.box.com/1/sessions/465c5d45caf04752a6113b0e5df593a5/assets/page-1.svg). All of the assets will exist in content.zip if you use the documents content endpoint.

download file from url in gwt

I want to download a file from internet and I have url of that file . so I wrote a download servlet :
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String pathToDownload = request.getParameter("url");
URL url = new URL(pathToDownload);
URLConnection uc = url.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
InputStream is = uc.getInputStream();
response.setContentType(contentType);
// resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "");
ServletOutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
in this i want to show the popup when user clicks on file whether to save or not so there is
resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "");
but I want the filename same as filename on internate so additionally what is needed in above snippet?
Cut substring from the last "/" to the end of the URL string - this is your file name.
String disposition = httpConn.getHeaderField("Content-Disposition");
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index != 0) {
fileName = disposition.substring(index + 9,
disposition.length());
}
} else {
// extracts file name from URL
fileName = link.substring(link.lastIndexOf("/") + 1,
link.length());
}

saving email attachments as binary to the database using c#

I can get email attachments from exchange server 2003 (MAPI.Attachment). How can I save the pdf attachment file as binary into the database?
Here's some code to understand better. For testing purposes I am saving the attachment pdf file into a filesystem. How ca I go about saving that into a database? Or how can I convert that into a byte array? Also, how can I get the size of the file since I need that when I declare the byte array "fileData"...
byte[] fileData = new byte[10000];
string[] fileTokens = new string[2];
string[] result = new string[3];
message.Unread = false;
emailSubject = message.Subject.ToString();
emailBody = message.Text.ToString();
MAPI.Attachments test = null;
test = (MAPI.Attachments)message.Attachments;
int attachmentCount = (int)test.Count;
for (int loopCounter = 1; loopCounter <= attachmentCount; loopCounter++)
{
MAPI.Attachment test2 = (MAPI.Attachment)test.get_Item(loopCounter);
bool temp = (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0);
if (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0)
{
//test2.ReadFromFile(fileData);
test2.WriteToFile("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
}
RequestHistorySet historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);
bool res = historySet.Update();
message.Unread = false;
message.Update();
And here's the Update function from historySet Class
public bool Update()
{
using (SqlConnection mySqlConnection = ...))
{
// Set up the Command object
SqlCommand myCommand = new SqlCommand("CONNECTION STRING..", mySqlConnection);
// Set up the OriginalName parameter
SqlParameter prmId = new SqlParameter("#id", SqlDbType.Int);
prmId.Value = id;
myCommand.Parameters.Add(prmId);
SqlParameter prmRequsetDate = new SqlParameter("#requestDate", SqlDbType.DateTime);
prmRequsetDate.Value = requestDate;
myCommand.Parameters.Add(prmRequsetDate);
// Set up the FileData parameter
SqlParameter prmFileData = new SqlParameter("#uplodedQuote_File ", SqlDbType.VarBinary);
prmFileData.Value = fileData;
prmFileData.Size = fileData.Length;
myCommand.Parameters.Add(prmFileData);
SqlParameter prmFileExtension = new SqlParameter("#uplodedQuote_Ext", SqlDbType.NVarChar);
prmFileExtension.Value = fileExtension;
myCommand.Parameters.Add(prmFileExtension);
// Execute the command, and clean up.
mySqlConnection.Open();
bool result = myCommand.ExecuteNonQuery() > 0;
mySqlConnection.Close();
return result;
}
}
As of now this is what I have done. I save it to a filesystem and then read from there.
test2.WriteToFile("d:\\data\\" + test2.Name);
fileData = FileToByteArray("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
TryToDelete("d:\\data\\" + test2.Name);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);

Extract images using iTextSharp

I have been using this code with great success to pull out the first image found in each page of a PDF. However, it is now not working with some new PDFs for an uknown reason. I have used other tools (Datalogics, etc) that do pull out the images fine with these new PDFs. However, I do not want to buy Datalogics or any tool if I can use iTextSharp. Can anybody tell me why this code is not finding the images in the PDF?
Knowns: my PDFs only have 1 image per page and nothing else.
using iTextSharp.text;
using iTextSharp.text.pdf;
...
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);
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 (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 = Utilities.GetImageEncoder("JPEG");
img.Save(path, jpegEncoder, parms);
break;
}
}
}
}
}
}
}
}
catch
{
throw;
}
finally
{
pdf.Close();
raf.Close();
}
}
I found that my problem was that I was not recursively searching inside of forms and groups for images. Basically, the original code would only find images that were embedded at the root of the pdf document. Here is the revised method plus a new method (FindImageInPDFDictionary) that recursively searches for images in the page. NOTE: the flaws of only supporting JPEG and non-compressed images still applies. See R Ubben's code for options to fix those flaws. HTH someone.
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 = Utilities.GetImageEncoder("JPEG");
img.Save(path, jpegEncoder, parms);
}
}
}
}
}
catch
{
throw;
}
finally
{
pdf.Close();
raf.Close();
}
}
private static PdfObject FindImageInPDFDictionary(PdfDictionary pg)
{
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));
//image at the root of the pdf
if (PdfName.IMAGE.Equals(type))
{
return obj;
}// image inside a form
else if (PdfName.FORM.Equals(type))
{
return FindImageInPDFDictionary(tg);
} //image inside a group
else if (PdfName.GROUP.Equals(type))
{
return FindImageInPDFDictionary(tg);
}
}
}
}
return null;
}
Here is a simpler solution:
iTextSharp.text.pdf.parser.PdfImageObject pdfImage =
new iTextSharp.text.pdf.parser.PdfImageObject(imgPRStream);
System.Drawing.Image img = pdfImage.GetDrawingImage();
The following code incorporates all of Dave and R Ubben's ideas above, plus it returns a full list of all the images and also deals with multiple bit depths. I had to convert it to VB for the project I'm working on though, sorry about that...
Private Sub getAllImages(ByVal dict As pdf.PdfDictionary, ByVal images As List(Of Byte()), ByVal doc As pdf.PdfReader)
Dim res As pdf.PdfDictionary = CType(pdf.PdfReader.GetPdfObject(dict.Get(pdf.PdfName.RESOURCES)), pdf.PdfDictionary)
Dim xobj As pdf.PdfDictionary = CType(pdf.PdfReader.GetPdfObject(res.Get(pdf.PdfName.XOBJECT)), pdf.PdfDictionary)
If xobj IsNot Nothing Then
For Each name As pdf.PdfName In xobj.Keys
Dim obj As pdf.PdfObject = xobj.Get(name)
If (obj.IsIndirect) Then
Dim tg As pdf.PdfDictionary = CType(pdf.PdfReader.GetPdfObject(obj), pdf.PdfDictionary)
Dim subtype As pdf.PdfName = CType(pdf.PdfReader.GetPdfObject(tg.Get(pdf.PdfName.SUBTYPE)), pdf.PdfName)
If pdf.PdfName.IMAGE.Equals(subtype) Then
Dim xrefIdx As Integer = CType(obj, pdf.PRIndirectReference).Number
Dim pdfObj As pdf.PdfObject = doc.GetPdfObject(xrefIdx)
Dim str As pdf.PdfStream = CType(pdfObj, pdf.PdfStream)
Dim bytes As Byte() = pdf.PdfReader.GetStreamBytesRaw(CType(str, pdf.PRStream))
Dim filter As String = tg.Get(pdf.PdfName.FILTER).ToString
Dim width As String = tg.Get(pdf.PdfName.WIDTH).ToString
Dim height As String = tg.Get(pdf.PdfName.HEIGHT).ToString
Dim bpp As String = tg.Get(pdf.PdfName.BITSPERCOMPONENT).ToString
If filter = "/FlateDecode" Then
bytes = pdf.PdfReader.FlateDecode(bytes, True)
Dim pixelFormat As System.Drawing.Imaging.PixelFormat
Select Case Integer.Parse(bpp)
Case 1
pixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed
Case 24
pixelFormat = Drawing.Imaging.PixelFormat.Format24bppRgb
Case Else
Throw New Exception("Unknown pixel format " + bpp)
End Select
Dim bmp As New System.Drawing.Bitmap(Int32.Parse(width), Int32.Parse(height), pixelFormat)
Dim bmd As System.Drawing.Imaging.BitmapData = bmp.LockBits(New System.Drawing.Rectangle(0, 0, Int32.Parse(width), Int32.Parse(height)), System.Drawing.Imaging.ImageLockMode.WriteOnly, pixelFormat)
Marshal.Copy(bytes, 0, bmd.Scan0, bytes.Length)
bmp.UnlockBits(bmd)
Using ms As New MemoryStream
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
bytes = ms.GetBuffer
End Using
End If
images.Add(bytes)
ElseIf pdf.PdfName.FORM.Equals(subtype) Or pdf.PdfName.GROUP.Equals(subtype) Then
getAllImages(tg, images, doc)
End If
End If
Next
End If
End Sub
This is just another rehash of others' ideas, but the one that worked for me. Here I use #Malco's image grabbing snippet with R Ubben's looping:
private IList<System.Drawing.Image> GetImagesFromPdfDict(PdfDictionary dict, PdfReader doc)
{
List<System.Drawing.Image> images = new List<System.Drawing.Image>();
PdfDictionary res = (PdfDictionary)(PdfReader.GetPdfObject(dict.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 subtype = (PdfName)(PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE)));
if (PdfName.IMAGE.Equals(subtype))
{
int xrefIdx = ((PRIndirectReference)obj).Number;
PdfObject pdfObj = doc.GetPdfObject(xrefIdx);
PdfStream str = (PdfStream)(pdfObj);
iTextSharp.text.pdf.parser.PdfImageObject pdfImage =
new iTextSharp.text.pdf.parser.PdfImageObject((PRStream)str);
System.Drawing.Image img = pdfImage.GetDrawingImage();
images.Add(img);
}
else if (PdfName.FORM.Equals(subtype) || PdfName.GROUP.Equals(subtype))
{
images.AddRange(GetImagesFromPdfDict(tg, doc));
}
}
}
}
return images;
}
De c# version:
private IList<System.Drawing.Image> GetImagesFromPdfDict(PdfDictionary dict, PdfReader doc){
List<System.Drawing.Image> images = new List<System.Drawing.Image>();
PdfDictionary res = (PdfDictionary)(PdfReader.GetPdfObject(dict.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));
pdf.PdfName subtype = (pdf.PdfName)(pdf.PdfReader.GetPdfObject(tg.Get(pdf.PdfName.SUBTYPE)));
if (pdf.PdfName.IMAGE.Equals(subtype))
{
int xrefIdx = ((pdf.PRIndirectReference)obj).Number;
pdf.PdfObject pdfObj = doc.GetPdfObject(xrefIdx);
pdf.PdfStream str = (pdf.PdfStream)(pdfObj);
byte[] bytes = pdf.PdfReader.GetStreamBytesRaw((pdf.PRStream)str);
string filter = tg.Get(pdf.PdfName.FILTER).ToString();
string width = tg.Get(pdf.PdfName.WIDTH).ToString();
string height = tg.Get(pdf.PdfName.HEIGHT).ToString();
string bpp = tg.Get(pdf.PdfName.BITSPERCOMPONENT).ToString();
if (filter == "/FlateDecode")
{
bytes = pdf.PdfReader.FlateDecode(bytes, true);
System.Drawing.Imaging.PixelFormat pixelFormat;
switch (int.Parse(bpp))
{
case 1:
pixelFormat = System.Drawing.Imaging.PixelFormat.Format1bppIndexed;
break;
case 24:
pixelFormat = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
break;
default:
throw new Exception("Unknown pixel format " + bpp);
}
var bmp = new System.Drawing.Bitmap(Int32.Parse(width), Int32.Parse(height), pixelFormat);
System.Drawing.Imaging.BitmapData bmd = bmp.LockBits(new System.Drawing.Rectangle(0, 0, Int32.Parse(width),
Int32.Parse(height)), System.Drawing.Imaging.ImageLockMode.WriteOnly, pixelFormat);
Marshal.Copy(bytes, 0, bmd.Scan0, bytes.Length);
bmp.UnlockBits(bmd);
using (var ms = new MemoryStream())
{
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
bytes = ms.GetBuffer();
}
}
images.Add(System.Drawing.Image.FromStream(new MemoryStream(bytes)));
}
else if (pdf.PdfName.FORM.Equals(subtype) || pdf.PdfName.GROUP.Equals(subtype))
{
images.AddRange(GetImagesFromPdfDict(tg, doc));
}
}
}
}
return images;
}
The above will only work with JPEGs. Excluding inline images and embedded files, you need to go through the objects of subtype IMAGE, then look at the filter and take the appropriate action. Here's an example, assuming we have a PdfObject of subtype IMAGE:
PdfReader pdf = new PdfReader("c:\\temp\\exp0.pdf");
int xo=pdf.XrefSize;
for (int i=0;i<xo;i++)
{
PdfObject obj=pdf.GetPdfObject(i);
if (obj!=null && obj.IsStream())
{
PdfDictionary pd=(PdfDictionary)obj;
if (pd.Contains(PdfName.SUBTYPE) && pd.Get(PdfName.SUBTYPE).ToString()=="/Image")
{
string filter=pd.Get(PdfName.FILTER).ToString();
string width=pd.Get(PdfName.WIDTH).ToString();
string height=pd.Get(PdfName.HEIGHT).ToString();
string bpp=pd.Get(PdfName.BITSPERCOMPONENT).ToString();
string extent=".";
byte [] img=null;
switch (filter)
{
case "/FlateDecode":
byte[] arr=PdfReader.FlateDecode(PdfReader.GetStreamBytesRaw((PRStream)obj),true);
Bitmap bmp=new Bitmap(Int32.Parse(width),Int32.Parse(height),PixelFormat.Format24bppRgb);
BitmapData bmd=bmp.LockBits(new Rectangle(0,0,Int32.Parse(width),Int32.Parse(height)),ImageLockMode.WriteOnly,
PixelFormat.Format24bppRgb);
Marshal.Copy(arr,0,bmd.Scan0,arr.Length);
bmp.UnlockBits(bmd);
bmp.Save("c:\\temp\\bmp1.png",ImageFormat.Png);
break;
default:
break;
}
}
}
}
This will mess the color up because of the Microsoft BGR, of course, but I wanted to keep it short. Do something similar for "/CCITTFaxDecode", etc.